diff options
868 files changed, 14583 insertions, 11844 deletions
diff --git a/.clang-format b/.clang-format index a8bde41..88bfbd3 100644 --- a/.clang-format +++ b/.clang-format @@ -5,5 +5,4 @@ AlignOperands: false AlwaysBreakAfterReturnType: None AlwaysBreakAfterDefinitionReturnType: None ColumnLimit: 79 -Standard: Cpp03 ... diff --git a/.clang-tidy b/.clang-tidy index 0f14f6b..a6e2597 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -6,12 +6,17 @@ misc-*,\ -misc-macro-parentheses,\ -misc-misplaced-widening-cast,\ -misc-static-assert,\ -modernize-make-shared,\ -modernize-make-unique,\ -modernize-redundant-void-arg,\ -modernize-use-bool-literals,\ -modernize-use-nullptr,\ -modernize-use-override,\ +modernize-*,\ +-modernize-deprecated-headers,\ +-modernize-pass-by-value,\ +-modernize-raw-string-literal,\ +-modernize-use-auto,\ +-modernize-use-default-member-init,\ +-modernize-use-emplace,\ +-modernize-use-equals-default,\ +-modernize-use-equals-delete,\ +-modernize-use-transparent-functors,\ +-modernize-use-using,\ performance-*,\ -performance-inefficient-string-concatenation,\ readability-*,\ diff --git a/Auxiliary/vim/cmake.vim.in b/Auxiliary/vim/cmake.vim.in index 389d9e4..2461e0b 100644 --- a/Auxiliary/vim/cmake.vim.in +++ b/Auxiliary/vim/cmake.vim.in @@ -1,10 +1,13 @@ " vim: set nowrap: " Vim syntax file +" Program: CMake - Cross-Platform Makefile Generator +" Version: @VERSION@ " Language: CMake -" Author: Andy Cedilnik <andy.cedilnik@kitware.com>, Nicholas Hutchinson <nshutchinson@gmail.com>, Patrick Boettcher <patrick.boettcher@posteo.de> -" Maintainer: Karthik Krishnan <karthik.krishnan@kitware.com> -" Last Change: $Date$ -" Version: $Revision$ +" Author: Andy Cedilnik <andy.cedilnik@kitware.com>, +" Nicholas Hutchinson <nshutchinson@gmail.com>, +" Patrick Boettcher <patrick.boettcher@posteo.de> +" Maintainer: Dimitri Merejkowsky <d.merej@gmail.com> +" Former Maintainer: Karthik Krishnan <karthik.krishnan@kitware.com> " " Licence: The CMake license applies to this file. See " https://cmake.org/licensing @@ -13,8 +16,10 @@ if exists("b:current_syntax") finish endif +let s:keepcpo= &cpo +set cpo&vim -syn region cmakeComment start="#" end="$" contains=cmakeTodo,@Spell +syn region cmakeComment start="#" end="$" contains=cmakeTodo,cmakeLuaComment,@Spell syn region cmakeLuaComment start="\[\z(=*\)\[" end="\]\z1\]" contains=cmakeTodo,@Spell syn match cmakeEscaped /\(\\\\\|\\"\|\\n\|\\t\)/ contained @@ -22,18 +27,18 @@ syn region cmakeRegistry start="\[" end="]" contained oneline contains=cmakeTodo syn region cmakeGeneratorExpression start="$<" end=">" contained oneline contains=cmakeVariableValue,cmakeProperty,cmakeGeneratorExpressions,cmakeTodo -syn region cmakeString start='"' end='"' contained contains=cmakeTodo,cmakeVariableValue +syn region cmakeString start='"' end='"' contained contains=cmakeTodo,cmakeVariableValue,cmakeEscaped syn region cmakeVariableValue start="${" end="}" contained oneline contains=cmakeVariable,cmakeTodo syn region cmakeEnvironment start="$ENV{" end="}" contained oneline contains=cmakeTodo -syn region cmakeArguments start="(" end=")" contains=ALLBUT,cmakeArguments,cmakeTodo +syn region cmakeArguments start="(" end=")" contains=ALLBUT,cmakeCommand,cmakeCommandConditional,cmakeCommandRepeat,cmakeCommandDeprecated,cmakeArguments,cmakeTodo syn case match syn keyword cmakeProperty contained - \ ABSTRACT ADDITIONAL_MAKE_CLEAN_FILES ADVANCED ALIASED_TARGET ALLOW_DUPLICATE_CUSTOM_TARGETS ANDROID_ANT_ADDITIONAL_OPTIONS ANDROID_API ANDROID_API_MIN ANDROID_ARCH ANDROID_ASSETS_DIRECTORIES ANDROID_GUI ANDROID_JAR_DEPENDENCIES ANDROID_JAR_DIRECTORIES ANDROID_JAVA_SOURCE_DIR ANDROID_NATIVE_LIB_DEPENDENCIES ANDROID_NATIVE_LIB_DIRECTORIES ANDROID_PROCESS_MAX ANDROID_PROGUARD ANDROID_PROGUARD_CONFIG_PATH ANDROID_SECURE_PROPS_PATH ANDROID_SKIP_ANT_STEP ANDROID_STL_TYPE ARCHIVE_OUTPUT_DIRECTORY ARCHIVE_OUTPUT_DIRECTORY_DEBUG ARCHIVE_OUTPUT_DIRECTORY_RELEASE ARCHIVE_OUTPUT_NAME ARCHIVE_OUTPUT_NAME_DEBUG ARCHIVE_OUTPUT_NAME_RELEASE ATTACHED_FILES ATTACHED_FILES_ON_FAIL AUTOGEN_TARGETS_FOLDER AUTOGEN_TARGET_DEPENDS AUTOMOC AUTOMOC_MOC_OPTIONS AUTOMOC_TARGETS_FOLDER AUTORCC AUTORCC_OPTIONS AUTOUIC AUTOUIC_OPTIONS BINARY_DIR BUILD_WITH_INSTALL_RPATH BUNDLE BUNDLE_EXTENSION CACHE_VARIABLES CLEAN_NO_CUSTOM CMAKE_CONFIGURE_DEPENDS CMAKE_CXX_KNOWN_FEATURES CMAKE_C_KNOWN_FEATURES COMPATIBLE_INTERFACE_BOOL COMPATIBLE_INTERFACE_NUMBER_MAX COMPATIBLE_INTERFACE_NUMBER_MIN COMPATIBLE_INTERFACE_STRING COMPILE_DEFINITIONS COMPILE_DEFINITIONS_DEBUG COMPILE_DEFINITIONS_RELEASE COMPILE_FEATURES COMPILE_FLAGS COMPILE_OPTIONS COMPILE_PDB_NAME COMPILE_PDB_NAME_DEBUG COMPILE_PDB_NAME_RELEASE COMPILE_PDB_OUTPUT_DIRECTORY COMPILE_PDB_OUTPUT_DIRECTORY_DEBUG COMPILE_PDB_OUTPUT_DIRECTORY_RELEASE COST CPACK_DESKTOP_SHORTCUTS CPACK_NEVER_OVERWRITE CPACK_PERMANENT CPACK_STARTUP_SHORTCUTS CPACK_START_MENU_SHORTCUTS CPACK_WIX_ACL CROSSCOMPILING_EMULATOR CXX_EXTENSIONS CXX_STANDARD CXX_STANDARD_REQUIRED C_EXTENSIONS C_STANDARD C_STANDARD_REQUIRED DEBUG_CONFIGURATIONS DEBUG_POSTFIX DEFINE_SYMBOL DEFINITIONS DEPENDS DISABLED_FEATURES ECLIPSE_EXTRA_NATURES ENABLED_FEATURES ENABLED_LANGUAGES ENABLE_EXPORTS ENVIRONMENT EXCLUDE_FROM_ALL EXCLUDE_FROM_DEFAULT_BUILD EXCLUDE_FROM_DEFAULT_BUILD_DEBUG EXCLUDE_FROM_DEFAULT_BUILD_RELEASE EXPORT_NAME EXTERNAL_OBJECT EchoString FAIL_REGULAR_EXPRESSION FIND_LIBRARY_USE_LIB64_PATHS FIND_LIBRARY_USE_OPENBSD_VERSIONING FOLDER FRAMEWORK FRAMEWORK_VERSION Fortran_FORMAT Fortran_MODULE_DIRECTORY GENERATED GENERATOR_FILE_NAME GLOBAL_DEPENDS_DEBUG_MODE GLOBAL_DEPENDS_NO_CYCLES GNUtoMS HAS_CXX HEADER_FILE_ONLY HELPSTRING IMPLICIT_DEPENDS_INCLUDE_TRANSFORM IMPORTED IMPORTED_CONFIGURATIONS IMPORTED_IMPLIB IMPORTED_IMPLIB_DEBUG IMPORTED_IMPLIB_RELEASE IMPORTED_LINK_DEPENDENT_LIBRARIES IMPORTED_LINK_DEPENDENT_LIBRARIES_DEBUG IMPORTED_LINK_DEPENDENT_LIBRARIES_RELEASE IMPORTED_LINK_INTERFACE_LANGUAGES IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE IMPORTED_LINK_INTERFACE_LIBRARIES IMPORTED_LINK_INTERFACE_LIBRARIES_DEBUG IMPORTED_LINK_INTERFACE_LIBRARIES_RELEASE IMPORTED_LINK_INTERFACE_MULTIPLICITY IMPORTED_LINK_INTERFACE_MULTIPLICITY_DEBUG IMPORTED_LINK_INTERFACE_MULTIPLICITY_RELEASE IMPORTED_LOCATION IMPORTED_LOCATION_DEBUG IMPORTED_LOCATION_RELEASE IMPORTED_NO_SONAME IMPORTED_NO_SONAME_DEBUG IMPORTED_NO_SONAME_RELEASE IMPORTED_SONAME IMPORTED_SONAME_DEBUG IMPORTED_SONAME_RELEASE IMPORT_PREFIX IMPORT_SUFFIX INCLUDE_DIRECTORIES INCLUDE_REGULAR_EXPRESSION INSTALL_NAME_DIR INSTALL_RPATH INSTALL_RPATH_USE_LINK_PATH INTERFACE_AUTOUIC_OPTIONS INTERFACE_COMPILE_DEFINITIONS INTERFACE_COMPILE_FEATURES INTERFACE_COMPILE_OPTIONS INTERFACE_INCLUDE_DIRECTORIES INTERFACE_LINK_LIBRARIES INTERFACE_POSITION_INDEPENDENT_CODE INTERFACE_SOURCES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES INTERPROCEDURAL_OPTIMIZATION INTERPROCEDURAL_OPTIMIZATION_DEBUG INTERPROCEDURAL_OPTIMIZATION_RELEASE IN_TRY_COMPILE JOB_POOLS JOB_POOL_COMPILE JOB_POOL_LINK KEEP_EXTENSION LABELS LANGUAGE LIBRARY_OUTPUT_DIRECTORY LIBRARY_OUTPUT_DIRECTORY_DEBUG LIBRARY_OUTPUT_DIRECTORY_RELEASE LIBRARY_OUTPUT_NAME LIBRARY_OUTPUT_NAME_DEBUG LIBRARY_OUTPUT_NAME_RELEASE LINKER_LANGUAGE LINK_DEPENDS LINK_DEPENDS_NO_SHARED LINK_DIRECTORIES LINK_FLAGS LINK_FLAGS_DEBUG LINK_FLAGS_RELEASE LINK_INTERFACE_LIBRARIES LINK_INTERFACE_LIBRARIES_DEBUG LINK_INTERFACE_LIBRARIES_RELEASE LINK_INTERFACE_MULTIPLICITY LINK_INTERFACE_MULTIPLICITY_DEBUG LINK_INTERFACE_MULTIPLICITY_RELEASE LINK_LIBRARIES LINK_SEARCH_END_STATIC LINK_SEARCH_START_STATIC LISTFILE_STACK LOCATION LOCATION_DEBUG LOCATION_RELEASE MACOSX_BUNDLE MACOSX_BUNDLE_INFO_PLIST MACOSX_FRAMEWORK_INFO_PLIST MACOSX_PACKAGE_LOCATION MACOSX_RPATH MACROS MAP_IMPORTED_CONFIG_DEBUG MAP_IMPORTED_CONFIG_RELEASE MEASUREMENT MODIFIED NAME NO_SONAME NO_SYSTEM_FROM_IMPORTED OBJECT_DEPENDS OBJECT_OUTPUTS OSX_ARCHITECTURES OSX_ARCHITECTURES_DEBUG OSX_ARCHITECTURES_RELEASE OUTPUT_NAME OUTPUT_NAME_DEBUG OUTPUT_NAME_RELEASE PACKAGES_FOUND PACKAGES_NOT_FOUND PARENT_DIRECTORY PASS_REGULAR_EXPRESSION PDB_NAME PDB_NAME_DEBUG PDB_NAME_RELEASE PDB_OUTPUT_DIRECTORY PDB_OUTPUT_DIRECTORY_DEBUG PDB_OUTPUT_DIRECTORY_RELEASE POSITION_INDEPENDENT_CODE POST_INSTALL_SCRIPT PREDEFINED_TARGETS_FOLDER PREFIX PRE_INSTALL_SCRIPT PRIVATE_HEADER PROCESSORS PROJECT_LABEL PUBLIC_HEADER REPORT_UNDEFINED_PROPERTIES REQUIRED_FILES RESOURCE RESOURCE_LOCK RULE_LAUNCH_COMPILE RULE_LAUNCH_CUSTOM RULE_LAUNCH_LINK RULE_MESSAGES RUNTIME_OUTPUT_DIRECTORY RUNTIME_OUTPUT_DIRECTORY_DEBUG RUNTIME_OUTPUT_DIRECTORY_RELEASE RUNTIME_OUTPUT_NAME RUNTIME_OUTPUT_NAME_DEBUG RUNTIME_OUTPUT_NAME_RELEASE RUN_SERIAL SKIP_BUILD_RPATH SKIP_RETURN_CODE SOURCES SOURCE_DIR SOVERSION STATIC_LIBRARY_FLAGS STATIC_LIBRARY_FLAGS_DEBUG STATIC_LIBRARY_FLAGS_RELEASE STRINGS SUFFIX SYMBOLIC TARGET_ARCHIVES_MAY_BE_SHARED_LIBS TARGET_MESSAGES TARGET_SUPPORTS_SHARED_LIBS TEST_INCLUDE_FILE TIMEOUT TYPE USE_FOLDERS VALUE VARIABLES VERSION VISIBILITY_INLINES_HIDDEN VS_DEPLOYMENT_CONTENT VS_DEPLOYMENT_LOCATION VS_DESKTOP_EXTENSIONS_VERSION VS_DOTNET_REFERENCES VS_DOTNET_TARGET_FRAMEWORK_VERSION VS_GLOBAL_KEYWORD VS_GLOBAL_PROJECT_TYPES VS_GLOBAL_ROOTNAMESPACE VS_IOT_EXTENSIONS_VERSION VS_IOT_STARTUP_TASK VS_KEYWORD VS_MOBILE_EXTENSIONS_VERSION VS_SCC_AUXPATH VS_SCC_LOCALPATH VS_SCC_PROJECTNAME VS_SCC_PROVIDER VS_SHADER_ENTRYPOINT VS_SHADER_FLAGS VS_SHADER_MODEL VS_SHADER_TYPE VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION VS_WINRT_COMPONENT VS_WINRT_EXTENSIONS VS_WINRT_REFERENCES VS_XAML_TYPE WILL_FAIL WIN32_EXECUTABLE WINDOWS_EXPORT_ALL_SYMBOLS WORKING_DIRECTORY WRAP_EXCLUDE XCODE_EXPLICIT_FILE_TYPE XCODE_LAST_KNOWN_FILE_TYPE XCTEST +@PROPERTIES@ syn keyword cmakeVariable contained @VARIABLE_LIST@ @@ -91,3 +96,8 @@ hi def link cmakeVariable Identifier @KEYWORDS_HIGHLIGHT@ let b:current_syntax = "cmake" + +let &cpo = s:keepcpo +unlet s:keepcpo + +"EOF" diff --git a/Auxiliary/vim/extract-upper-case.pl b/Auxiliary/vim/extract-upper-case.pl index ea77cbb..9e3c439 100755 --- a/Auxiliary/vim/extract-upper-case.pl +++ b/Auxiliary/vim/extract-upper-case.pl @@ -29,8 +29,8 @@ push @modules, "ExternalProject"; # variables open(CMAKE, "$cmake --help-variable-list|") or die "could not run cmake"; while (<CMAKE>) { + next if /\</; # skip if containing < or > chomp; - next if /\</; # skip VARIABLES which contained <>-"templates" push @variables, $_; } close(CMAKE); @@ -70,11 +70,24 @@ my @generator_expr = extract_upper("$cmake --help-manual cmake-generator-express # properties open(CMAKE, "$cmake --help-property-list|"); while (<CMAKE>) { + next if /\</; # skip if containing < or > chomp; push @properties, $_; } close(CMAKE); +# transform all properties in a hash +my %properties = map { $_ => 1 } @properties; + +# version +open(CMAKE, "$cmake --version|"); +my $version = 'unknown'; +while (<CMAKE>) { + chomp; + $version = $_ if /cmake version/; +} +close(CMAKE); + # generate cmake.vim open(IN, "<cmake.vim.in") or die "could not read cmake.vim.in"; open(OUT, ">syntax/cmake.vim") or die "could not write to syntax/cmake.vim"; @@ -102,6 +115,8 @@ while(<IN>) print OUT " " x 12 , "\\ ", join(" ", sort keys %loop), "\n"; } elsif ($1 eq "DEPRECATED") { print OUT " " x 12 , "\\ ", join(" ", sort keys %deprecated), "\n"; + } elsif ($1 eq "PROPERTIES") { + print OUT " " x 12 , "\\ ", join(" ", sort keys %properties), "\n"; } elsif ($1 eq "KEYWORDS") { foreach my $k (sort keys %keywords) { print OUT "syn keyword cmakeKW$k contained\n"; @@ -111,6 +126,9 @@ while(<IN>) } } elsif ($1 eq "KEYWORDS_HIGHLIGHT") { print OUT join("\n", @keyword_hi), "\n"; + } elsif ($1 eq "VERSION") { + $_ =~ s/\@VERSION\@/$version/; + print OUT $_; } else { print "ERROR do not know how to replace $1\n"; } @@ -128,7 +146,6 @@ sub extract_upper open(KW, $input); while (<KW>) { - foreach my $w (m/\b([A-Z_]{2,})\b/g) { next if exists $variables{$w} or # skip if it is a variable diff --git a/Auxiliary/vim/indent/cmake.vim b/Auxiliary/vim/indent/cmake.vim index 6063e43..76aff64 100644 --- a/Auxiliary/vim/indent/cmake.vim +++ b/Auxiliary/vim/indent/cmake.vim @@ -14,7 +14,6 @@ if exists("b:did_indent") endif let b:did_indent = 1 -setlocal et setlocal indentexpr=CMakeGetIndent(v:lnum) setlocal indentkeys+==ENDIF(,ENDFOREACH(,ENDMACRO(,ELSE(,ELSEIF(,ENDWHILE( diff --git a/Auxiliary/vim/syntax/cmake.vim b/Auxiliary/vim/syntax/cmake.vim index b06fa42..f6a73c3 100644 --- a/Auxiliary/vim/syntax/cmake.vim +++ b/Auxiliary/vim/syntax/cmake.vim @@ -1,10 +1,13 @@ " vim: set nowrap: " Vim syntax file +" Program: CMake - Cross-Platform Makefile Generator +" Version: cmake version 3.9.20170830-ge0713 " Language: CMake -" Author: Andy Cedilnik <andy.cedilnik@kitware.com>, Nicholas Hutchinson <nshutchinson@gmail.com>, Patrick Boettcher <patrick.boettcher@posteo.de> -" Maintainer: Karthik Krishnan <karthik.krishnan@kitware.com> -" Last Change: $Date$ -" Version: $Revision$ +" Author: Andy Cedilnik <andy.cedilnik@kitware.com>, +" Nicholas Hutchinson <nshutchinson@gmail.com>, +" Patrick Boettcher <patrick.boettcher@posteo.de> +" Maintainer: Dimitri Merejkowsky <d.merej@gmail.com> +" Former Maintainer: Karthik Krishnan <karthik.krishnan@kitware.com> " " Licence: The CMake license applies to this file. See " https://cmake.org/licensing @@ -13,8 +16,10 @@ if exists("b:current_syntax") finish endif +let s:keepcpo= &cpo +set cpo&vim -syn region cmakeComment start="#" end="$" contains=cmakeTodo,@Spell +syn region cmakeComment start="#" end="$" contains=cmakeTodo,cmakeLuaComment,@Spell syn region cmakeLuaComment start="\[\z(=*\)\[" end="\]\z1\]" contains=cmakeTodo,@Spell syn match cmakeEscaped /\(\\\\\|\\"\|\\n\|\\t\)/ contained @@ -22,26 +27,27 @@ syn region cmakeRegistry start="\[" end="]" contained oneline contains=cmakeTodo syn region cmakeGeneratorExpression start="$<" end=">" contained oneline contains=cmakeVariableValue,cmakeProperty,cmakeGeneratorExpressions,cmakeTodo -syn region cmakeString start='"' end='"' contained contains=cmakeTodo,cmakeVariableValue +syn region cmakeString start='"' end='"' contained contains=cmakeTodo,cmakeVariableValue,cmakeEscaped syn region cmakeVariableValue start="${" end="}" contained oneline contains=cmakeVariable,cmakeTodo syn region cmakeEnvironment start="$ENV{" end="}" contained oneline contains=cmakeTodo -syn region cmakeArguments start="(" end=")" contains=ALLBUT,cmakeArguments,cmakeTodo +syn region cmakeArguments start="(" end=")" contains=ALLBUT,cmakeCommand,cmakeCommandConditional,cmakeCommandRepeat,cmakeCommandDeprecated,cmakeArguments,cmakeTodo syn case match + syn keyword cmakeProperty contained - \ ABSTRACT ADDITIONAL_MAKE_CLEAN_FILES ADVANCED ALIASED_TARGET ALLOW_DUPLICATE_CUSTOM_TARGETS ANDROID_ANT_ADDITIONAL_OPTIONS ANDROID_API ANDROID_API_MIN ANDROID_ARCH ANDROID_ASSETS_DIRECTORIES ANDROID_GUI ANDROID_JAR_DEPENDENCIES ANDROID_JAR_DIRECTORIES ANDROID_JAVA_SOURCE_DIR ANDROID_NATIVE_LIB_DEPENDENCIES ANDROID_NATIVE_LIB_DIRECTORIES ANDROID_PROCESS_MAX ANDROID_PROGUARD ANDROID_PROGUARD_CONFIG_PATH ANDROID_SECURE_PROPS_PATH ANDROID_SKIP_ANT_STEP ANDROID_STL_TYPE ARCHIVE_OUTPUT_DIRECTORY ARCHIVE_OUTPUT_DIRECTORY_DEBUG ARCHIVE_OUTPUT_DIRECTORY_RELEASE ARCHIVE_OUTPUT_NAME ARCHIVE_OUTPUT_NAME_DEBUG ARCHIVE_OUTPUT_NAME_RELEASE ATTACHED_FILES ATTACHED_FILES_ON_FAIL AUTOGEN_TARGETS_FOLDER AUTOGEN_TARGET_DEPENDS AUTOMOC AUTOMOC_MOC_OPTIONS AUTOMOC_TARGETS_FOLDER AUTORCC AUTORCC_OPTIONS AUTOUIC AUTOUIC_OPTIONS BINARY_DIR BUILD_WITH_INSTALL_RPATH BUNDLE BUNDLE_EXTENSION CACHE_VARIABLES CLEAN_NO_CUSTOM CMAKE_CONFIGURE_DEPENDS CMAKE_CXX_KNOWN_FEATURES CMAKE_C_KNOWN_FEATURES CMAKE_DIRECTORY_LABELS COMPATIBLE_INTERFACE_BOOL COMPATIBLE_INTERFACE_NUMBER_MAX COMPATIBLE_INTERFACE_NUMBER_MIN COMPATIBLE_INTERFACE_STRING COMPILE_DEFINITIONS COMPILE_DEFINITIONS_DEBUG COMPILE_DEFINITIONS_RELEASE COMPILE_FEATURES COMPILE_FLAGS COMPILE_OPTIONS COMPILE_PDB_NAME COMPILE_PDB_NAME_DEBUG COMPILE_PDB_NAME_RELEASE COMPILE_PDB_OUTPUT_DIRECTORY COMPILE_PDB_OUTPUT_DIRECTORY_DEBUG COMPILE_PDB_OUTPUT_DIRECTORY_RELEASE COST CPACK_DESKTOP_SHORTCUTS CPACK_NEVER_OVERWRITE CPACK_PERMANENT CPACK_STARTUP_SHORTCUTS CPACK_START_MENU_SHORTCUTS CPACK_WIX_ACL CROSSCOMPILING_EMULATOR CXX_EXTENSIONS CXX_STANDARD CXX_STANDARD_REQUIRED C_EXTENSIONS C_STANDARD C_STANDARD_REQUIRED DEBUG_CONFIGURATIONS DEBUG_POSTFIX DEFINE_SYMBOL DEFINITIONS DEPENDS DISABLED_FEATURES ECLIPSE_EXTRA_NATURES ENABLED_FEATURES ENABLED_LANGUAGES ENABLE_EXPORTS ENVIRONMENT EXCLUDE_FROM_ALL EXCLUDE_FROM_DEFAULT_BUILD EXCLUDE_FROM_DEFAULT_BUILD_DEBUG EXCLUDE_FROM_DEFAULT_BUILD_RELEASE EXPORT_NAME EXTERNAL_OBJECT EchoString FAIL_REGULAR_EXPRESSION FIND_LIBRARY_USE_LIB64_PATHS FIND_LIBRARY_USE_OPENBSD_VERSIONING FOLDER FRAMEWORK FRAMEWORK_VERSION Fortran_FORMAT Fortran_MODULE_DIRECTORY GENERATED GENERATOR_FILE_NAME GLOBAL_DEPENDS_DEBUG_MODE GLOBAL_DEPENDS_NO_CYCLES GNUtoMS HAS_CXX HEADER_FILE_ONLY HELPSTRING IMPLICIT_DEPENDS_INCLUDE_TRANSFORM IMPORTED IMPORTED_CONFIGURATIONS IMPORTED_IMPLIB IMPORTED_IMPLIB_DEBUG IMPORTED_IMPLIB_RELEASE IMPORTED_LINK_DEPENDENT_LIBRARIES IMPORTED_LINK_DEPENDENT_LIBRARIES_DEBUG IMPORTED_LINK_DEPENDENT_LIBRARIES_RELEASE IMPORTED_LINK_INTERFACE_LANGUAGES IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE IMPORTED_LINK_INTERFACE_LIBRARIES IMPORTED_LINK_INTERFACE_LIBRARIES_DEBUG IMPORTED_LINK_INTERFACE_LIBRARIES_RELEASE IMPORTED_LINK_INTERFACE_MULTIPLICITY IMPORTED_LINK_INTERFACE_MULTIPLICITY_DEBUG IMPORTED_LINK_INTERFACE_MULTIPLICITY_RELEASE IMPORTED_LOCATION IMPORTED_LOCATION_DEBUG IMPORTED_LOCATION_RELEASE IMPORTED_NO_SONAME IMPORTED_NO_SONAME_DEBUG IMPORTED_NO_SONAME_RELEASE IMPORTED_SONAME IMPORTED_SONAME_DEBUG IMPORTED_SONAME_RELEASE IMPORT_PREFIX IMPORT_SUFFIX INCLUDE_DIRECTORIES INCLUDE_REGULAR_EXPRESSION INSTALL_NAME_DIR INSTALL_RPATH INSTALL_RPATH_USE_LINK_PATH INTERFACE_AUTOUIC_OPTIONS INTERFACE_COMPILE_DEFINITIONS INTERFACE_COMPILE_FEATURES INTERFACE_COMPILE_OPTIONS INTERFACE_INCLUDE_DIRECTORIES INTERFACE_LINK_LIBRARIES INTERFACE_POSITION_INDEPENDENT_CODE INTERFACE_SOURCES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES INTERPROCEDURAL_OPTIMIZATION INTERPROCEDURAL_OPTIMIZATION_DEBUG INTERPROCEDURAL_OPTIMIZATION_RELEASE IN_TRY_COMPILE JOB_POOLS JOB_POOL_COMPILE JOB_POOL_LINK KEEP_EXTENSION LABELS LANGUAGE LIBRARY_OUTPUT_DIRECTORY LIBRARY_OUTPUT_DIRECTORY_DEBUG LIBRARY_OUTPUT_DIRECTORY_RELEASE LIBRARY_OUTPUT_NAME LIBRARY_OUTPUT_NAME_DEBUG LIBRARY_OUTPUT_NAME_RELEASE LINKER_LANGUAGE LINK_DEPENDS LINK_DEPENDS_NO_SHARED LINK_DIRECTORIES LINK_FLAGS LINK_FLAGS_DEBUG LINK_FLAGS_RELEASE LINK_INTERFACE_LIBRARIES LINK_INTERFACE_LIBRARIES_DEBUG LINK_INTERFACE_LIBRARIES_RELEASE LINK_INTERFACE_MULTIPLICITY LINK_INTERFACE_MULTIPLICITY_DEBUG LINK_INTERFACE_MULTIPLICITY_RELEASE LINK_LIBRARIES LINK_SEARCH_END_STATIC LINK_SEARCH_START_STATIC LISTFILE_STACK LOCATION LOCATION_DEBUG LOCATION_RELEASE MACOSX_BUNDLE MACOSX_BUNDLE_INFO_PLIST MACOSX_FRAMEWORK_INFO_PLIST MACOSX_PACKAGE_LOCATION MACOSX_RPATH MACROS MAP_IMPORTED_CONFIG_DEBUG MAP_IMPORTED_CONFIG_RELEASE MEASUREMENT MODIFIED NAME NO_SONAME NO_SYSTEM_FROM_IMPORTED OBJECT_DEPENDS OBJECT_OUTPUTS OSX_ARCHITECTURES OSX_ARCHITECTURES_DEBUG OSX_ARCHITECTURES_RELEASE OUTPUT_NAME OUTPUT_NAME_DEBUG OUTPUT_NAME_RELEASE PACKAGES_FOUND PACKAGES_NOT_FOUND PARENT_DIRECTORY PASS_REGULAR_EXPRESSION PDB_NAME PDB_NAME_DEBUG PDB_NAME_RELEASE PDB_OUTPUT_DIRECTORY PDB_OUTPUT_DIRECTORY_DEBUG PDB_OUTPUT_DIRECTORY_RELEASE POSITION_INDEPENDENT_CODE POST_INSTALL_SCRIPT PREDEFINED_TARGETS_FOLDER PREFIX PRE_INSTALL_SCRIPT PRIVATE_HEADER PROCESSORS PROJECT_LABEL PUBLIC_HEADER REPORT_UNDEFINED_PROPERTIES REQUIRED_FILES RESOURCE RESOURCE_LOCK RULE_LAUNCH_COMPILE RULE_LAUNCH_CUSTOM RULE_LAUNCH_LINK RULE_MESSAGES RUNTIME_OUTPUT_DIRECTORY RUNTIME_OUTPUT_DIRECTORY_DEBUG RUNTIME_OUTPUT_DIRECTORY_RELEASE RUNTIME_OUTPUT_NAME RUNTIME_OUTPUT_NAME_DEBUG RUNTIME_OUTPUT_NAME_RELEASE RUN_SERIAL SKIP_BUILD_RPATH SKIP_RETURN_CODE SOURCES SOURCE_DIR SOVERSION STATIC_LIBRARY_FLAGS STATIC_LIBRARY_FLAGS_DEBUG STATIC_LIBRARY_FLAGS_RELEASE STRINGS SUFFIX SYMBOLIC TARGET_ARCHIVES_MAY_BE_SHARED_LIBS TARGET_MESSAGES TARGET_SUPPORTS_SHARED_LIBS TEST_INCLUDE_FILE TIMEOUT TYPE USE_FOLDERS VALUE VARIABLES VERSION VISIBILITY_INLINES_HIDDEN VS_DEPLOYMENT_CONTENT VS_DEPLOYMENT_LOCATION VS_DESKTOP_EXTENSIONS_VERSION VS_DOTNET_REFERENCES VS_DOTNET_TARGET_FRAMEWORK_VERSION VS_GLOBAL_KEYWORD VS_GLOBAL_PROJECT_TYPES VS_GLOBAL_ROOTNAMESPACE VS_IOT_EXTENSIONS_VERSION VS_IOT_STARTUP_TASK VS_KEYWORD VS_MOBILE_EXTENSIONS_VERSION VS_SCC_AUXPATH VS_SCC_LOCALPATH VS_SCC_PROJECTNAME VS_SCC_PROVIDER VS_SHADER_ENTRYPOINT VS_SHADER_FLAGS VS_SHADER_MODEL VS_SHADER_TYPE VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION VS_WINRT_COMPONENT VS_WINRT_EXTENSIONS VS_WINRT_REFERENCES VS_XAML_TYPE WILL_FAIL WIN32_EXECUTABLE WINDOWS_EXPORT_ALL_SYMBOLS WORKING_DIRECTORY WRAP_EXCLUDE XCODE_EXPLICIT_FILE_TYPE XCODE_LAST_KNOWN_FILE_TYPE XCTEST + \ ABSTRACT ADDITIONAL_MAKE_CLEAN_FILES ADVANCED ALIASED_TARGET ALLOW_DUPLICATE_CUSTOM_TARGETS ANDROID_ANT_ADDITIONAL_OPTIONS ANDROID_API ANDROID_API_MIN ANDROID_ARCH ANDROID_ASSETS_DIRECTORIES ANDROID_GUI ANDROID_JAR_DEPENDENCIES ANDROID_JAR_DIRECTORIES ANDROID_JAVA_SOURCE_DIR ANDROID_NATIVE_LIB_DEPENDENCIES ANDROID_NATIVE_LIB_DIRECTORIES ANDROID_PROCESS_MAX ANDROID_PROGUARD ANDROID_PROGUARD_CONFIG_PATH ANDROID_SECURE_PROPS_PATH ANDROID_SKIP_ANT_STEP ANDROID_STL_TYPE ARCHIVE_OUTPUT_DIRECTORY ARCHIVE_OUTPUT_NAME ATTACHED_FILES ATTACHED_FILES_ON_FAIL AUTOGEN_BUILD_DIR AUTOGEN_SOURCE_GROUP AUTOGEN_TARGETS_FOLDER AUTOGEN_TARGET_DEPENDS AUTOMOC AUTOMOC_DEPEND_FILTERS AUTOMOC_MACRO_NAMES AUTOMOC_MOC_OPTIONS AUTOMOC_SOURCE_GROUP AUTOMOC_TARGETS_FOLDER AUTORCC AUTORCC_OPTIONS AUTORCC_SOURCE_GROUP AUTOUIC AUTOUIC_OPTIONS AUTOUIC_SEARCH_PATHS BINARY_DIR BUILDSYSTEM_TARGETS BUILD_RPATH BUILD_WITH_INSTALL_NAME_DIR BUILD_WITH_INSTALL_RPATH BUNDLE BUNDLE_EXTENSION CACHE_VARIABLES CLEAN_NO_CUSTOM CMAKE_CONFIGURE_DEPENDS CMAKE_CXX_KNOWN_FEATURES CMAKE_C_KNOWN_FEATURES COMPATIBLE_INTERFACE_BOOL COMPATIBLE_INTERFACE_NUMBER_MAX COMPATIBLE_INTERFACE_NUMBER_MIN COMPATIBLE_INTERFACE_STRING COMPILE_DEFINITIONS COMPILE_FEATURES COMPILE_FLAGS COMPILE_OPTIONS COMPILE_PDB_NAME COMPILE_PDB_OUTPUT_DIRECTORY COST CPACK_DESKTOP_SHORTCUTS CPACK_NEVER_OVERWRITE CPACK_PERMANENT CPACK_STARTUP_SHORTCUTS CPACK_START_MENU_SHORTCUTS CPACK_WIX_ACL CROSSCOMPILING_EMULATOR CUDA_EXTENSIONS CUDA_PTX_COMPILATION CUDA_RESOLVE_DEVICE_SYMBOLS CUDA_SEPARABLE_COMPILATION CUDA_STANDARD CUDA_STANDARD_REQUIRED CXX_EXTENSIONS CXX_STANDARD CXX_STANDARD_REQUIRED C_EXTENSIONS C_STANDARD C_STANDARD_REQUIRED DEBUG_CONFIGURATIONS DEBUG_POSTFIX DEFINE_SYMBOL DEFINITIONS DEPENDS DEPLOYMENT_REMOTE_DIRECTORY DISABLED DISABLED_FEATURES ECLIPSE_EXTRA_NATURES ENABLED_FEATURES ENABLED_LANGUAGES ENABLE_EXPORTS ENVIRONMENT EXCLUDE_FROM_ALL EXCLUDE_FROM_DEFAULT_BUILD EXPORT_NAME EXTERNAL_OBJECT EchoString FAIL_REGULAR_EXPRESSION FIND_LIBRARY_USE_LIB32_PATHS FIND_LIBRARY_USE_LIB64_PATHS FIND_LIBRARY_USE_LIBX32_PATHS FIND_LIBRARY_USE_OPENBSD_VERSIONING FIXTURES_CLEANUP FIXTURES_REQUIRED FIXTURES_SETUP FOLDER FRAMEWORK FRAMEWORK_VERSION Fortran_FORMAT Fortran_MODULE_DIRECTORY GENERATED GENERATOR_FILE_NAME GENERATOR_IS_MULTI_CONFIG GLOBAL_DEPENDS_DEBUG_MODE GLOBAL_DEPENDS_NO_CYCLES GNUtoMS HAS_CXX HEADER_FILE_ONLY HELPSTRING IMPLICIT_DEPENDS_INCLUDE_TRANSFORM IMPORTED IMPORTED_CONFIGURATIONS IMPORTED_IMPLIB IMPORTED_LIBNAME IMPORTED_LINK_DEPENDENT_LIBRARIES IMPORTED_LINK_INTERFACE_LANGUAGES IMPORTED_LINK_INTERFACE_LIBRARIES IMPORTED_LINK_INTERFACE_MULTIPLICITY IMPORTED_LOCATION IMPORTED_NO_SONAME IMPORTED_OBJECTS IMPORTED_SONAME IMPORT_PREFIX IMPORT_SUFFIX INCLUDE_DIRECTORIES INCLUDE_REGULAR_EXPRESSION INSTALL_NAME_DIR INSTALL_RPATH INSTALL_RPATH_USE_LINK_PATH INTERFACE_AUTOUIC_OPTIONS INTERFACE_COMPILE_DEFINITIONS INTERFACE_COMPILE_FEATURES INTERFACE_COMPILE_OPTIONS INTERFACE_INCLUDE_DIRECTORIES INTERFACE_LINK_LIBRARIES INTERFACE_POSITION_INDEPENDENT_CODE INTERFACE_SOURCES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES INTERPROCEDURAL_OPTIMIZATION IN_TRY_COMPILE IOS_INSTALL_COMBINED JOB_POOLS JOB_POOL_COMPILE JOB_POOL_LINK KEEP_EXTENSION LABELS LANGUAGE LIBRARY_OUTPUT_DIRECTORY LIBRARY_OUTPUT_NAME LINKER_LANGUAGE LINK_DEPENDS LINK_DEPENDS_NO_SHARED LINK_DIRECTORIES LINK_FLAGS LINK_INTERFACE_LIBRARIES LINK_INTERFACE_MULTIPLICITY LINK_LIBRARIES LINK_SEARCH_END_STATIC LINK_SEARCH_START_STATIC LINK_WHAT_YOU_USE LISTFILE_STACK LOCATION MACOSX_BUNDLE MACOSX_BUNDLE_INFO_PLIST MACOSX_FRAMEWORK_INFO_PLIST MACOSX_PACKAGE_LOCATION MACOSX_RPATH MACROS MANUALLY_ADDED_DEPENDENCIES MEASUREMENT MODIFIED NAME NO_SONAME NO_SYSTEM_FROM_IMPORTED OBJECT_DEPENDS OBJECT_OUTPUTS OSX_ARCHITECTURES OUTPUT_NAME PACKAGES_FOUND PACKAGES_NOT_FOUND PARENT_DIRECTORY PASS_REGULAR_EXPRESSION PDB_NAME PDB_OUTPUT_DIRECTORY POSITION_INDEPENDENT_CODE POST_INSTALL_SCRIPT PREDEFINED_TARGETS_FOLDER PREFIX PRE_INSTALL_SCRIPT PRIVATE_HEADER PROCESSORS PROJECT_LABEL PUBLIC_HEADER REPORT_UNDEFINED_PROPERTIES REQUIRED_FILES RESOURCE RESOURCE_LOCK RULE_LAUNCH_COMPILE RULE_LAUNCH_CUSTOM RULE_LAUNCH_LINK RULE_MESSAGES RUNTIME_OUTPUT_DIRECTORY RUNTIME_OUTPUT_NAME RUN_SERIAL SKIP_AUTOGEN SKIP_AUTOMOC SKIP_AUTORCC SKIP_AUTOUIC SKIP_BUILD_RPATH SKIP_RETURN_CODE SOURCES SOURCE_DIR SOVERSION STATIC_LIBRARY_FLAGS STRINGS SUBDIRECTORIES SUFFIX SYMBOLIC TARGET_ARCHIVES_MAY_BE_SHARED_LIBS TARGET_MESSAGES TARGET_SUPPORTS_SHARED_LIBS TEST_INCLUDE_FILE TEST_INCLUDE_FILES TIMEOUT TIMEOUT_AFTER_MATCH TYPE USE_FOLDERS VALUE VARIABLES VERSION VISIBILITY_INLINES_HIDDEN VS_CONFIGURATION_TYPE VS_COPY_TO_OUT_DIR VS_DEBUGGER_WORKING_DIRECTORY VS_DEPLOYMENT_CONTENT VS_DEPLOYMENT_LOCATION VS_DESKTOP_EXTENSIONS_VERSION VS_DOTNET_REFERENCES VS_DOTNET_REFERENCES_COPY_LOCAL VS_DOTNET_TARGET_FRAMEWORK_VERSION VS_GLOBAL_KEYWORD VS_GLOBAL_PROJECT_TYPES VS_GLOBAL_ROOTNAMESPACE VS_INCLUDE_IN_VSIX VS_IOT_EXTENSIONS_VERSION VS_IOT_STARTUP_TASK VS_KEYWORD VS_MOBILE_EXTENSIONS_VERSION VS_RESOURCE_GENERATOR VS_SCC_AUXPATH VS_SCC_LOCALPATH VS_SCC_PROJECTNAME VS_SCC_PROVIDER VS_SDK_REFERENCES VS_SHADER_ENTRYPOINT VS_SHADER_FLAGS VS_SHADER_MODEL VS_SHADER_TYPE VS_STARTUP_PROJECT VS_TOOL_OVERRIDE VS_USER_PROPS VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION VS_WINRT_COMPONENT VS_WINRT_EXTENSIONS VS_WINRT_REFERENCES VS_XAML_TYPE WILL_FAIL WIN32_EXECUTABLE WINDOWS_EXPORT_ALL_SYMBOLS WORKING_DIRECTORY WRAP_EXCLUDE XCODE_EMIT_EFFECTIVE_PLATFORM_NAME XCODE_EXPLICIT_FILE_TYPE XCODE_FILE_ATTRIBUTES XCODE_LAST_KNOWN_FILE_TYPE XCODE_PRODUCT_TYPE XCTEST syn keyword cmakeVariable contained - \ ANDROID APPLE BORLAND BUILD_SHARED_LIBS CMAKE_ABSOLUTE_DESTINATION_FILES CMAKE_ANDROID_ANT_ADDITIONAL_OPTIONS CMAKE_ANDROID_API CMAKE_ANDROID_API_MIN CMAKE_ANDROID_ARCH CMAKE_ANDROID_ARCH_ABI CMAKE_ANDROID_ARM_MODE CMAKE_ANDROID_ARM_NEON CMAKE_ANDROID_ASSETS_DIRECTORIES CMAKE_ANDROID_GUI CMAKE_ANDROID_JAR_DEPENDENCIES CMAKE_ANDROID_JAR_DIRECTORIES CMAKE_ANDROID_JAVA_SOURCE_DIR CMAKE_ANDROID_NATIVE_LIB_DEPENDENCIES CMAKE_ANDROID_NATIVE_LIB_DIRECTORIES CMAKE_ANDROID_NDK CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION CMAKE_ANDROID_PROCESS_MAX CMAKE_ANDROID_PROGUARD CMAKE_ANDROID_PROGUARD_CONFIG_PATH CMAKE_ANDROID_SECURE_PROPS_PATH CMAKE_ANDROID_SKIP_ANT_STEP CMAKE_ANDROID_STANDALONE_TOOLCHAIN CMAKE_ANDROID_STL_TYPE CMAKE_APPBUNDLE_PATH CMAKE_AR CMAKE_ARCHIVE_OUTPUT_DIRECTORY CMAKE_ARGC CMAKE_ARGV0 CMAKE_AUTOMOC CMAKE_AUTOMOC_DEPEND_FILTERS CMAKE_AUTOMOC_MOC_OPTIONS CMAKE_AUTOMOC_RELAXED_MODE CMAKE_AUTORCC CMAKE_AUTORCC_OPTIONS CMAKE_AUTOUIC CMAKE_AUTOUIC_OPTIONS CMAKE_AUTOUIC_SEARCH_PATHS CMAKE_BACKWARDS_COMPATIBILITY CMAKE_BINARY_DIR CMAKE_BUILD_RPATH CMAKE_BUILD_TOOL CMAKE_BUILD_TYPE CMAKE_BUILD_WITH_INSTALL_NAME_DIR CMAKE_BUILD_WITH_INSTALL_RPATH CMAKE_CACHEFILE_DIR CMAKE_CACHE_MAJOR_VERSION CMAKE_CACHE_MINOR_VERSION CMAKE_CACHE_PATCH_VERSION CMAKE_CFG_INTDIR CMAKE_CL_64 CMAKE_CODELITE_USE_TARGETS CMAKE_COLOR_MAKEFILE CMAKE_COMMAND CMAKE_COMPILER_2005 CMAKE_COMPILER_IS_GNUCC CMAKE_COMPILER_IS_GNUCXX CMAKE_COMPILER_IS_GNUG77 CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY CMAKE_CONFIGURATION_TYPES CMAKE_CROSSCOMPILING CMAKE_CROSSCOMPILING_EMULATOR CMAKE_CTEST_COMMAND CMAKE_CUDA_EXTENSIONS CMAKE_CUDA_STANDARD CMAKE_CUDA_STANDARD_REQUIRED CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES CMAKE_CURRENT_BINARY_DIR CMAKE_CURRENT_LIST_DIR CMAKE_CURRENT_LIST_FILE CMAKE_CURRENT_LIST_LINE CMAKE_CURRENT_SOURCE_DIR CMAKE_CXX_COMPILE_FEATURES CMAKE_CXX_EXTENSIONS CMAKE_CXX_STANDARD CMAKE_CXX_STANDARD_REQUIRED CMAKE_C_COMPILE_FEATURES CMAKE_C_EXTENSIONS CMAKE_C_STANDARD CMAKE_C_STANDARD_REQUIRED CMAKE_DEBUG_POSTFIX CMAKE_DEBUG_TARGET_PROPERTIES CMAKE_DEPENDS_IN_PROJECT_ONLY CMAKE_DL_LIBS CMAKE_ECLIPSE_GENERATE_LINKED_RESOURCES CMAKE_ECLIPSE_GENERATE_SOURCE_PROJECT CMAKE_ECLIPSE_MAKE_ARGUMENTS CMAKE_ECLIPSE_VERSION CMAKE_EDIT_COMMAND CMAKE_ENABLE_EXPORTS CMAKE_ERROR_DEPRECATED CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION CMAKE_EXECUTABLE_SUFFIX CMAKE_EXE_LINKER_FLAGS CMAKE_EXE_LINKER_FLAGS_INIT CMAKE_EXPORT_COMPILE_COMMANDS CMAKE_EXPORT_NO_PACKAGE_REGISTRY CMAKE_EXTRA_GENERATOR CMAKE_EXTRA_SHARED_LIBRARY_SUFFIXES CMAKE_FIND_APPBUNDLE CMAKE_FIND_FRAMEWORK CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX CMAKE_FIND_LIBRARY_PREFIXES CMAKE_FIND_LIBRARY_SUFFIXES CMAKE_FIND_NO_INSTALL_PREFIX CMAKE_FIND_PACKAGE_NAME CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY CMAKE_FIND_PACKAGE_SORT_DIRECTION CMAKE_FIND_PACKAGE_SORT_ORDER CMAKE_FIND_PACKAGE_WARN_NO_MODULE CMAKE_FIND_ROOT_PATH CMAKE_FIND_ROOT_PATH_MODE_INCLUDE CMAKE_FIND_ROOT_PATH_MODE_LIBRARY CMAKE_FIND_ROOT_PATH_MODE_PACKAGE CMAKE_FIND_ROOT_PATH_MODE_PROGRAM CMAKE_FRAMEWORK_PATH CMAKE_Fortran_FORMAT CMAKE_Fortran_MODDIR_DEFAULT CMAKE_Fortran_MODDIR_FLAG CMAKE_Fortran_MODOUT_FLAG CMAKE_Fortran_MODULE_DIRECTORY CMAKE_GENERATOR CMAKE_GENERATOR_PLATFORM CMAKE_GENERATOR_TOOLSET CMAKE_GNUtoMS CMAKE_HOME_DIRECTORY CMAKE_HOST_APPLE CMAKE_HOST_SOLARIS CMAKE_HOST_SYSTEM CMAKE_HOST_SYSTEM_NAME CMAKE_HOST_SYSTEM_PROCESSOR CMAKE_HOST_SYSTEM_VERSION CMAKE_HOST_UNIX CMAKE_HOST_WIN32 CMAKE_IGNORE_PATH CMAKE_IMPORT_LIBRARY_PREFIX CMAKE_IMPORT_LIBRARY_SUFFIX CMAKE_INCLUDE_CURRENT_DIR CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE CMAKE_INCLUDE_DIRECTORIES_BEFORE CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE CMAKE_INCLUDE_PATH CMAKE_INSTALL_DEFAULT_COMPONENT_NAME CMAKE_INSTALL_MESSAGE CMAKE_INSTALL_NAME_DIR CMAKE_INSTALL_PREFIX CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT CMAKE_INSTALL_RPATH CMAKE_INSTALL_RPATH_USE_LINK_PATH CMAKE_INTERNAL_PLATFORM_ABI CMAKE_INTERPROCEDURAL_OPTIMIZATION CMAKE_IOS_INSTALL_COMBINED CMAKE_JOB_POOL_COMPILE CMAKE_JOB_POOL_LINK CMAKE_LIBRARY_ARCHITECTURE CMAKE_LIBRARY_ARCHITECTURE_REGEX CMAKE_LIBRARY_OUTPUT_DIRECTORY CMAKE_LIBRARY_PATH CMAKE_LIBRARY_PATH_FLAG CMAKE_LINK_DEF_FILE_FLAG CMAKE_LINK_DEPENDS_NO_SHARED CMAKE_LINK_INTERFACE_LIBRARIES CMAKE_LINK_LIBRARY_FILE_FLAG CMAKE_LINK_LIBRARY_FLAG CMAKE_LINK_LIBRARY_SUFFIX CMAKE_LINK_SEARCH_END_STATIC CMAKE_LINK_SEARCH_START_STATIC CMAKE_LINK_WHAT_YOU_USE CMAKE_MACOSX_BUNDLE CMAKE_MACOSX_RPATH CMAKE_MAJOR_VERSION CMAKE_MAKE_PROGRAM CMAKE_MATCH_COUNT CMAKE_MFC_FLAG CMAKE_MINIMUM_REQUIRED_VERSION CMAKE_MINOR_VERSION CMAKE_MODULE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS_INIT CMAKE_MODULE_PATH CMAKE_NINJA_OUTPUT_PATH_PREFIX CMAKE_NOT_USING_CONFIG_FLAGS CMAKE_NO_BUILTIN_CHRPATH CMAKE_NO_SYSTEM_FROM_IMPORTED CMAKE_OBJECT_PATH_MAX CMAKE_OSX_ARCHITECTURES CMAKE_OSX_DEPLOYMENT_TARGET CMAKE_OSX_SYSROOT CMAKE_PARENT_LIST_FILE CMAKE_PATCH_VERSION CMAKE_PDB_OUTPUT_DIRECTORY CMAKE_POSITION_INDEPENDENT_CODE CMAKE_PREFIX_PATH CMAKE_PROGRAM_PATH CMAKE_PROJECT_DESCRIPTION CMAKE_PROJECT_NAME CMAKE_RANLIB CMAKE_ROOT CMAKE_RUNTIME_OUTPUT_DIRECTORY CMAKE_SCRIPT_MODE_FILE CMAKE_SHARED_LIBRARY_PREFIX CMAKE_SHARED_LIBRARY_SUFFIX CMAKE_SHARED_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS_INIT CMAKE_SHARED_MODULE_PREFIX CMAKE_SHARED_MODULE_SUFFIX CMAKE_SIZEOF_VOID_P CMAKE_SKIP_BUILD_RPATH CMAKE_SKIP_INSTALL_ALL_DEPENDENCY CMAKE_SKIP_INSTALL_RPATH CMAKE_SKIP_INSTALL_RULES CMAKE_SKIP_RPATH CMAKE_SOURCE_DIR CMAKE_STAGING_PREFIX CMAKE_STATIC_LIBRARY_PREFIX CMAKE_STATIC_LIBRARY_SUFFIX CMAKE_STATIC_LINKER_FLAGS CMAKE_STATIC_LINKER_FLAGS_INIT CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE CMAKE_SYSROOT CMAKE_SYSTEM CMAKE_SYSTEM_APPBUNDLE_PATH CMAKE_SYSTEM_FRAMEWORK_PATH CMAKE_SYSTEM_IGNORE_PATH CMAKE_SYSTEM_INCLUDE_PATH CMAKE_SYSTEM_LIBRARY_PATH CMAKE_SYSTEM_NAME CMAKE_SYSTEM_PREFIX_PATH CMAKE_SYSTEM_PROCESSOR CMAKE_SYSTEM_PROGRAM_PATH CMAKE_SYSTEM_VERSION CMAKE_Swift_LANGUAGE_VERSION CMAKE_TOOLCHAIN_FILE CMAKE_TRY_COMPILE_CONFIGURATION CMAKE_TRY_COMPILE_PLATFORM_VARIABLES CMAKE_TRY_COMPILE_TARGET_TYPE CMAKE_TWEAK_VERSION CMAKE_USER_MAKE_RULES_OVERRIDE CMAKE_USE_RELATIVE_PATHS CMAKE_VERBOSE_MAKEFILE CMAKE_VERSION CMAKE_VISIBILITY_INLINES_HIDDEN CMAKE_VS_DEVENV_COMMAND CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD CMAKE_VS_INTEL_Fortran_PROJECT_VERSION CMAKE_VS_MSBUILD_COMMAND CMAKE_VS_NsightTegra_VERSION CMAKE_VS_PLATFORM_NAME CMAKE_VS_PLATFORM_TOOLSET CMAKE_VS_PLATFORM_TOOLSET_CUDA CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION CMAKE_WARN_DEPRECATED CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION CMAKE_WIN32_EXECUTABLE CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS CMAKE_XCODE_GENERATE_SCHEME CMAKE_XCODE_PLATFORM_TOOLSET CPACK_ABSOLUTE_DESTINATION_FILES CPACK_COMPONENT_INCLUDE_TOPLEVEL_DIRECTORY CPACK_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION CPACK_INCLUDE_TOPLEVEL_DIRECTORY CPACK_INSTALL_SCRIPT CPACK_PACKAGING_INSTALL_PREFIX CPACK_SET_DESTDIR CPACK_WARN_ON_ABSOLUTE_INSTALL_DESTINATION CTEST_BINARY_DIRECTORY CTEST_BUILD_COMMAND CTEST_BUILD_NAME CTEST_BZR_COMMAND CTEST_BZR_UPDATE_OPTIONS CTEST_CHANGE_ID CTEST_CHECKOUT_COMMAND CTEST_CONFIGURATION_TYPE CTEST_CONFIGURE_COMMAND CTEST_COVERAGE_COMMAND CTEST_COVERAGE_EXTRA_FLAGS CTEST_CURL_OPTIONS CTEST_CUSTOM_COVERAGE_EXCLUDE CTEST_CUSTOM_ERROR_EXCEPTION CTEST_CUSTOM_ERROR_MATCH CTEST_CUSTOM_ERROR_POST_CONTEXT CTEST_CUSTOM_ERROR_PRE_CONTEXT CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE CTEST_CUSTOM_MAXIMUM_NUMBER_OF_ERRORS CTEST_CUSTOM_MAXIMUM_NUMBER_OF_WARNINGS CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE CTEST_CUSTOM_MEMCHECK_IGNORE CTEST_CUSTOM_POST_MEMCHECK CTEST_CUSTOM_POST_TEST CTEST_CUSTOM_PRE_MEMCHECK CTEST_CUSTOM_PRE_TEST CTEST_CUSTOM_TEST_IGNORE CTEST_CUSTOM_WARNING_EXCEPTION CTEST_CUSTOM_WARNING_MATCH CTEST_CVS_CHECKOUT CTEST_CVS_COMMAND CTEST_CVS_UPDATE_OPTIONS CTEST_DROP_LOCATION CTEST_DROP_METHOD CTEST_DROP_SITE CTEST_DROP_SITE_CDASH CTEST_DROP_SITE_PASSWORD CTEST_DROP_SITE_USER CTEST_EXTRA_COVERAGE_GLOB CTEST_GIT_COMMAND CTEST_GIT_INIT_SUBMODULES CTEST_GIT_UPDATE_CUSTOM CTEST_GIT_UPDATE_OPTIONS CTEST_HG_COMMAND CTEST_HG_UPDATE_OPTIONS CTEST_LABELS_FOR_SUBPROJECTS CTEST_MEMORYCHECK_COMMAND CTEST_MEMORYCHECK_COMMAND_OPTIONS CTEST_MEMORYCHECK_SANITIZER_OPTIONS CTEST_MEMORYCHECK_SUPPRESSIONS_FILE CTEST_MEMORYCHECK_TYPE CTEST_NIGHTLY_START_TIME CTEST_P4_CLIENT CTEST_P4_COMMAND CTEST_P4_OPTIONS CTEST_P4_UPDATE_OPTIONS CTEST_SCP_COMMAND CTEST_SITE CTEST_SOURCE_DIRECTORY CTEST_SVN_COMMAND CTEST_SVN_OPTIONS CTEST_SVN_UPDATE_OPTIONS CTEST_TEST_LOAD CTEST_TEST_TIMEOUT CTEST_TRIGGER_SITE CTEST_UPDATE_COMMAND CTEST_UPDATE_OPTIONS CTEST_UPDATE_VERSION_ONLY CTEST_USE_LAUNCHERS CYGWIN ENV EXECUTABLE_OUTPUT_PATH GHS-MULTI LIBRARY_OUTPUT_PATH MINGW MSVC MSVC10 MSVC11 MSVC12 MSVC14 MSVC60 MSVC70 MSVC71 MSVC80 MSVC90 MSVC_IDE MSVC_VERSION PROJECT_BINARY_DIR PROJECT_DESCRIPTION PROJECT_NAME PROJECT_SOURCE_DIR PROJECT_VERSION PROJECT_VERSION_MAJOR PROJECT_VERSION_MINOR PROJECT_VERSION_PATCH PROJECT_VERSION_TWEAK UNIX WIN32 WINCE WINDOWS_PHONE WINDOWS_STORE XCODE XCODE_VERSION + \ ANDROID APPLE BORLAND BUILD_SHARED_LIBS CMAKE_ABSOLUTE_DESTINATION_FILES CMAKE_ANDROID_ANT_ADDITIONAL_OPTIONS CMAKE_ANDROID_API CMAKE_ANDROID_API_MIN CMAKE_ANDROID_ARCH CMAKE_ANDROID_ARCH_ABI CMAKE_ANDROID_ARM_MODE CMAKE_ANDROID_ARM_NEON CMAKE_ANDROID_ASSETS_DIRECTORIES CMAKE_ANDROID_GUI CMAKE_ANDROID_JAR_DEPENDENCIES CMAKE_ANDROID_JAR_DIRECTORIES CMAKE_ANDROID_JAVA_SOURCE_DIR CMAKE_ANDROID_NATIVE_LIB_DEPENDENCIES CMAKE_ANDROID_NATIVE_LIB_DIRECTORIES CMAKE_ANDROID_NDK CMAKE_ANDROID_NDK_DEPRECATED_HEADERS CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION CMAKE_ANDROID_PROCESS_MAX CMAKE_ANDROID_PROGUARD CMAKE_ANDROID_PROGUARD_CONFIG_PATH CMAKE_ANDROID_SECURE_PROPS_PATH CMAKE_ANDROID_SKIP_ANT_STEP CMAKE_ANDROID_STANDALONE_TOOLCHAIN CMAKE_ANDROID_STL_TYPE CMAKE_APPBUNDLE_PATH CMAKE_AR CMAKE_ARCHIVE_OUTPUT_DIRECTORY CMAKE_ARGC CMAKE_ARGV0 CMAKE_AUTOMOC CMAKE_AUTOMOC_DEPEND_FILTERS CMAKE_AUTOMOC_MACRO_NAMES CMAKE_AUTOMOC_MOC_OPTIONS CMAKE_AUTOMOC_RELAXED_MODE CMAKE_AUTORCC CMAKE_AUTORCC_OPTIONS CMAKE_AUTOUIC CMAKE_AUTOUIC_OPTIONS CMAKE_AUTOUIC_SEARCH_PATHS CMAKE_BACKWARDS_COMPATIBILITY CMAKE_BINARY_DIR CMAKE_BUILD_RPATH CMAKE_BUILD_TOOL CMAKE_BUILD_TYPE CMAKE_BUILD_WITH_INSTALL_NAME_DIR CMAKE_BUILD_WITH_INSTALL_RPATH CMAKE_CACHEFILE_DIR CMAKE_CACHE_MAJOR_VERSION CMAKE_CACHE_MINOR_VERSION CMAKE_CACHE_PATCH_VERSION CMAKE_CFG_INTDIR CMAKE_CL_64 CMAKE_CODELITE_USE_TARGETS CMAKE_COLOR_MAKEFILE CMAKE_COMMAND CMAKE_COMPILER_2005 CMAKE_COMPILER_IS_GNUCC CMAKE_COMPILER_IS_GNUCXX CMAKE_COMPILER_IS_GNUG77 CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY CMAKE_CONFIGURATION_TYPES CMAKE_CROSSCOMPILING CMAKE_CROSSCOMPILING_EMULATOR CMAKE_CTEST_COMMAND CMAKE_CUDA_EXTENSIONS CMAKE_CUDA_STANDARD CMAKE_CUDA_STANDARD_REQUIRED CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES CMAKE_CURRENT_BINARY_DIR CMAKE_CURRENT_LIST_DIR CMAKE_CURRENT_LIST_FILE CMAKE_CURRENT_LIST_LINE CMAKE_CURRENT_SOURCE_DIR CMAKE_CXX_COMPILE_FEATURES CMAKE_CXX_EXTENSIONS CMAKE_CXX_STANDARD CMAKE_CXX_STANDARD_REQUIRED CMAKE_C_COMPILE_FEATURES CMAKE_C_EXTENSIONS CMAKE_C_STANDARD CMAKE_C_STANDARD_REQUIRED CMAKE_DEBUG_POSTFIX CMAKE_DEBUG_TARGET_PROPERTIES CMAKE_DEPENDS_IN_PROJECT_ONLY CMAKE_DIRECTORY_LABELS CMAKE_DL_LIBS CMAKE_ECLIPSE_GENERATE_LINKED_RESOURCES CMAKE_ECLIPSE_GENERATE_SOURCE_PROJECT CMAKE_ECLIPSE_MAKE_ARGUMENTS CMAKE_ECLIPSE_VERSION CMAKE_EDIT_COMMAND CMAKE_ENABLE_EXPORTS CMAKE_ERROR_DEPRECATED CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION CMAKE_EXECUTABLE_SUFFIX CMAKE_EXE_LINKER_FLAGS CMAKE_EXE_LINKER_FLAGS_INIT CMAKE_EXPORT_COMPILE_COMMANDS CMAKE_EXPORT_NO_PACKAGE_REGISTRY CMAKE_EXTRA_GENERATOR CMAKE_EXTRA_SHARED_LIBRARY_SUFFIXES CMAKE_FIND_APPBUNDLE CMAKE_FIND_FRAMEWORK CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX CMAKE_FIND_LIBRARY_PREFIXES CMAKE_FIND_LIBRARY_SUFFIXES CMAKE_FIND_NO_INSTALL_PREFIX CMAKE_FIND_PACKAGE_NAME CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY CMAKE_FIND_PACKAGE_SORT_DIRECTION CMAKE_FIND_PACKAGE_SORT_ORDER CMAKE_FIND_PACKAGE_WARN_NO_MODULE CMAKE_FIND_ROOT_PATH CMAKE_FIND_ROOT_PATH_MODE_INCLUDE CMAKE_FIND_ROOT_PATH_MODE_LIBRARY CMAKE_FIND_ROOT_PATH_MODE_PACKAGE CMAKE_FIND_ROOT_PATH_MODE_PROGRAM CMAKE_FRAMEWORK_PATH CMAKE_Fortran_FORMAT CMAKE_Fortran_MODDIR_DEFAULT CMAKE_Fortran_MODDIR_FLAG CMAKE_Fortran_MODOUT_FLAG CMAKE_Fortran_MODULE_DIRECTORY CMAKE_GENERATOR CMAKE_GENERATOR_PLATFORM CMAKE_GENERATOR_TOOLSET CMAKE_GNUtoMS CMAKE_HOME_DIRECTORY CMAKE_HOST_APPLE CMAKE_HOST_SOLARIS CMAKE_HOST_SYSTEM CMAKE_HOST_SYSTEM_NAME CMAKE_HOST_SYSTEM_PROCESSOR CMAKE_HOST_SYSTEM_VERSION CMAKE_HOST_UNIX CMAKE_HOST_WIN32 CMAKE_IGNORE_PATH CMAKE_IMPORT_LIBRARY_PREFIX CMAKE_IMPORT_LIBRARY_SUFFIX CMAKE_INCLUDE_CURRENT_DIR CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE CMAKE_INCLUDE_DIRECTORIES_BEFORE CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE CMAKE_INCLUDE_PATH CMAKE_INSTALL_DEFAULT_COMPONENT_NAME CMAKE_INSTALL_MESSAGE CMAKE_INSTALL_NAME_DIR CMAKE_INSTALL_PREFIX CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT CMAKE_INSTALL_RPATH CMAKE_INSTALL_RPATH_USE_LINK_PATH CMAKE_INTERNAL_PLATFORM_ABI CMAKE_INTERPROCEDURAL_OPTIMIZATION CMAKE_IOS_INSTALL_COMBINED CMAKE_JOB_POOL_COMPILE CMAKE_JOB_POOL_LINK CMAKE_LIBRARY_ARCHITECTURE CMAKE_LIBRARY_ARCHITECTURE_REGEX CMAKE_LIBRARY_OUTPUT_DIRECTORY CMAKE_LIBRARY_PATH CMAKE_LIBRARY_PATH_FLAG CMAKE_LINK_DEF_FILE_FLAG CMAKE_LINK_DEPENDS_NO_SHARED CMAKE_LINK_INTERFACE_LIBRARIES CMAKE_LINK_LIBRARY_FILE_FLAG CMAKE_LINK_LIBRARY_FLAG CMAKE_LINK_LIBRARY_SUFFIX CMAKE_LINK_SEARCH_END_STATIC CMAKE_LINK_SEARCH_START_STATIC CMAKE_LINK_WHAT_YOU_USE CMAKE_MACOSX_BUNDLE CMAKE_MACOSX_RPATH CMAKE_MAJOR_VERSION CMAKE_MAKE_PROGRAM CMAKE_MATCH_COUNT CMAKE_MFC_FLAG CMAKE_MINIMUM_REQUIRED_VERSION CMAKE_MINOR_VERSION CMAKE_MODULE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS_INIT CMAKE_MODULE_PATH CMAKE_MSVCIDE_RUN_PATH CMAKE_NINJA_OUTPUT_PATH_PREFIX CMAKE_NOT_USING_CONFIG_FLAGS CMAKE_NO_BUILTIN_CHRPATH CMAKE_NO_SYSTEM_FROM_IMPORTED CMAKE_OBJECT_PATH_MAX CMAKE_OSX_ARCHITECTURES CMAKE_OSX_DEPLOYMENT_TARGET CMAKE_OSX_SYSROOT CMAKE_PARENT_LIST_FILE CMAKE_PATCH_VERSION CMAKE_PDB_OUTPUT_DIRECTORY CMAKE_POSITION_INDEPENDENT_CODE CMAKE_PREFIX_PATH CMAKE_PROGRAM_PATH CMAKE_PROJECT_DESCRIPTION CMAKE_PROJECT_NAME CMAKE_RANLIB CMAKE_ROOT CMAKE_RUNTIME_OUTPUT_DIRECTORY CMAKE_SCRIPT_MODE_FILE CMAKE_SHARED_LIBRARY_PREFIX CMAKE_SHARED_LIBRARY_SUFFIX CMAKE_SHARED_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS_INIT CMAKE_SHARED_MODULE_PREFIX CMAKE_SHARED_MODULE_SUFFIX CMAKE_SIZEOF_VOID_P CMAKE_SKIP_BUILD_RPATH CMAKE_SKIP_INSTALL_ALL_DEPENDENCY CMAKE_SKIP_INSTALL_RPATH CMAKE_SKIP_INSTALL_RULES CMAKE_SKIP_RPATH CMAKE_SOURCE_DIR CMAKE_STAGING_PREFIX CMAKE_STATIC_LIBRARY_PREFIX CMAKE_STATIC_LIBRARY_SUFFIX CMAKE_STATIC_LINKER_FLAGS CMAKE_STATIC_LINKER_FLAGS_INIT CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE CMAKE_SYSROOT CMAKE_SYSROOT_COMPILE CMAKE_SYSROOT_LINK CMAKE_SYSTEM CMAKE_SYSTEM_APPBUNDLE_PATH CMAKE_SYSTEM_FRAMEWORK_PATH CMAKE_SYSTEM_IGNORE_PATH CMAKE_SYSTEM_INCLUDE_PATH CMAKE_SYSTEM_LIBRARY_PATH CMAKE_SYSTEM_NAME CMAKE_SYSTEM_PREFIX_PATH CMAKE_SYSTEM_PROCESSOR CMAKE_SYSTEM_PROGRAM_PATH CMAKE_SYSTEM_VERSION CMAKE_Swift_LANGUAGE_VERSION CMAKE_TOOLCHAIN_FILE CMAKE_TRY_COMPILE_CONFIGURATION CMAKE_TRY_COMPILE_PLATFORM_VARIABLES CMAKE_TRY_COMPILE_TARGET_TYPE CMAKE_TWEAK_VERSION CMAKE_USER_MAKE_RULES_OVERRIDE CMAKE_USE_RELATIVE_PATHS CMAKE_VERBOSE_MAKEFILE CMAKE_VERSION CMAKE_VISIBILITY_INLINES_HIDDEN CMAKE_VS_DEVENV_COMMAND CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD CMAKE_VS_INTEL_Fortran_PROJECT_VERSION CMAKE_VS_MSBUILD_COMMAND CMAKE_VS_NsightTegra_VERSION CMAKE_VS_PLATFORM_NAME CMAKE_VS_PLATFORM_TOOLSET CMAKE_VS_PLATFORM_TOOLSET_CUDA CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION CMAKE_WARN_DEPRECATED CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION CMAKE_WIN32_EXECUTABLE CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS CMAKE_XCODE_GENERATE_SCHEME CMAKE_XCODE_PLATFORM_TOOLSET CPACK_ABSOLUTE_DESTINATION_FILES CPACK_COMPONENT_INCLUDE_TOPLEVEL_DIRECTORY CPACK_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION CPACK_INCLUDE_TOPLEVEL_DIRECTORY CPACK_INSTALL_SCRIPT CPACK_PACKAGING_INSTALL_PREFIX CPACK_SET_DESTDIR CPACK_WARN_ON_ABSOLUTE_INSTALL_DESTINATION CTEST_BINARY_DIRECTORY CTEST_BUILD_COMMAND CTEST_BUILD_NAME CTEST_BZR_COMMAND CTEST_BZR_UPDATE_OPTIONS CTEST_CHANGE_ID CTEST_CHECKOUT_COMMAND CTEST_CONFIGURATION_TYPE CTEST_CONFIGURE_COMMAND CTEST_COVERAGE_COMMAND CTEST_COVERAGE_EXTRA_FLAGS CTEST_CURL_OPTIONS CTEST_CUSTOM_COVERAGE_EXCLUDE CTEST_CUSTOM_ERROR_EXCEPTION CTEST_CUSTOM_ERROR_MATCH CTEST_CUSTOM_ERROR_POST_CONTEXT CTEST_CUSTOM_ERROR_PRE_CONTEXT CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE CTEST_CUSTOM_MAXIMUM_NUMBER_OF_ERRORS CTEST_CUSTOM_MAXIMUM_NUMBER_OF_WARNINGS CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE CTEST_CUSTOM_MEMCHECK_IGNORE CTEST_CUSTOM_POST_MEMCHECK CTEST_CUSTOM_POST_TEST CTEST_CUSTOM_PRE_MEMCHECK CTEST_CUSTOM_PRE_TEST CTEST_CUSTOM_TEST_IGNORE CTEST_CUSTOM_WARNING_EXCEPTION CTEST_CUSTOM_WARNING_MATCH CTEST_CVS_CHECKOUT CTEST_CVS_COMMAND CTEST_CVS_UPDATE_OPTIONS CTEST_DROP_LOCATION CTEST_DROP_METHOD CTEST_DROP_SITE CTEST_DROP_SITE_CDASH CTEST_DROP_SITE_PASSWORD CTEST_DROP_SITE_USER CTEST_EXTRA_COVERAGE_GLOB CTEST_GIT_COMMAND CTEST_GIT_INIT_SUBMODULES CTEST_GIT_UPDATE_CUSTOM CTEST_GIT_UPDATE_OPTIONS CTEST_HG_COMMAND CTEST_HG_UPDATE_OPTIONS CTEST_LABELS_FOR_SUBPROJECTS CTEST_MEMORYCHECK_COMMAND CTEST_MEMORYCHECK_COMMAND_OPTIONS CTEST_MEMORYCHECK_SANITIZER_OPTIONS CTEST_MEMORYCHECK_SUPPRESSIONS_FILE CTEST_MEMORYCHECK_TYPE CTEST_NIGHTLY_START_TIME CTEST_P4_CLIENT CTEST_P4_COMMAND CTEST_P4_OPTIONS CTEST_P4_UPDATE_OPTIONS CTEST_SCP_COMMAND CTEST_SITE CTEST_SOURCE_DIRECTORY CTEST_SVN_COMMAND CTEST_SVN_OPTIONS CTEST_SVN_UPDATE_OPTIONS CTEST_TEST_LOAD CTEST_TEST_TIMEOUT CTEST_TRIGGER_SITE CTEST_UPDATE_COMMAND CTEST_UPDATE_OPTIONS CTEST_UPDATE_VERSION_ONLY CTEST_USE_LAUNCHERS CYGWIN ENV EXECUTABLE_OUTPUT_PATH GHS-MULTI LIBRARY_OUTPUT_PATH MINGW MSVC MSVC10 MSVC11 MSVC12 MSVC14 MSVC60 MSVC70 MSVC71 MSVC80 MSVC90 MSVC_IDE MSVC_VERSION PROJECT_BINARY_DIR PROJECT_DESCRIPTION PROJECT_NAME PROJECT_SOURCE_DIR PROJECT_VERSION PROJECT_VERSION_MAJOR PROJECT_VERSION_MINOR PROJECT_VERSION_PATCH PROJECT_VERSION_TWEAK UNIX WIN32 WINCE WINDOWS_PHONE WINDOWS_STORE XCODE XCODE_VERSION syn keyword cmakeModule contained \ ExternalProject syn keyword cmakeKWExternalProject contained - \ ALGO BINARY_DIR BUILD_ALWAYS BUILD_BYPRODUCTS BUILD_COMMAND BUILD_IN_SOURCE CMAKE_ARGS CMAKE_CACHE_ARGS CMAKE_CACHE_DEFAULT_ARGS COMMENT CONFIGURE_COMMAND CVSROOT CVS_MODULE CVS_REPOSITORY CVS_TAG DEPENDEES DEPENDERS DEPENDS DOWNLOADED_FILE DOWNLOAD_COMMAND DOWNLOAD_DIR DOWNLOAD_NAME DOWNLOAD_NO_EXTRACT DOWNLOAD_NO_PROGRESS EP_BASE EP_INDEPENDENT_STEP_TARGETS EP_PREFIX EP_STEP_TARGETS EP_UPDATE_DISCONNECTED EXCLUDE_FROM_ALL FORCE GIT_CONFIG GIT_PROGRESS GIT_REMOTE_NAME GIT_REPOSITORY GIT_SHALLOW GIT_SUBMODULES GIT_TAG HG_REPOSITORY HG_TAG HTTP_HEADER HTTP_PASSWORD HTTP_USERNAME INDEPENDENT_STEP_TARGETS INSTALL_COMMAND INSTALL_DIR JOB_POOLS LIST_SEPARATOR LOG_BUILD LOG_CONFIGURE LOG_DOWNLOAD LOG_INSTALL LOG_TEST LOG_UPDATE NO_DEPENDS PATCH_COMMAND PREFIX PROPERTY SOURCE_DIR SOURCE_SUBDIR STAMP_DIR STEP_TARGETS SVN_PASSWORD SVN_REPOSITORY SVN_REVISION SVN_TRUST_CERT SVN_USERNAME TEST_AFTER_INSTALL TEST_BEFORE_INSTALL TEST_COMMAND TEST_EXCLUDE_FROM_MAIN TIMEOUT TLS_CAINFO TLS_VERIFY TMP_DIR UPDATE_COMMAND UPDATE_DISCONNECTED URL URL_HASH USES_TERMINAL_BUILD USES_TERMINAL_CONFIGURE USES_TERMINAL_DOWNLOAD USES_TERMINAL_INSTALL USES_TERMINAL_TEST USES_TERMINAL_UPDATE WORKING_DIRECTORY + \ ALGO AWS BINARY_DIR BUILD_ALWAYS BUILD_BYPRODUCTS BUILD_COMMAND BUILD_IN_SOURCE CMAKE_ARGS CMAKE_CACHE_ARGS CMAKE_CACHE_DEFAULT_ARGS CMAKE_TLS_CAINFO CMAKE_TLS_VERIFY COMMENT CONFIGURE_COMMAND CVS CVSROOT CVS_MODULE CVS_REPOSITORY CVS_TAG DEPENDEES DEPENDERS DEPENDS DOWNLOADED_FILE DOWNLOAD_COMMAND DOWNLOAD_DIR DOWNLOAD_NAME DOWNLOAD_NO_EXTRACT DOWNLOAD_NO_PROGRESS EP_BASE EP_INDEPENDENT_STEP_TARGETS EP_PREFIX EP_STEP_TARGETS EP_UPDATE_DISCONNECTED EXCLUDE_FROM_ALL FORCE GIT_CONFIG GIT_PROGRESS GIT_REMOTE_NAME GIT_REPOSITORY GIT_SHALLOW GIT_SUBMODULES GIT_TAG HG_REPOSITORY HG_TAG HTTP_HEADER HTTP_PASSWORD HTTP_USERNAME INDEPENDENT_STEP_TARGETS INSTALL_COMMAND INSTALL_DIR JOB_POOLS LIST_SEPARATOR LOG_ LOG_BUILD LOG_CONFIGURE LOG_DOWNLOAD LOG_INSTALL LOG_TEST LOG_UPDATE MAKE_EXE NAMES NOTE NO_DEPENDS PATCH_COMMAND PREFIX PROPERTY SOURCE_DIR SOURCE_SUBDIR STAMP_DIR STEP_TARGETS STRING SVN_PASSWORD SVN_REPOSITORY SVN_REVISION SVN_TRUST_CERT SVN_USERNAME TEST_AFTER_INSTALL TEST_BEFORE_INSTALL TEST_COMMAND TEST_EXCLUDE_FROM_MAIN TIMEOUT TLS_CAINFO TLS_VERIFY TMP_DIR TRUE UPDATE_COMMAND UPDATE_DISCONNECTED URL URL_HASH USES_TERMINAL_BUILD USES_TERMINAL_CONFIGURE USES_TERMINAL_DOWNLOAD USES_TERMINAL_INSTALL USES_TERMINAL_TEST USES_TERMINAL_UPDATE WORKING_DIRECTORY syn keyword cmakeKWadd_compile_options contained \ COMPILE_OPTIONS @@ -59,10 +65,10 @@ syn keyword cmakeKWadd_dependencies contained \ DEPENDS OBJECT_DEPENDS syn keyword cmakeKWadd_executable contained - \ ALIAS CONFIG EXCLUDE_FROM_ALL GLOBAL IMPORTED IMPORTED_ IMPORTED_LOCATION IMPORTED_LOCATION_ MACOSX_BUNDLE OUTPUT_NAME RUNTIME_OUTPUT_DIRECTORY TARGET + \ ALIAS CONFIG EXCLUDE_FROM_ALL GLOBAL HEADER_FILE_ONLY IMPORTED IMPORTED_ IMPORTED_LOCATION IMPORTED_LOCATION_ MACOSX_BUNDLE OUTPUT_NAME RUNTIME_OUTPUT_DIRECTORY TARGET syn keyword cmakeKWadd_library contained - \ ALIAS ARCHIVE_OUTPUT_DIRECTORY CLI CONFIG DLL EXCLUDE_FROM_ALL FRAMEWORK GLOBAL IMPORTED IMPORTED_ IMPORTED_LOCATION IMPORTED_LOCATION_ INTERFACE_ LIBRARY_OUTPUT_DIRECTORY MODULE OBJECT ON OUTPUT_NAME POSITION_INDEPENDENT_CODE POST_BUILD PRE_BUILD PRE_LINK RUNTIME_OUTPUT_DIRECTORY SHARED STATIC TARGET_OBJECTS UNKNOWN + \ ALIAS ARCHIVE_OUTPUT_DIRECTORY CLI CONFIG DLL EXCLUDE_FROM_ALL FRAMEWORK GLOBAL HEADER_FILE_ONLY IMPORTED IMPORTED_ IMPORTED_LOCATION IMPORTED_LOCATION_ INTERFACE_ LIBRARY_OUTPUT_DIRECTORY MODULE OBJECT ON OUTPUT_NAME POSITION_INDEPENDENT_CODE POST_BUILD PRE_BUILD PRE_LINK RUNTIME_OUTPUT_DIRECTORY SHARED STATIC TARGET_OBJECTS UNKNOWN syn keyword cmakeKWadd_subdirectory contained \ EXCLUDE_FROM_ALL @@ -77,7 +83,7 @@ syn keyword cmakeKWbuild_name contained \ CMAKE_CXX_COMPILER syn keyword cmakeKWcmake_host_system_information contained - \ AVAILABLE_PHYSICAL_MEMORY AVAILABLE_VIRTUAL_MEMORY FQDN HOSTNAME NUMBER_OF_LOGICAL_CORES NUMBER_OF_PHYSICAL_CORES QUERY RESULT TOTAL_PHYSICAL_MEMORY TOTAL_VIRTUAL_MEMORY IS_64BIT HAS_FPU HAS_MMX HAS_MMX_PLUS HAS_SSE HAS_SSE2 HAS_SSE_FP HAS_SSE_MMX HAS_AMD_3DNOW HAS_AMD_3DNOW_PLUS HAS_IA64 HAS_SERIAL_NUMBER PROCESSOR_SERIAL_NUMBER PROCESSOR_NAME OS_NAME OS_RELEASE OS_VERSION OS_PLATFORM + \ AVAILABLE_PHYSICAL_MEMORY AVAILABLE_VIRTUAL_MEMORY FQDN HAS_FPU HAS_MMX HAS_MMX_PLUS HAS_SERIAL_NUMBER HAS_SSE HAS_SSE_FP HAS_SSE_MMX HOSTNAME ID NUMBER_OF_LOGICAL_CORES NUMBER_OF_PHYSICAL_CORES OS_NAME OS_PLATFORM OS_RELEASE OS_VERSION PROCESSOR_DESCRIPTION PROCESSOR_NAME PROCESSOR_SERIAL_NUMBER QUERY RESULT TOTAL_PHYSICAL_MEMORY TOTAL_VIRTUAL_MEMORY syn keyword cmakeKWcmake_minimum_required contained \ FATAL_ERROR VERSION @@ -104,7 +110,7 @@ syn keyword cmakeKWctest_coverage contained \ APPEND BUILD CAPTURE_CMAKE_ERROR LABELS QUIET RETURN_VALUE syn keyword cmakeKWctest_memcheck contained - \ APPEND BUILD DEFECT_COUNT EXCLUDE EXCLUDE_LABEL INCLUDE INCLUDE_LABEL OFF ON PARALLEL_LEVEL QUIET RETURN_VALUE SCHEDULE_RANDOM START STOP_TIME STRIDE TEST_LOAD + \ APPEND BUILD DEFECT_COUNT EXCLUDE EXCLUDE_FIXTURE EXCLUDE_FIXTURE_CLEANUP EXCLUDE_FIXTURE_SETUP EXCLUDE_LABEL INCLUDE INCLUDE_LABEL OFF ON PARALLEL_LEVEL QUIET RETURN_VALUE SCHEDULE_RANDOM START STOP_TIME STRIDE TEST_LOAD syn keyword cmakeKWctest_run_script contained \ NEW_PROCESS RETURN_VALUE @@ -113,10 +119,10 @@ syn keyword cmakeKWctest_start contained \ APPEND QUIET TAG TRACK syn keyword cmakeKWctest_submit contained - \ API CDASH_UPLOAD CDASH_UPLOAD_TYPE CTEST_EXTRA_SUBMIT_FILES CTEST_NOTES_FILES FILES PARTS QUIET RETRY_COUNT RETRY_DELAY RETURN_VALUE + \ API CDASH_UPLOAD CDASH_UPLOAD_TYPE CTEST_EXTRA_SUBMIT_FILES CTEST_NOTES_FILES FILES HTTPHEADER PARTS QUIET RETRY_COUNT RETRY_DELAY RETURN_VALUE syn keyword cmakeKWctest_test contained - \ APPEND BUILD CAPTURE_CMAKE_ERROR CPU EXCLUDE EXCLUDE_LABEL INCLUDE INCLUDE_LABEL OFF ON PARALLEL_LEVEL QUIET RETURN_VALUE SCHEDULE_RANDOM START STOP_TIME STRIDE TEST_LOAD + \ APPEND BUILD CAPTURE_CMAKE_ERROR CPU EXCLUDE EXCLUDE_FIXTURE EXCLUDE_FIXTURE_CLEANUP EXCLUDE_FIXTURE_SETUP EXCLUDE_LABEL INCLUDE INCLUDE_LABEL OFF ON PARALLEL_LEVEL QUIET RETURN_VALUE SCHEDULE_RANDOM START STOP_TIME STRIDE TEST_LOAD syn keyword cmakeKWctest_update contained \ QUIET RETURN_VALUE SOURCE @@ -134,7 +140,7 @@ syn keyword cmakeKWexec_program contained \ ARGS OUTPUT_VARIABLE RETURN_VALUE syn keyword cmakeKWexecute_process contained - \ ANSI AUTO COMMAND ENCODING ERROR_FILE ERROR_QUIET ERROR_STRIP_TRAILING_WHITESPACE ERROR_VARIABLE INPUT_FILE NONE OEM OUTPUT_FILE OUTPUT_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE RESULT_VARIABLE TIMEOUT UTF VERBATIM WORKING_DIRECTORY + \ ANSI AUTO COMMAND ENCODING ERROR_FILE ERROR_QUIET ERROR_STRIP_TRAILING_WHITESPACE ERROR_VARIABLE INPUT_FILE NONE OEM OUTPUT_FILE OUTPUT_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE RESULTS_VARIABLE RESULT_VARIABLE TIMEOUT UTF VERBATIM WORKING_DIRECTORY syn keyword cmakeKWexport contained \ ANDROID_MK APPEND CONFIG EXPORT EXPORT_LINK_INTERFACE_LIBRARIES FILE IMPORTED IMPORTED_ NAMESPACE NDK OLD PACKAGE TARGETS @@ -143,7 +149,7 @@ syn keyword cmakeKWexport_library_dependencies contained \ APPEND EXPORT INCLUDE LINK_INTERFACE_LIBRARIES SET syn keyword cmakeKWfile contained - \ ALGO APPEND ASCII CMAKE_TLS_CAINFO CMAKE_TLS_VERIFY CONDITION CONFIG CONTENT COPY CR DESTINATION DIRECTORY_PERMISSIONS DOWNLOAD ENCODING EXCLUDE EXPECTED_HASH FILES_MATCHING FILE_PERMISSIONS FOLLOW_SYMLINKS FUNCTION GENERATE GLOB GLOB_RECURSE GUARD HASH HEX HTTPHEADER INACTIVITY_TIMEOUT INSTALL LENGTH_MAXIMUM LENGTH_MINIMUM LF LIMIT LIMIT_COUNT LIMIT_INPUT LIMIT_OUTPUT LIST_DIRECTORIES LOCK LOG MAKE_DIRECTORY NEWLINE_CONSUME NO_HEX_CONVERSION NO_SOURCE_PERMISSIONS OFFSET OLD PATTERN PROCESS READ REGEX RELATIVE RELATIVE_PATH RELEASE REMOVE REMOVE_RECURSE RENAME RESULT_VARIABLE SHOW_PROGRESS SORT SSL STATUS STRINGS TIMESTAMP TLS_CAINFO TLS_VERIFY TO_CMAKE_PATH TO_NATIVE_PATH UPLOAD USERPWD USE_SOURCE_PERMISSIONS UTC UTF WRITE + \ ALGO APPEND ASCII CMAKE_TLS_CAINFO CMAKE_TLS_VERIFY CONDITION CONFIG CONTENT COPY CR DESTINATION DIRECTORY_PERMISSIONS DOWNLOAD ENCODING EXCLUDE EXPECTED_HASH FILES_MATCHING FILE_PERMISSIONS FOLLOW_SYMLINKS FUNCTION GENERATE GLOB GLOB_RECURSE GUARD HASH HEX HTTPHEADER INACTIVITY_TIMEOUT INSTALL LENGTH_MAXIMUM LENGTH_MINIMUM LF LIMIT LIMIT_COUNT LIMIT_INPUT LIMIT_OUTPUT LIST_DIRECTORIES LOCK LOG MAKE_DIRECTORY NEWLINE_CONSUME NO_HEX_CONVERSION NO_SOURCE_PERMISSIONS OFFSET OLD PATTERN PROCESS READ REGEX RELATIVE RELATIVE_PATH RELEASE REMOVE REMOVE_RECURSE RENAME RESULT_VARIABLE SHOW_PROGRESS SSL STATUS STRINGS TIMESTAMP TLS_CAINFO TLS_VERIFY TO_CMAKE_PATH TO_NATIVE_PATH UPLOAD USERPWD USE_SOURCE_PERMISSIONS UTC UTF WRITE syn keyword cmakeKWfind_file contained \ CMAKE_FIND_ROOT_PATH_BOTH DOC DVAR HINTS INCLUDE NAMES NO_CMAKE_ENVIRONMENT_PATH NO_CMAKE_FIND_ROOT_PATH NO_CMAKE_PATH NO_CMAKE_SYSTEM_PATH NO_DEFAULT_PATH NO_SYSTEM_ENVIRONMENT_PATH ONLY_CMAKE_FIND_ROOT_PATH OS PATHS PATH_SUFFIXES VAR @@ -203,7 +209,7 @@ syn keyword cmakeKWinclude_external_msproject contained \ GUID MAP_IMPORTED_CONFIG_ PLATFORM TYPE WIX syn keyword cmakeKWinclude_guard contained - \ DIRECTORY GLOBAL + \ DIRECTORY GLOBAL TRUE __CURRENT_FILE_VAR__ syn keyword cmakeKWinstall contained \ ARCHIVE BUNDLE CODE COMPONENT CONFIGURATIONS CVS DESTDIR DESTINATION DIRECTORY DIRECTORY_PERMISSIONS DLL EXCLUDE_FROM_ALL EXPORT EXPORT_ANDROID_MK EXPORT_LINK_INTERFACE_LIBRARIES FILES FILES_MATCHING FILE_PERMISSIONS FRAMEWORK GROUP_EXECUTE GROUP_READ GROUP_WRITE IMPORTED_ INCLUDES INSTALL_PREFIX INTERFACE_INCLUDE_DIRECTORIES LIBRARY MACOSX_BUNDLE MESSAGE_NEVER NAMELINK_ONLY NAMELINK_SKIP NAMESPACE NDK OBJECTS OPTIONAL OWNER_EXECUTE OWNER_READ OWNER_WRITE PATTERN PERMISSIONS POST_INSTALL_SCRIPT PRE_INSTALL_SCRIPT PRIVATE_HEADER PROGRAMS PUBLIC_HEADER REGEX RENAME RESOURCE RUNTIME SCRIPT SETGID SETUID SOVERSION TARGETS TRUE USE_SOURCE_PERMISSIONS VERSION WORLD_EXECUTE WORLD_READ WORLD_WRITE @@ -275,7 +281,7 @@ syn keyword cmakeKWsource_group contained \ FILES PREFIX REGULAR_EXPRESSION TREE syn keyword cmakeKWstring contained - \ ALPHABET APPEND ASCII CMAKE_MATCH_ COMPARE CONCAT CONFIGURE EQUAL ESCAPE_QUOTES FIND GENEX_STRIP GREATER GREATER_EQUAL GUID HASH LENGTH LESS LESS_EQUAL MAKE_C_IDENTIFIER MATCH MATCHALL MATCHES NAMESPACE NOTEQUAL ONLY RANDOM RANDOM_SEED REGEX REPLACE REVERSE RFC SHA SOURCE_DATE_EPOCH STRIP SUBSTRING SZ TIMESTAMP TOLOWER TOUPPER TYPE US UTC UUID + \ ALPHABET APPEND ASCII CMAKE_MATCH_ COMPARE CONCAT CONFIGURE EQUAL ESCAPE_QUOTES FIND GENEX_STRIP GREATER GREATER_EQUAL GUID HASH LENGTH LESS LESS_EQUAL MAKE_C_IDENTIFIER MATCH MATCHALL MATCHES NAMESPACE NOTEQUAL ONLY PREPEND RANDOM RANDOM_SEED REGEX REPLACE REVERSE RFC SHA SOURCE_DATE_EPOCH STRIP SUBSTRING SZ TIMESTAMP TOLOWER TOUPPER TYPE US UTC UUID syn keyword cmakeKWsubdirs contained \ EXCLUDE_FROM_ALL PREORDER @@ -464,3 +470,8 @@ hi def link cmakeKWwhile ModeMsg hi def link cmakeKWwrite_file ModeMsg let b:current_syntax = "cmake" + +let &cpo = s:keepcpo +unlet s:keepcpo + +"EOF" diff --git a/CMakeCPack.cmake b/CMakeCPack.cmake index a0aacb4..dc9f0ba 100644 --- a/CMakeCPack.cmake +++ b/CMakeCPack.cmake @@ -245,5 +245,23 @@ configure_file("${CMake_SOURCE_DIR}/CMakeCPackOptions.cmake.in" "${CMake_BINARY_DIR}/CMakeCPackOptions.cmake" @ONLY) set(CPACK_PROJECT_CONFIG_FILE "${CMake_BINARY_DIR}/CMakeCPackOptions.cmake") +set(CPACK_SOURCE_IGNORE_FILES + # Files specific to version control. + "/\\\\.git/" + "/\\\\.gitattributes$" + "/\\\\.github/" + "/\\\\.gitignore$" + "/\\\\.hooks-config$" + + # Cygwin package build. + "/\\\\.build/" + + # Temporary files. + "\\\\.swp$" + "\\\\.#" + "/#" + "~$" + ) + # include CPack model once all variables are set include(CPack) diff --git a/CMakeCPackOptions.cmake.in b/CMakeCPackOptions.cmake.in index ad0c245..a08c97d 100644 --- a/CMakeCPackOptions.cmake.in +++ b/CMakeCPackOptions.cmake.in @@ -208,12 +208,6 @@ if(CPACK_GENERATOR MATCHES "IFW") endif() -if(CPACK_GENERATOR MATCHES "CygwinSource") - # when packaging source make sure the .build directory is not included - set(CPACK_SOURCE_IGNORE_FILES - "/CVS/" "/\\.build/" "/\\.svn/" "\\.swp$" "\\.#" "/#" "~$") -endif() - if("${CPACK_GENERATOR}" STREQUAL "PackageMaker") if(CMAKE_PACKAGE_QTGUI) set(CPACK_PACKAGE_DEFAULT_LOCATION "/Applications") diff --git a/CMakeLists.txt b/CMakeLists.txt index c9e632e..c578ec3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -753,6 +753,9 @@ add_subdirectory(Tests) if(NOT CMake_TEST_EXTERNAL_CMAKE) if(BUILD_TESTING) CMAKE_SET_TARGET_FOLDER(CMakeLibTests "Tests") + IF(TARGET CMakeServerLibTests) + CMAKE_SET_TARGET_FOLDER(CMakeServerLibTests "Tests") + ENDIF() endif() if(TARGET documentation) CMAKE_SET_TARGET_FOLDER(documentation "Documentation") diff --git a/Copyright.txt b/Copyright.txt index b7af4c5..3c92a81 100644 --- a/Copyright.txt +++ b/Copyright.txt @@ -69,12 +69,14 @@ The following individuals and institutions are among the Contributors: * Matthaeus G. Chajdas * Matthias Kretz <kretz@kde.org> * Matthias Maennich <matthias@maennich.net> +* Michael Stürmer * Miguel A. Figueroa-Villanueva * Mike Jackson * Mike McQuaid <mike@mikemcquaid.com> * Nicolas Bock <nicolasbock@gmail.com> * Nicolas Despres <nicolas.despres@gmail.com> * Nikita Krupen'ko <krnekit@gmail.com> +* NVIDIA Corporation <www.nvidia.com> * OpenGamma Ltd. <opengamma.com> * Per Øyvind Karlsen <peroyvind@mandriva.org> * Peter Collingbourne <peter@pcc.me.uk> diff --git a/Help/command/add_custom_command.rst b/Help/command/add_custom_command.rst index d038406..1b0aa14 100644 --- a/Help/command/add_custom_command.rst +++ b/Help/command/add_custom_command.rst @@ -225,3 +225,13 @@ of the following is specified: :command:`add_custom_target` command. ``POST_BUILD`` Run after all other rules within the target have been executed. + +.. note:: + Because generator expressions can be used in custom commands, + it is possible to define ``COMMAND`` lines or whole custom commands + which evaluate to empty strings for certain configurations. + For **Visual Studio 2010 (and newer)** generators these command + lines or custom commands will be omitted for the specific + configuration and no "empty-string-command" will be added. + + This allows to add individual build events for every configuration. diff --git a/Help/command/string.rst b/Help/command/string.rst index ba4a412..fb3893f 100644 --- a/Help/command/string.rst +++ b/Help/command/string.rst @@ -324,6 +324,7 @@ specifiers: %j The day of the current year (001-366). %m The month of the current year (01-12). %b Abbreviated month name (e.g. Oct). + %B Full month name (e.g. October). %M The minute of the current hour (00-59). %s Seconds since midnight (UTC) 1-Jan-1970 (UNIX time). %S The second of the current minute. @@ -331,6 +332,7 @@ specifiers: %U The week number of the current year (00-53). %w The day of the current week. 0 is Sunday. (0-6) %a Abbreviated weekday name (e.g. Fri). + %A Full weekday name (e.g. Friday). %y The last two digits of the current year (00-99) %Y The current year. diff --git a/Help/dev/source.rst b/Help/dev/source.rst index b40a884..96fc4a7 100644 --- a/Help/dev/source.rst +++ b/Help/dev/source.rst @@ -26,11 +26,9 @@ C++ Subset Permitted CMake requires compiling as C++11 or above. However, in order to support building on older toolchains some constructs need to be handled with care: -* Do not use ``CM_AUTO_PTR`` or ``std::auto_ptr``. +* Do not use ``std::auto_ptr``. - The ``std::auto_ptr`` template is deprecated in C++11. The ``CM_AUTO_PTR`` - macro remains leftover from C++98 support until its uses can be ported to - ``std::unique_ptr``. Do not add new uses of the macro. + The ``std::auto_ptr`` template is deprecated in C++11. Use ``std::unique_ptr``. * Use ``CM_EQ_DELETE;`` instead of ``= delete;``. diff --git a/Help/generator/CodeBlocks.rst b/Help/generator/CodeBlocks.rst index d03cb0c..06cc746 100644 --- a/Help/generator/CodeBlocks.rst +++ b/Help/generator/CodeBlocks.rst @@ -6,7 +6,11 @@ Generates CodeBlocks project files. Project files for CodeBlocks will be created in the top directory and in every subdirectory which features a CMakeLists.txt file containing a PROJECT() call. Additionally a hierarchy of makefiles is generated -into the build tree. The appropriate make program can build the +into the build tree. +The :variable:`CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES` variable may +be set to ``ON`` to exclude any files which are located outside of +the project root directory. +The appropriate make program can build the project through the default make target. A "make install" target is also provided. diff --git a/Help/manual/cmake-modules.7.rst b/Help/manual/cmake-modules.7.rst index fa6144c..8f4b252 100644 --- a/Help/manual/cmake-modules.7.rst +++ b/Help/manual/cmake-modules.7.rst @@ -153,6 +153,7 @@ All Modules /module/FindMPEG2 /module/FindMPEG /module/FindMPI + /module/FindOpenACC /module/FindOpenAL /module/FindOpenCL /module/FindOpenGL @@ -182,6 +183,7 @@ All Modules /module/FindosgWidget /module/FindPackageHandleStandardArgs /module/FindPackageMessage + /module/FindPatch /module/FindPerlLibs /module/FindPerl /module/FindPHP4 diff --git a/Help/manual/cmake-qt.7.rst b/Help/manual/cmake-qt.7.rst index 55121df..79e7e79 100644 --- a/Help/manual/cmake-qt.7.rst +++ b/Help/manual/cmake-qt.7.rst @@ -73,8 +73,8 @@ automatically added to the target's :prop_tgt:`INCLUDE_DIRECTORIES`. * This differs from CMake 3.7 and below; see their documentation for details. -* For multi configuration generators, the include directory is - ``<AUTOGEN_BUILD_DIR>/include_<CONFIG>``. +* For :prop_gbl:`multi configuration generators <GENERATOR_IS_MULTI_CONFIG>`, + the include directory is ``<AUTOGEN_BUILD_DIR>/include_<CONFIG>``. * See :prop_tgt:`AUTOGEN_BUILD_DIR`. @@ -133,8 +133,8 @@ automatically added to the target's :prop_tgt:`INCLUDE_DIRECTORIES`. * This differs from CMake 3.7 and below; see their documentation for details. -* For multi configuration generators, the include directory is - ``<AUTOGEN_BUILD_DIR>/include_<CONFIG>``. +* For :prop_gbl:`multi configuration generators <GENERATOR_IS_MULTI_CONFIG>`, + the include directory is ``<AUTOGEN_BUILD_DIR>/include_<CONFIG>``. * See :prop_tgt:`AUTOGEN_BUILD_DIR`. @@ -214,6 +214,24 @@ overrides options from the :prop_tgt:`AUTORCC_OPTIONS` target property. Source files can be excluded from :prop_tgt:`AUTORCC` processing by enabling :prop_sf:`SKIP_AUTORCC` or the broader :prop_sf:`SKIP_AUTOGEN`. +Visual Studio Generators +======================== + +When using the :manual:`Visual Studio generators <cmake-generators(7)>` +CMake tries to use a ``PRE_BUILD`` +:command:`custom command <add_custom_command>` instead +of a :command:`custom target <add_custom_target>` for autogen. +``PRE_BUILD`` can't be used when the autogen target depends on files. +This happens when + +- :prop_tgt:`AUTOMOC` or :prop_tgt:`AUTOUIC` is enabled and the origin target + depends on :prop_sf:`GENERATED` files which aren't excluded from autogen by + :prop_sf:`SKIP_AUTOMOC`, :prop_sf:`SKIP_AUTOUIC`, :prop_sf:`SKIP_AUTOGEN` + or :policy:`CMP0071` +- :prop_tgt:`AUTORCC` is enabled and a ``.qrc`` file is listed in + the origin target sources +- :prop_tgt:`AUTOGEN_TARGET_DEPENDS` lists a source file + qtmain.lib on Windows ===================== diff --git a/Help/manual/cmake-variables.7.rst b/Help/manual/cmake-variables.7.rst index ca9ce5b..cba81e5 100644 --- a/Help/manual/cmake-variables.7.rst +++ b/Help/manual/cmake-variables.7.rst @@ -121,6 +121,7 @@ Variables that Change Behavior /variable/CMAKE_AUTOMOC_RELAXED_MODE /variable/CMAKE_BACKWARDS_COMPATIBILITY /variable/CMAKE_BUILD_TYPE + /variable/CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES /variable/CMAKE_CODELITE_USE_TARGETS /variable/CMAKE_COLOR_MAKEFILE /variable/CMAKE_CONFIGURATION_TYPES diff --git a/Help/manual/cmake.1.rst b/Help/manual/cmake.1.rst index e159ced..6a21683 100644 --- a/Help/manual/cmake.1.rst +++ b/Help/manual/cmake.1.rst @@ -69,11 +69,11 @@ Options See `Find-Package Tool Mode`_. ``--graphviz=[file]`` - Generate graphviz of dependencies, see CMakeGraphVizOptions.cmake for more. + Generate graphviz of dependencies, see :module:`CMakeGraphVizOptions` for more. Generate a graphviz input file that will contain all the library and executable dependencies in the project. See the documentation for - CMakeGraphVizOptions.cmake for more details. + :module:`CMakeGraphVizOptions` for more details. ``--system-information [file]`` Dump information about this system. diff --git a/Help/manual/ctest.1.rst b/Help/manual/ctest.1.rst index 03466ce..423f1ca 100644 --- a/Help/manual/ctest.1.rst +++ b/Help/manual/ctest.1.rst @@ -886,6 +886,8 @@ Configuration settings include: * `CTest Script`_ variable: :variable:`CTEST_COVERAGE_EXTRA_FLAGS` * :module:`CTest` module variable: ``COVERAGE_EXTRA_FLAGS`` + These options are the first arguments passed to ``CoverageCommand``. + .. _`CTest MemCheck Step`: CTest MemCheck Step diff --git a/Help/module/FindOpenACC.rst b/Help/module/FindOpenACC.rst new file mode 100644 index 0000000..dda3308 --- /dev/null +++ b/Help/module/FindOpenACC.rst @@ -0,0 +1 @@ +.. cmake-module:: ../../Modules/FindOpenACC.cmake diff --git a/Help/module/FindPatch.rst b/Help/module/FindPatch.rst new file mode 100644 index 0000000..ba5e910 --- /dev/null +++ b/Help/module/FindPatch.rst @@ -0,0 +1 @@ +.. cmake-module:: ../../Modules/FindPatch.cmake diff --git a/Help/prop_test/PROCESSORS.rst b/Help/prop_test/PROCESSORS.rst index 763b6d0..a1211fb 100644 --- a/Help/prop_test/PROCESSORS.rst +++ b/Help/prop_test/PROCESSORS.rst @@ -1,8 +1,13 @@ PROCESSORS ---------- -How many process slots this test requires +Set to specify how many process slots this test requires. Denotes the number of processors that this test will require. This is typically used for MPI tests, and should be used in conjunction with -the ctest_test PARALLEL_LEVEL option. +the :command:`ctest_test` ``PARALLEL_LEVEL`` option. + +This will also be used to display a weighted test timing result in label and +subproject summaries in the command line output of :manual:`ctest(1)`. The wall +clock time for the test run will be multiplied by this property to give a +better idea of how much cpu resource CTest allocated for the test. diff --git a/Help/prop_tgt/AUTOMOC.rst b/Help/prop_tgt/AUTOMOC.rst index 61813be68..4542401 100644 --- a/Help/prop_tgt/AUTOMOC.rst +++ b/Help/prop_tgt/AUTOMOC.rst @@ -20,8 +20,8 @@ source files at build time and invoke moc accordingly. This allows the compiler to find the included ``moc_<basename>.cpp`` file regardless of the location the original source. - * For multi configuration generators, the include directory is - ``<AUTOGEN_BUILD_DIR>/include_<CONFIG>``. + * For :prop_gbl:`multi configuration generators <GENERATOR_IS_MULTI_CONFIG>`, + the include directory is ``<AUTOGEN_BUILD_DIR>/include_<CONFIG>``. * See :prop_tgt:`AUTOGEN_BUILD_DIR`. diff --git a/Help/prop_tgt/AUTOUIC.rst b/Help/prop_tgt/AUTOUIC.rst index 2fc2167..1791384 100644 --- a/Help/prop_tgt/AUTOUIC.rst +++ b/Help/prop_tgt/AUTOUIC.rst @@ -17,8 +17,8 @@ optional :prop_tgt:`AUTOUIC_SEARCH_PATHS` of the target. ``<AUTOGEN_BUILD_DIR>/include``, which is automatically added to the target's :prop_tgt:`INCLUDE_DIRECTORIES`. -* For multi configuration generators, the include directory is - ``<AUTOGEN_BUILD_DIR>/include_<CONFIG>``. +* For :prop_gbl:`multi configuration generators <GENERATOR_IS_MULTI_CONFIG>`, + the include directory is ``<AUTOGEN_BUILD_DIR>/include_<CONFIG>``. * See :prop_tgt:`AUTOGEN_BUILD_DIR`. diff --git a/Help/release/dev/FindEXPAT-importedtargets.rst b/Help/release/dev/FindEXPAT-importedtargets.rst new file mode 100644 index 0000000..ea73551 --- /dev/null +++ b/Help/release/dev/FindEXPAT-importedtargets.rst @@ -0,0 +1,4 @@ +FindEXPAT-importedtargets +------------------------- + +* The :module:`FindEXPAT` module now provides imported targets. diff --git a/Help/release/dev/FindFreetype-importedtargets.rst b/Help/release/dev/FindFreetype-importedtargets.rst new file mode 100644 index 0000000..a895883 --- /dev/null +++ b/Help/release/dev/FindFreetype-importedtargets.rst @@ -0,0 +1,4 @@ +FindFreetype-importedtargets +---------------------------- + +* The :module:`FindFreetype` module now provides imported targets. diff --git a/Help/release/dev/FindMPI-overhaul.rst b/Help/release/dev/FindMPI-overhaul.rst new file mode 100644 index 0000000..3bff602 --- /dev/null +++ b/Help/release/dev/FindMPI-overhaul.rst @@ -0,0 +1,16 @@ +findmpi-overhaul +---------------- + +* :module:`FindMPI` gained a number of new features, including: + + * Language-specific components have been added to the module. + * Many more MPI environments are now supported. + * The environmental support for Fortran has been improved. + * A user now has fine-grained control over the MPI selection process, + including passing custom parameters to the MPI compiler. + * The version of the implemented MPI standard is now being exposed. + * MPI-2 C++ bindings can now be detected and also suppressed if so desired. + * The available Fortran bindings are now being detected and verified. + * Various MPI-3 information can be requested, including the library version + and Fortran capabilities of the individual bindings. + * Statically linked MPI implementations are supported. diff --git a/Help/release/dev/FindOpenACC.rst b/Help/release/dev/FindOpenACC.rst new file mode 100644 index 0000000..f6acbdf --- /dev/null +++ b/Help/release/dev/FindOpenACC.rst @@ -0,0 +1,5 @@ +FindOpenACC +----------- + +* A :module:`FindOpenACC` module was added to detect compiler support + for OpenACC. Currently only supports PGI, GNU and Cray compilers. diff --git a/Help/release/dev/FindOpenGL-glvnd.rst b/Help/release/dev/FindOpenGL-glvnd.rst new file mode 100644 index 0000000..b3c8d53 --- /dev/null +++ b/Help/release/dev/FindOpenGL-glvnd.rst @@ -0,0 +1,4 @@ +FindOpenGL-glvnd +---------------- + +* The :module:`FindOpenGL` module gained support for GLVND on Linux. diff --git a/Help/release/dev/codeblocks-exclude-external.rst b/Help/release/dev/codeblocks-exclude-external.rst new file mode 100644 index 0000000..4c758e3 --- /dev/null +++ b/Help/release/dev/codeblocks-exclude-external.rst @@ -0,0 +1,6 @@ +codeblocks-exclude-external +--------------------------- + +* A :variable:`CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES` variable was added + to tell the :generator:`CodeBlocks` extra generator to exclude files + from outside the project root directory from the generated project files. diff --git a/Help/release/dev/cpack-rpm-deb-version.rst b/Help/release/dev/cpack-rpm-deb-version.rst new file mode 100644 index 0000000..a64e8bd --- /dev/null +++ b/Help/release/dev/cpack-rpm-deb-version.rst @@ -0,0 +1,14 @@ +cpack-rpm-deb-version +--------------------- + +* Modules :module:`CPackRPM` and :module:`CPackDeb` learned to set package epoch + version. + See :variable:`CPACK_RPM_PACKAGE_EPOCH` and + :variable:`CPACK_DEBIAN_PACKAGE_EPOCH` variables. + +* The :module:`CPackDeb` module learned to set package release version in + `Version` info property. + See :variable:`CPACK_DEBIAN_PACKAGE_RELEASE` variable. + +* The :module:`CPackDeb` module learned more strict package version checking + that complies with Debian rules. diff --git a/Help/release/dev/cpackifw-options.rst b/Help/release/dev/cpackifw-options.rst new file mode 100644 index 0000000..7c471f4 --- /dev/null +++ b/Help/release/dev/cpackifw-options.rst @@ -0,0 +1,6 @@ +cpackifw-options +---------------- + +* The :module:`CPackIFW` module :command:`cpack_ifw_configure_component` and + :command:`cpack_ifw_configure_component_group` commands gained a new + ``REPLACES`` and ``CHECKABLE`` options. diff --git a/Help/release/dev/find-patch.rst b/Help/release/dev/find-patch.rst new file mode 100644 index 0000000..d720c81 --- /dev/null +++ b/Help/release/dev/find-patch.rst @@ -0,0 +1,5 @@ +find-patch +---------- + +* A :module:`FindPatch` module was added to find the ``patch`` + command-line executable. diff --git a/Help/release/dev/findopenmp-components.rst b/Help/release/dev/findopenmp-components.rst new file mode 100644 index 0000000..243abfa --- /dev/null +++ b/Help/release/dev/findopenmp-components.rst @@ -0,0 +1,5 @@ +findopenmp-components +--------------------- + +* The :module:`FindOpenMP` module gained support for + language-specific components. diff --git a/Help/release/dev/flang.rst b/Help/release/dev/flang.rst new file mode 100644 index 0000000..9849f14 --- /dev/null +++ b/Help/release/dev/flang.rst @@ -0,0 +1,6 @@ +flang +----- + +* The `flang`_ Fortran compiler is now supported, with compiler id ``Flang``. + +.. _`flang`: https://github.com/flang-compiler/flang diff --git a/Help/release/dev/freebsd-compiler-name.rst b/Help/release/dev/freebsd-compiler-name.rst new file mode 100644 index 0000000..ece7596 --- /dev/null +++ b/Help/release/dev/freebsd-compiler-name.rst @@ -0,0 +1,4 @@ +freebsd-compiler-name +--------------------- + +* On FreeBSD the C++ compiler named ``c++`` is now the preferred default. diff --git a/Help/release/dev/get_filename_component-fix-program-split.rst b/Help/release/dev/get_filename_component-fix-program-split.rst new file mode 100644 index 0000000..55c8719 --- /dev/null +++ b/Help/release/dev/get_filename_component-fix-program-split.rst @@ -0,0 +1,9 @@ +get_filename_component-fix-program-split +---------------------------------------- + +* The :command:`get_filename_component` ``PROGRAM`` mode semantics + have been revised to not tolerate unquoted spaces in the path + to the program while also accepting arguments. While technically + incompatible with the old behavior, it is expected that behavior + under typical use cases with properly-quoted command-lines has + not changed. diff --git a/Help/release/dev/graphviz-line-styles.rst b/Help/release/dev/graphviz-line-styles.rst new file mode 100644 index 0000000..d24f236 --- /dev/null +++ b/Help/release/dev/graphviz-line-styles.rst @@ -0,0 +1,6 @@ +graphviz-line-styles +------------------------- + +* The graphviz output now distinguishes between the different dependency types + ``PUBLIC``, ``PRIVATE`` and ``INTERFACE`` and represents them in the output graph + as solid, dashed and dotted edges. diff --git a/Help/release/dev/irsl-intel.rst b/Help/release/dev/irsl-intel.rst new file mode 100644 index 0000000..330fcc6 --- /dev/null +++ b/Help/release/dev/irsl-intel.rst @@ -0,0 +1,5 @@ +irsl-intel +---------- + +* The :module:`InstallRequiredSystemLibraries` gained support for installing + Intel compiler runtimes. diff --git a/Help/release/dev/midipix-support.rst b/Help/release/dev/midipix-support.rst new file mode 100644 index 0000000..adc971e --- /dev/null +++ b/Help/release/dev/midipix-support.rst @@ -0,0 +1,4 @@ +midipix-support +--------------- + +* A new minimal platform file for ``Midipix`` was added. diff --git a/Help/release/dev/msvc-arm64.rst b/Help/release/dev/msvc-arm64.rst new file mode 100644 index 0000000..c8fadd4 --- /dev/null +++ b/Help/release/dev/msvc-arm64.rst @@ -0,0 +1,5 @@ +msvc-arm64 +---------- + +* Support for the MSVC ARM64 architecture was added. + Visual Studio 2017 Update 4 and above offer an ARM64 toolchain. diff --git a/Help/release/dev/timestamp.rst b/Help/release/dev/timestamp.rst new file mode 100644 index 0000000..e40009e --- /dev/null +++ b/Help/release/dev/timestamp.rst @@ -0,0 +1,5 @@ +timestamp +--------- + +* The :command:`string(TIMESTAMP)` command now supports ``%A`` + for full weekday name and ``%B`` for full month name. diff --git a/Help/variable/APPLE.rst b/Help/variable/APPLE.rst index 75eecf1..810d5fc 100644 --- a/Help/variable/APPLE.rst +++ b/Help/variable/APPLE.rst @@ -1,6 +1,5 @@ APPLE ----- -``True`` if running on OS X. - -Set to ``true`` on OS X. +Set to ``True`` when the target system is an Apple platform +(macOS, iOS, tvOS or watchOS). diff --git a/Help/variable/CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES.rst b/Help/variable/CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES.rst new file mode 100644 index 0000000..80ffce3 --- /dev/null +++ b/Help/variable/CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES.rst @@ -0,0 +1,7 @@ +CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES +--------------------------------------- + +Change the way the CodeBlocks generator creates project files. + +If this variable evaluates to ``ON`` the generator excludes from +the project file any files that are located outside the project root. diff --git a/Help/variable/CMAKE_FIND_NO_INSTALL_PREFIX.rst b/Help/variable/CMAKE_FIND_NO_INSTALL_PREFIX.rst index c49d264..789dc99 100644 --- a/Help/variable/CMAKE_FIND_NO_INSTALL_PREFIX.rst +++ b/Help/variable/CMAKE_FIND_NO_INSTALL_PREFIX.rst @@ -1,15 +1,19 @@ CMAKE_FIND_NO_INSTALL_PREFIX ---------------------------- -Ignore the :variable:`CMAKE_INSTALL_PREFIX` when searching for assets. +Exclude the values of the :variable:`CMAKE_INSTALL_PREFIX` and +:variable:`CMAKE_STAGING_PREFIX` variables from +:variable:`CMAKE_SYSTEM_PREFIX_PATH`. CMake adds these project-destination +prefixes to :variable:`CMAKE_SYSTEM_PREFIX_PATH` by default in order to +support building a series of dependent packages and installing them into +a common prefix. Set ``CMAKE_FIND_NO_INSTALL_PREFIX`` to ``TRUE`` +to suppress this behavior. -CMake adds the :variable:`CMAKE_INSTALL_PREFIX` and the -:variable:`CMAKE_STAGING_PREFIX` variable to the -:variable:`CMAKE_SYSTEM_PREFIX_PATH` by default. This variable may be set -on the command line to control that behavior. +The :variable:`CMAKE_SYSTEM_PREFIX_PATH` is initialized on the first call to a +:command:`project` or :command:`enable_language` command. Therefore one must +set ``CMAKE_FIND_NO_INSTALL_PREFIX`` before this in order to take effect. A +user may set the variable as a cache entry on the command line to achieve this. -Set ``CMAKE_FIND_NO_INSTALL_PREFIX`` to ``TRUE`` to tell -:command:`find_package` not to search in the :variable:`CMAKE_INSTALL_PREFIX` -or :variable:`CMAKE_STAGING_PREFIX` by default. Note that the -prefix may still be searched for other reasons, such as being the same prefix -as the CMake installation, or for being a built-in system prefix. +Note that the prefix(es) may still be searched for other reasons, such as being +the same prefix as the CMake installation, or for being a built-in system +prefix. diff --git a/Help/variable/CMAKE_LANG_COMPILER_ID.rst b/Help/variable/CMAKE_LANG_COMPILER_ID.rst index 5204044..2264269 100644 --- a/Help/variable/CMAKE_LANG_COMPILER_ID.rst +++ b/Help/variable/CMAKE_LANG_COMPILER_ID.rst @@ -27,6 +27,7 @@ include: NVIDIA = NVIDIA CUDA Compiler (nvidia.com) OpenWatcom = Open Watcom (openwatcom.org) PGI = The Portland Group (pgroup.com) + Flang = Flang Fortran Compiler PathScale = PathScale (pathscale.com) SDCC = Small Device C Compiler (sdcc.sourceforge.net) SunPro = Oracle Solaris Studio (oracle.com) diff --git a/Help/variable/CMAKE_SYSTEM_PREFIX_PATH.rst b/Help/variable/CMAKE_SYSTEM_PREFIX_PATH.rst index e74dfad..38b2f8d 100644 --- a/Help/variable/CMAKE_SYSTEM_PREFIX_PATH.rst +++ b/Help/variable/CMAKE_SYSTEM_PREFIX_PATH.rst @@ -10,8 +10,11 @@ documentation. By default this contains the standard directories for the current system, the :variable:`CMAKE_INSTALL_PREFIX`, and the :variable:`CMAKE_STAGING_PREFIX`. -It is *not* intended to be modified by the project; use -:variable:`CMAKE_PREFIX_PATH` for this. +The installation and staging prefixes may be excluded by setting +the :variable:`CMAKE_FIND_NO_INSTALL_PREFIX` variable. + +``CMAKE_SYSTEM_PREFIX_PATH`` is *not* intended to be modified by the project; +use :variable:`CMAKE_PREFIX_PATH` for this. See also :variable:`CMAKE_SYSTEM_INCLUDE_PATH`, :variable:`CMAKE_SYSTEM_LIBRARY_PATH`, :variable:`CMAKE_SYSTEM_PROGRAM_PATH`, diff --git a/Help/variable/MSVC_VERSION.rst b/Help/variable/MSVC_VERSION.rst index 8932147..0a3a7a6 100644 --- a/Help/variable/MSVC_VERSION.rst +++ b/Help/variable/MSVC_VERSION.rst @@ -5,13 +5,15 @@ The version of Microsoft Visual C/C++ being used if any. Known version numbers are:: - 1200 = VS 6.0 - 1300 = VS 7.0 - 1310 = VS 7.1 - 1400 = VS 8.0 - 1500 = VS 9.0 - 1600 = VS 10.0 - 1700 = VS 11.0 - 1800 = VS 12.0 - 1900 = VS 14.0 - 1910 = VS 15.0 + 1200 = VS 6.0 + 1300 = VS 7.0 + 1310 = VS 7.1 + 1400 = VS 8.0 (v80 toolset) + 1500 = VS 9.0 (v90 toolset) + 1600 = VS 10.0 (v100 toolset) + 1700 = VS 11.0 (v110 toolset) + 1800 = VS 12.0 (v120 toolset) + 1900 = VS 14.0 (v140 toolset) + 1910-1919 = VS 15.0 (v141 toolset) + +See also the :variable:`CMAKE_<LANG>_COMPILER_VERSION` variable. diff --git a/Help/variable/UNIX.rst b/Help/variable/UNIX.rst index 0877b7c..49d8668 100644 --- a/Help/variable/UNIX.rst +++ b/Help/variable/UNIX.rst @@ -1,7 +1,7 @@ UNIX ---- -``True`` for UNIX and UNIX like operating systems. - -Set to ``true`` when the target system is UNIX or UNIX like (i.e. -:variable:`APPLE` and :variable:`CYGWIN`). +Set to ``True`` when the target system is UNIX or UNIX-like +(e.g. :variable:`APPLE` and :variable:`CYGWIN`). The +:variable:`CMAKE_SYSTEM_NAME` variable should be queried if +a more specific understanding of the target system is required. diff --git a/Help/variable/WIN32.rst b/Help/variable/WIN32.rst index 2189069..78ab772 100644 --- a/Help/variable/WIN32.rst +++ b/Help/variable/WIN32.rst @@ -1,6 +1,4 @@ WIN32 ----- -``True`` on Windows systems, including Win64. - -Set to ``true`` when the target system is Windows. +Set to ``True`` when the target system is Windows, including Win64. diff --git a/Modules/AutogenInfo.cmake.in b/Modules/AutogenInfo.cmake.in index 60ceebc..7f4b398 100644 --- a/Modules/AutogenInfo.cmake.in +++ b/Modules/AutogenInfo.cmake.in @@ -1,3 +1,5 @@ +# Meta +set(AM_MULTI_CONFIG @_multi_config@) # Directories and files set(AM_CMAKE_BINARY_DIR "@CMAKE_BINARY_DIR@/") set(AM_CMAKE_SOURCE_DIR "@CMAKE_SOURCE_DIR@/") @@ -9,13 +11,14 @@ set(AM_SOURCES @_sources@) set(AM_HEADERS @_headers@) # Qt environment set(AM_QT_VERSION_MAJOR @_qt_version_major@) +set(AM_QT_VERSION_MINOR @_qt_version_minor@) set(AM_QT_MOC_EXECUTABLE @_qt_moc_executable@) set(AM_QT_UIC_EXECUTABLE @_qt_uic_executable@) set(AM_QT_RCC_EXECUTABLE @_qt_rcc_executable@) # MOC settings set(AM_MOC_SKIP @_moc_skip@) set(AM_MOC_DEFINITIONS @_moc_compile_defs@) -set(AM_MOC_INCLUDES @_moc_incs@) +set(AM_MOC_INCLUDES @_moc_include_dirs@) set(AM_MOC_OPTIONS @_moc_options@) set(AM_MOC_RELAXED_MODE @_moc_relaxed_mode@) set(AM_MOC_MACRO_NAMES @_moc_macro_names@) @@ -28,7 +31,7 @@ set(AM_UIC_OPTIONS_FILES @_qt_uic_options_files@) set(AM_UIC_OPTIONS_OPTIONS @_qt_uic_options_options@) set(AM_UIC_SEARCH_PATHS @_uic_search_paths@) # RCC settings -set(AM_RCC_SOURCES @_rcc_files@ ) +set(AM_RCC_SOURCES @_rcc_files@) +set(AM_RCC_BUILDS @_rcc_builds@) +set(AM_RCC_OPTIONS @_rcc_options@) set(AM_RCC_INPUTS @_rcc_inputs@) -set(AM_RCC_OPTIONS_FILES @_rcc_options_files@) -set(AM_RCC_OPTIONS_OPTIONS @_rcc_options_options@) diff --git a/Modules/CMakeCSharpInformation.cmake b/Modules/CMakeCSharpInformation.cmake index d474c29..25f869c 100644 --- a/Modules/CMakeCSharpInformation.cmake +++ b/Modules/CMakeCSharpInformation.cmake @@ -43,7 +43,7 @@ endif() # on the initial values computed in the platform/*.cmake files # use _INIT variables so that this only happens the first time # and you can set these flags in the cmake cache -set(CMAKE_CSharp_FLAGS_INIT "$ENV{CSharpFLAGS} ${CMAKE_CSharp_FLAGS_INIT}") +set(CMAKE_CSharp_FLAGS_INIT "$ENV{CSFLAGS} ${CMAKE_CSharp_FLAGS_INIT}") # avoid just having a space as the initial value for the cache if(CMAKE_CSharp_FLAGS_INIT STREQUAL " ") set(CMAKE_CSharp_FLAGS_INIT) diff --git a/Modules/CMakeDetermineCompilerId.cmake b/Modules/CMakeDetermineCompilerId.cmake index f11059f..cddc966 100644 --- a/Modules/CMakeDetermineCompilerId.cmake +++ b/Modules/CMakeDetermineCompilerId.cmake @@ -220,7 +220,9 @@ Id flags: ${testflags} ${CMAKE_${lang}_COMPILER_ID_FLAGS_ALWAYS} if(CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION) set(id_WindowsTargetPlatformVersion "<WindowsTargetPlatformVersion>${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}</WindowsTargetPlatformVersion>") endif() - if(id_platform STREQUAL ARM) + if(id_platform STREQUAL ARM64) + set(id_WindowsSDKDesktopARMSupport "<WindowsSDKDesktopARM64Support>true</WindowsSDKDesktopARM64Support>") + elseif(id_platform STREQUAL ARM) set(id_WindowsSDKDesktopARMSupport "<WindowsSDKDesktopARMSupport>true</WindowsSDKDesktopARMSupport>") else() set(id_WindowsSDKDesktopARMSupport "") @@ -319,12 +321,19 @@ Id flags: ${testflags} ${CMAKE_${lang}_COMPILER_ID_FLAGS_ALWAYS} set(id_product_type "com.apple.product-type.tool") if(CMAKE_OSX_SYSROOT) set(id_sdkroot "SDKROOT = \"${CMAKE_OSX_SYSROOT}\";") - if(CMAKE_OSX_SYSROOT MATCHES "(^|/)[Ii][Pp][Hh][Oo][Nn][Ee]") + if(CMAKE_OSX_SYSROOT MATCHES "(^|/)[Ii][Pp][Hh][Oo][Nn][Ee]" OR + CMAKE_OSX_SYSROOT MATCHES "(^|/)[Aa][Pp][Pp][Ll][Ee][Tt][Vv]") set(id_product_type "com.apple.product-type.bundle.unit-test") endif() else() set(id_sdkroot "") endif() + if(CMAKE_XCODE_ATTRIBUTE_DEVELOPMENT_TEAM) + set(id_development_team + "DEVELOPMENT_TEAM = \"${CMAKE_XCODE_ATTRIBUTE_DEVELOPMENT_TEAM}\";") + else() + set(id_development_team "") + endif() configure_file(${CMAKE_ROOT}/Modules/CompilerId/Xcode-3.pbxproj.in ${id_dir}/CompilerId${lang}.xcodeproj/project.pbxproj @ONLY) unset(_ENV_MACOSX_DEPLOYMENT_TARGET) diff --git a/Modules/CMakeDetermineFortranCompiler.cmake b/Modules/CMakeDetermineFortranCompiler.cmake index 5559640..2549c22 100644 --- a/Modules/CMakeDetermineFortranCompiler.cmake +++ b/Modules/CMakeDetermineFortranCompiler.cmake @@ -52,6 +52,7 @@ else() # frt: Fujitsu F77 compiler # pathf90/pathf95/pathf2003: PathScale Fortran compiler # pgf77/pgf90/pgf95/pgfortran: Portland Group F77/F90/F95 compilers + # flang: Flang Fortran compiler # xlf/xlf90/xlf95: IBM (AIX) F77/F90/F95 compilers # lf95: Lahey-Fujitsu F95 compiler # fl32: Microsoft Fortran 77 "PowerStation" compiler @@ -68,7 +69,7 @@ else() set(CMAKE_Fortran_COMPILER_LIST ftn ifort ifc af95 af90 efc f95 pathf2003 pathf95 pgf95 pgfortran lf95 xlf95 - fort gfortran gfortran-4 g95 f90 pathf90 pgf90 xlf90 epcf90 fort77 + fort flang gfortran gfortran-4 g95 f90 pathf90 pgf90 xlf90 epcf90 fort77 frt pgf77 xlf fl32 af77 g77 f77 nag ) @@ -77,10 +78,11 @@ else() set(_Fortran_COMPILER_NAMES_Intel ifort ifc efc) set(_Fortran_COMPILER_NAMES_Absoft af95 af90 af77) set(_Fortran_COMPILER_NAMES_PGI pgf95 pgfortran pgf90 pgf77) + set(_Fortran_COMPILER_NAMES_Flang flang) set(_Fortran_COMPILER_NAMES_PathScale pathf2003 pathf95 pathf90) set(_Fortran_COMPILER_NAMES_XL xlf) set(_Fortran_COMPILER_NAMES_VisualAge xlf95 xlf90 xlf) - set(_Fortran_COMPILER_NAMES_NAG nagfor) + set(_Fortran_COMPILER_NAMES_NAG nagfor) endif() _cmake_find_compiler(Fortran) diff --git a/Modules/CMakeFindDependencyMacro.cmake b/Modules/CMakeFindDependencyMacro.cmake index 81606ce..6a89fff 100644 --- a/Modules/CMakeFindDependencyMacro.cmake +++ b/Modules/CMakeFindDependencyMacro.cmake @@ -1,23 +1,34 @@ # Distributed under the OSI-approved BSD 3-Clause License. See accompanying # file Copyright.txt or https://cmake.org/licensing for details. -#.rst: -# CMakeFindDependencyMacro -# ------------------------- -# -# :: -# -# find_dependency(<dep> [...]) -# -# -# ``find_dependency()`` wraps a :command:`find_package` call for a package -# dependency. It is designed to be used in a <package>Config.cmake file, and it -# forwards the correct parameters for QUIET and REQUIRED which were passed to -# the original :command:`find_package` call. It also sets an informative -# diagnostic message if the dependency could not be found. -# -# Any additional arguments specified are forwarded to :command:`find_package`. -# +#[=======================================================================[.rst: +CMakeFindDependencyMacro +------------------------- + +.. command:: find_dependency + + The ``find_dependency()`` macro wraps a :command:`find_package` call for + a package dependency:: + + find_dependency(<dep> [...]) + + It is designed to be used in a + :ref:`Package Configuration File <Config File Packages>` + (``<package>Config.cmake``). ``find_dependency`` forwards the correct + parameters for ``QUIET`` and ``REQUIRED`` which were passed to + the original :command:`find_package` call. Any additional arguments + specified are forwarded to :command:`find_package`. + + If the dependency could not be found it sets an informative diagnostic + message and calls :command:`return` to end processing of the calling + package configuration file and return to the :command:`find_package` + command that loaded it. + + .. note:: + + The call to :command:`return` makes this macro unsuitable to call + from :ref:`Find Modules`. +#]=======================================================================] macro(find_dependency dep) if (NOT ${dep}_FOUND) diff --git a/Modules/CMakeFortranCompilerId.F.in b/Modules/CMakeFortranCompilerId.F.in index 26b2ed6..49789f1 100644 --- a/Modules/CMakeFortranCompilerId.F.in +++ b/Modules/CMakeFortranCompilerId.F.in @@ -90,6 +90,13 @@ # if defined(__PGIC_PATCHLEVEL__) # define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__) # endif +#elif defined(__FLANG) + PRINT *, 'INFO:compiler[Flang]' +# define COMPILER_VERSION_MAJOR DEC(__FLANG_MAJOR__) +# define COMPILER_VERSION_MINOR DEC(__FLANG_MINOR__) +# if defined(__FLANG_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__FLANG_PATCHLEVEL__) +# endif #elif defined(_SGI_COMPILER_VERSION) || defined(_COMPILER_VERSION) PRINT *, 'INFO:compiler[MIPSpro]' # if 0 diff --git a/Modules/CMakeGenericSystem.cmake b/Modules/CMakeGenericSystem.cmake index cd05237..9c38f6e 100644 --- a/Modules/CMakeGenericSystem.cmake +++ b/Modules/CMakeGenericSystem.cmake @@ -76,6 +76,8 @@ function(GetDefaultWindowsPrefixBase var) # if("${CMAKE_GENERATOR}" MATCHES "(Win64|IA64)") set(arch_hint "x64") + elseif("${CMAKE_GENERATOR_PLATFORM}" MATCHES "ARM64") + set(arch_hint "ARM64") elseif("${CMAKE_GENERATOR}" MATCHES "ARM") set(arch_hint "ARM") elseif("${CMAKE_SIZEOF_VOID_P}" STREQUAL "8") diff --git a/Modules/CMakeGraphVizOptions.cmake b/Modules/CMakeGraphVizOptions.cmake index 420e3a9..0d7f1d9 100644 --- a/Modules/CMakeGraphVizOptions.cmake +++ b/Modules/CMakeGraphVizOptions.cmake @@ -11,19 +11,22 @@ # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # # CMake -# can generate graphviz files, showing the dependencies between the +# can generate `graphviz <http://www.graphviz.org/>`_ files, showing the dependencies between the # targets in a project and also external libraries which are linked -# against. When CMake is run with the --graphviz=foo.dot option, it will +# against. When CMake is run with the ``--graphviz=foo.dot`` option, it will # produce: # -# * a foo.dot file showing all dependencies in the project -# * a foo.dot.<target> file for each target, file showing on which other targets the respective target depends -# * a foo.dot.<target>.dependers file, showing which other targets depend on the respective target +# * a ``foo.dot`` file showing all dependencies in the project +# * a ``foo.dot.<target>`` file for each target, file showing on which other targets the respective target depends +# * a ``foo.dot.<target>.dependers`` file, showing which other targets depend on the respective target +# +# The different dependency types ``PUBLIC``, ``PRIVATE`` and ``INTERFACE`` +# are represented as solid, dashed and dotted edges. # # This can result in huge graphs. Using the file -# CMakeGraphVizOptions.cmake the look and content of the generated +# ``CMakeGraphVizOptions.cmake`` the look and content of the generated # graphs can be influenced. This file is searched first in -# ${CMAKE_BINARY_DIR} and then in ${CMAKE_SOURCE_DIR}. If found, it is +# :variable:`CMAKE_BINARY_DIR` and then in :variable:`CMAKE_SOURCE_DIR`. If found, it is # read and the variables set in it are used to adjust options for the # generated graphviz files. # diff --git a/Modules/CMakePlatformId.h.in b/Modules/CMakePlatformId.h.in index c7065b2..a6a9c0a 100644 --- a/Modules/CMakePlatformId.h.in +++ b/Modules/CMakePlatformId.h.in @@ -114,6 +114,9 @@ # elif defined(_M_IX86) # define ARCHITECTURE_ID "X86" +# elif defined(_M_ARM64) +# define ARCHITECTURE_ID "ARM64" + # elif defined(_M_ARM) # if _M_ARM == 4 # define ARCHITECTURE_ID "ARMV4I" diff --git a/Modules/CMakeTestCCompiler.cmake b/Modules/CMakeTestCCompiler.cmake index 7f19969..e34ae75 100644 --- a/Modules/CMakeTestCCompiler.cmake +++ b/Modules/CMakeTestCCompiler.cmake @@ -48,9 +48,10 @@ if(NOT CMAKE_C_COMPILER_WORKS) file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log "Determining if the C compiler works failed with " "the following output:\n${__CMAKE_C_COMPILER_OUTPUT}\n\n") - message(FATAL_ERROR "The C compiler \"${CMAKE_C_COMPILER}\" " + string(REPLACE "\n" "\n " _output "${__CMAKE_C_COMPILER_OUTPUT}") + message(FATAL_ERROR "The C compiler\n \"${CMAKE_C_COMPILER}\"\n" "is not able to compile a simple test program.\nIt fails " - "with the following output:\n ${__CMAKE_C_COMPILER_OUTPUT}\n\n" + "with the following output:\n ${_output}\n\n" "CMake will not be able to correctly generate this project.") else() if(C_TEST_WAS_RUN) diff --git a/Modules/CMakeTestCSharpCompiler.cmake b/Modules/CMakeTestCSharpCompiler.cmake index 1a8bf32..f3b95fd 100644 --- a/Modules/CMakeTestCSharpCompiler.cmake +++ b/Modules/CMakeTestCSharpCompiler.cmake @@ -42,9 +42,10 @@ if(NOT CMAKE_CSharp_COMPILER_WORKS) file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log "Determining if the C# compiler works failed with " "the following output:\n${__CMAKE_CSharp_COMPILER_OUTPUT}\n\n") - message(FATAL_ERROR "The C# compiler \"${CMAKE_CSharp_COMPILER}\" " + string(REPLACE "\n" "\n " _output "${__CMAKE_CSharp_COMPILER_OUTPUT}") + message(FATAL_ERROR "The C# compiler\n \"${CMAKE_CSharp_COMPILER}\"\n" "is not able to compile a simple test program.\nIt fails " - "with the following output:\n ${__CMAKE_CSharp_COMPILER_OUTPUT}\n\n" + "with the following output:\n ${_output}\n\n" "CMake will not be able to correctly generate this project.") else() if(CSharp_TEST_WAS_RUN) diff --git a/Modules/CMakeTestCUDACompiler.cmake b/Modules/CMakeTestCUDACompiler.cmake index 80113cb..df5ec72 100644 --- a/Modules/CMakeTestCUDACompiler.cmake +++ b/Modules/CMakeTestCUDACompiler.cmake @@ -42,9 +42,10 @@ if(NOT CMAKE_CUDA_COMPILER_WORKS) file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log "Determining if the CUDA compiler works failed with " "the following output:\n${__CMAKE_CUDA_COMPILER_OUTPUT}\n\n") - message(FATAL_ERROR "The CUDA compiler \"${CMAKE_CUDA_COMPILER}\" " + string(REPLACE "\n" "\n " _output "${__CMAKE_CUDA_COMPILER_OUTPUT}") + message(FATAL_ERROR "The CUDA compiler\n \"${CMAKE_CUDA_COMPILER}\"\n" "is not able to compile a simple test program.\nIt fails " - "with the following output:\n ${__CMAKE_CUDA_COMPILER_OUTPUT}\n\n" + "with the following output:\n ${_output}\n\n" "CMake will not be able to correctly generate this project.") else() if(CUDA_TEST_WAS_RUN) diff --git a/Modules/CMakeTestCXXCompiler.cmake b/Modules/CMakeTestCXXCompiler.cmake index a31067b..7b80dc0 100644 --- a/Modules/CMakeTestCXXCompiler.cmake +++ b/Modules/CMakeTestCXXCompiler.cmake @@ -41,9 +41,10 @@ if(NOT CMAKE_CXX_COMPILER_WORKS) file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log "Determining if the CXX compiler works failed with " "the following output:\n${__CMAKE_CXX_COMPILER_OUTPUT}\n\n") - message(FATAL_ERROR "The C++ compiler \"${CMAKE_CXX_COMPILER}\" " + string(REPLACE "\n" "\n " _output "${__CMAKE_CXX_COMPILER_OUTPUT}") + message(FATAL_ERROR "The C++ compiler\n \"${CMAKE_CXX_COMPILER}\"\n" "is not able to compile a simple test program.\nIt fails " - "with the following output:\n ${__CMAKE_CXX_COMPILER_OUTPUT}\n\n" + "with the following output:\n ${_output}\n\n" "CMake will not be able to correctly generate this project.") else() if(CXX_TEST_WAS_RUN) diff --git a/Modules/CMakeTestFortranCompiler.cmake b/Modules/CMakeTestFortranCompiler.cmake index c81694e..3c150a8 100644 --- a/Modules/CMakeTestFortranCompiler.cmake +++ b/Modules/CMakeTestFortranCompiler.cmake @@ -41,9 +41,10 @@ if(NOT CMAKE_Fortran_COMPILER_WORKS) file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log "Determining if the Fortran compiler works failed with " "the following output:\n${OUTPUT}\n\n") - message(FATAL_ERROR "The Fortran compiler \"${CMAKE_Fortran_COMPILER}\" " + string(REPLACE "\n" "\n " _output "${OUTPUT}") + message(FATAL_ERROR "The Fortran compiler\n \"${CMAKE_Fortran_COMPILER}\"\n" "is not able to compile a simple test program.\nIt fails " - "with the following output:\n ${OUTPUT}\n\n" + "with the following output:\n ${_output}\n\n" "CMake will not be able to correctly generate this project.") else() if(FORTRAN_TEST_WAS_RUN) diff --git a/Modules/CMakeTestSwiftCompiler.cmake b/Modules/CMakeTestSwiftCompiler.cmake index 6393f44..bcd5c33 100644 --- a/Modules/CMakeTestSwiftCompiler.cmake +++ b/Modules/CMakeTestSwiftCompiler.cmake @@ -39,9 +39,10 @@ if(NOT CMAKE_Swift_COMPILER_WORKS) file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log "Determining if the Swift compiler works failed with " "the following output:\n${__CMAKE_Swift_COMPILER_OUTPUT}\n\n") - message(FATAL_ERROR "The Swift compiler \"${CMAKE_Swift_COMPILER}\" " + string(REPLACE "\n" "\n " _output "${__CMAKE_Swift_COMPILER_OUTPUT}") + message(FATAL_ERROR "The Swift compiler\n \"${CMAKE_Swift_COMPILER}\"\n" "is not able to compile a simple test program.\nIt fails " - "with the following output:\n ${__CMAKE_Swift_COMPILER_OUTPUT}\n\n" + "with the following output:\n ${_output}\n\n" "CMake will not be able to correctly generate this project.") else() if(Swift_TEST_WAS_RUN) diff --git a/Modules/CPackDeb.cmake b/Modules/CPackDeb.cmake index 85d564e..337bec8 100644 --- a/Modules/CPackDeb.cmake +++ b/Modules/CPackDeb.cmake @@ -88,6 +88,16 @@ # get overwritten and it is up to the packager to set the variables in a # manner that will prevent such errors. # +# .. variable:: CPACK_DEBIAN_PACKAGE_EPOCH +# +# The Debian package epoch +# +# * Mandatory : No +# * Default : - +# +# Optional number that should be incremented when changing versioning schemas +# or fixing mistakes in the version numbers of older packages. +# # .. variable:: CPACK_DEBIAN_PACKAGE_VERSION # # The Debian package version @@ -95,12 +105,17 @@ # * Mandatory : YES # * Default : :variable:`CPACK_PACKAGE_VERSION` # +# This variable may contain only alphanumerics (A-Za-z0-9) and the characters +# . + - ~ (full stop, plus, hyphen, tilde) and should start with a digit. If +# :variable:`CPACK_DEBIAN_PACKAGE_RELEASE` is not set then hyphens are not +# allowed. +# # .. variable:: CPACK_DEBIAN_PACKAGE_RELEASE # # The Debian package release - Debian revision number. # -# * Mandatory : YES -# * Default : 1 +# * Mandatory : No +# * Default : - # # This is the numbering of the DEB package itself, i.e. the version of the # packaging and not the version of the content (see @@ -738,6 +753,32 @@ function(cpack_deb_prepare_package_vars) set(CPACK_DEBIAN_PACKAGE_VERSION ${CPACK_PACKAGE_VERSION}) endif() + if(NOT CPACK_DEBIAN_PACKAGE_VERSION MATCHES "^[0-9][A-Za-z0-9.+-~]*$") + message(FATAL_ERROR + "CPackDeb: Debian package version must confirm to \"^[0-9][A-Za-z0-9.+-~]*$\" regex!") + endif() + + if(CPACK_DEBIAN_PACKAGE_RELEASE) + if(NOT CPACK_DEBIAN_PACKAGE_RELEASE MATCHES "^[A-Za-z0-9.+~]+$") + message(FATAL_ERROR + "CPackDeb: Debian package release must confirm to \"^[A-Za-z0-9.+~]+$\" regex!") + endif() + string(APPEND CPACK_DEBIAN_PACKAGE_VERSION + "-${CPACK_DEBIAN_PACKAGE_RELEASE}") + elseif(CPACK_DEBIAN_PACKAGE_VERSION MATCHES ".*-.*") + message(FATAL_ERROR + "CPackDeb: Debian package version must not contain hyphens when CPACK_DEBIAN_PACKAGE_RELEASE is not provided!") + endif() + + if(CPACK_DEBIAN_PACKAGE_EPOCH) + if(NOT CPACK_DEBIAN_PACKAGE_EPOCH MATCHES "^[0-9]+$") + message(FATAL_ERROR + "CPackDeb: Debian package epoch must confirm to \"^[0-9]+$\" regex!") + endif() + set(CPACK_DEBIAN_PACKAGE_VERSION + "${CPACK_DEBIAN_PACKAGE_EPOCH}:${CPACK_DEBIAN_PACKAGE_VERSION}") + endif() + # Architecture: (mandatory) if(CPACK_DEB_PACKAGE_COMPONENT AND CPACK_DEBIAN_${_local_component_name}_PACKAGE_ARCHITECTURE) set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "${CPACK_DEBIAN_${_local_component_name}_PACKAGE_ARCHITECTURE}") @@ -961,11 +1002,6 @@ function(cpack_deb_prepare_package_vars) set(CPACK_DEBIAN_GENERATE_POSTRM 0) endif() - if(NOT CPACK_DEBIAN_PACKAGE_RELEASE) - set(CPACK_DEBIAN_PACKAGE_RELEASE 1) - endif() - - cpack_deb_variable_fallback("CPACK_DEBIAN_FILE_NAME" "CPACK_DEBIAN_${_local_component_name}_FILE_NAME" "CPACK_DEBIAN_FILE_NAME") @@ -974,7 +1010,7 @@ function(cpack_deb_prepare_package_vars) # Patch package file name to be in corrent debian format: # <foo>_<VersionNumber>-<DebianRevisionNumber>_<DebianArchitecture>.deb set(CPACK_OUTPUT_FILE_NAME - "${CPACK_DEBIAN_PACKAGE_NAME}_${CPACK_DEBIAN_PACKAGE_VERSION}-${CPACK_DEBIAN_PACKAGE_RELEASE}_${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}.deb") + "${CPACK_DEBIAN_PACKAGE_NAME}_${CPACK_DEBIAN_PACKAGE_VERSION}_${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}.deb") else() cmake_policy(PUSH) cmake_policy(SET CMP0010 NEW) diff --git a/Modules/CPackIFW.cmake b/Modules/CPackIFW.cmake index 0b42c83..8d8b070 100644 --- a/Modules/CPackIFW.cmake +++ b/Modules/CPackIFW.cmake @@ -323,7 +323,9 @@ # [LICENSES <display_name> <file_path> ...] # [DEFAULT <value>] # [USER_INTERFACES <file_path> <file_path> ...] -# [TRANSLATIONS <file_path> <file_path> ...]) +# [TRANSLATIONS <file_path> <file_path> ...] +# [REPLACES <comp_id> ...] +# [CHECKABLE <value>]) # # This command should be called after :command:`cpack_add_component` command. # @@ -404,6 +406,15 @@ # ``TRANSLATIONS`` # is a list of <file_path> ('.qm' files) representing translations to load. # +# ``REPLACES`` +# list of identifiers of component or component group to replace. +# +# ``CHECKABLE`` +# Possible values are: TRUE, FALSE. +# Set to FALSE if you want to hide the checkbox for an item. +# This is useful when only a few subcomponents should be selected +# instead of all. +# # # .. command:: cpack_ifw_configure_component_group # @@ -426,7 +437,9 @@ # [LICENSES <display_name> <file_path> ...] # [DEFAULT <value>] # [USER_INTERFACES <file_path> <file_path> ...] -# [TRANSLATIONS <file_path> <file_path> ...]) +# [TRANSLATIONS <file_path> <file_path> ...] +# [REPLACES <comp_id> ...] +# [CHECKABLE <value>]) # # This command should be called after :command:`cpack_add_component_group` # command. @@ -499,6 +512,15 @@ # ``TRANSLATIONS`` # is a list of <file_path> ('.qm' files) representing translations to load. # +# ``REPLACES`` +# list of identifiers of component or component group to replace. +# +# ``CHECKABLE`` +# Possible values are: TRUE, FALSE. +# Set to FALSE if you want to hide the checkbox for an item. +# This is useful when only a few subcomponents should be selected +# instead of all. +# # # .. command:: cpack_ifw_add_repository # @@ -882,8 +904,8 @@ macro(cpack_ifw_configure_component compname) string(TOUPPER ${compname} _CPACK_IFWCOMP_UNAME) set(_IFW_OPT COMMON ESSENTIAL VIRTUAL FORCED_INSTALLATION REQUIRES_ADMIN_RIGHTS) - set(_IFW_ARGS NAME VERSION RELEASE_DATE SCRIPT PRIORITY SORTING_PRIORITY UPDATE_TEXT DEFAULT) - set(_IFW_MULTI_ARGS DISPLAY_NAME DESCRIPTION DEPENDS DEPENDENCIES AUTO_DEPEND_ON LICENSES USER_INTERFACES TRANSLATIONS) + set(_IFW_ARGS NAME VERSION RELEASE_DATE SCRIPT PRIORITY SORTING_PRIORITY UPDATE_TEXT DEFAULT CHECKABLE) + set(_IFW_MULTI_ARGS DISPLAY_NAME DESCRIPTION DEPENDS DEPENDENCIES AUTO_DEPEND_ON LICENSES USER_INTERFACES TRANSLATIONS REPLACES) cmake_parse_arguments(CPACK_IFW_COMPONENT_${_CPACK_IFWCOMP_UNAME} "${_IFW_OPT}" "${_IFW_ARGS}" "${_IFW_MULTI_ARGS}" ${ARGN}) _cpack_ifw_resolve_script(CPACK_IFW_COMPONENT_${_CPACK_IFWCOMP_UNAME}_SCRIPT) @@ -923,8 +945,8 @@ macro(cpack_ifw_configure_component_group grpname) string(TOUPPER ${grpname} _CPACK_IFWGRP_UNAME) set(_IFW_OPT VIRTUAL FORCED_INSTALLATION REQUIRES_ADMIN_RIGHTS) - set(_IFW_ARGS NAME VERSION RELEASE_DATE SCRIPT PRIORITY SORTING_PRIORITY UPDATE_TEXT DEFAULT) - set(_IFW_MULTI_ARGS DISPLAY_NAME DESCRIPTION DEPENDS DEPENDENCIES AUTO_DEPEND_ON LICENSES USER_INTERFACES TRANSLATIONS) + set(_IFW_ARGS NAME VERSION RELEASE_DATE SCRIPT PRIORITY SORTING_PRIORITY UPDATE_TEXT DEFAULT CHECKABLE) + set(_IFW_MULTI_ARGS DISPLAY_NAME DESCRIPTION DEPENDS DEPENDENCIES AUTO_DEPEND_ON LICENSES USER_INTERFACES TRANSLATIONS REPLACES) cmake_parse_arguments(CPACK_IFW_COMPONENT_GROUP_${_CPACK_IFWGRP_UNAME} "${_IFW_OPT}" "${_IFW_ARGS}" "${_IFW_MULTI_ARGS}" ${ARGN}) _cpack_ifw_resolve_script(CPACK_IFW_COMPONENT_GROUP_${_CPACK_IFWGRP_UNAME}_SCRIPT) diff --git a/Modules/CPackRPM.cmake b/Modules/CPackRPM.cmake index 3913494..9f77ec3 100644 --- a/Modules/CPackRPM.cmake +++ b/Modules/CPackRPM.cmake @@ -106,6 +106,16 @@ # group rpm package is generated without component suffix in filename and # package name. # +# .. variable:: CPACK_RPM_PACKAGE_EPOCH +# +# The RPM package epoch +# +# * Mandatory : No +# * Default : - +# +# Optional number that should be incremented when changing versioning schemas +# or fixing mistakes in the version numbers of older packages. +# # .. variable:: CPACK_RPM_PACKAGE_VERSION # # The RPM package version. @@ -530,7 +540,9 @@ # list of path to be excluded. # # * Mandatory : NO -# * Default : /etc /etc/init.d /usr /usr/share /usr/share/doc /usr/bin /usr/lib /usr/lib64 /usr/include +# * Default : /etc /etc/init.d /usr /usr/bin /usr/include /usr/lib +# /usr/libx32 /usr/lib64 /usr/share /usr/share/aclocal +# /usr/share/doc # # May be used to exclude path (directories or files) from the auto-generated # list of paths discovered by CPack RPM. The defaut value contains a @@ -1083,7 +1095,9 @@ function(cpack_rpm_prepare_content_list) endif() if(NOT DEFINED CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST) - set(CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST /etc /etc/init.d /usr /usr/share /usr/share/doc /usr/bin /usr/lib /usr/lib64 /usr/libx32 /usr/include) + set(CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST /etc /etc/init.d /usr /usr/bin + /usr/include /usr/lib /usr/libx32 /usr/lib64 + /usr/share /usr/share/aclocal /usr/share/doc ) if(CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION) if(CPACK_RPM_PACKAGE_DEBUG) message("CPackRPM:Debug: Adding ${CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION} to builtin omit list.") @@ -1891,11 +1905,16 @@ function(cpack_rpm_generate_package) OUTPUT_STRIP_TRAILING_WHITESPACE) string(REPLACE "\n" ";" RPMBUILD_TAG_LIST "${RPMBUILD_TAG_LIST}") + if(CPACK_RPM_PACKAGE_EPOCH) + set(TMP_RPM_EPOCH "Epoch: ${CPACK_RPM_PACKAGE_EPOCH}") + endif() + # Check if additional fields for RPM spec header are given # There may be some COMPONENT specific variables as well # If component specific var is not provided we use the global one # for each component foreach(_RPM_SPEC_HEADER URL REQUIRES SUGGESTS PROVIDES OBSOLETES PREFIX CONFLICTS AUTOPROV AUTOREQ AUTOREQPROV REQUIRES_PRE REQUIRES_POST REQUIRES_PREUN REQUIRES_POSTUN) + if(CPACK_RPM_PACKAGE_DEBUG) message("CPackRPM:Debug: processing ${_RPM_SPEC_HEADER}") endif() @@ -2501,6 +2520,7 @@ Vendor: \@CPACK_RPM_PACKAGE_VENDOR\@ \@TMP_RPM_AUTOREQPROV\@ \@TMP_RPM_BUILDARCH\@ \@TMP_RPM_PREFIXES\@ +\@TMP_RPM_EPOCH\@ %description -n \@CPACK_RPM_PACKAGE_NAME\@ \@CPACK_RPM_PACKAGE_DESCRIPTION\@ @@ -2560,6 +2580,7 @@ Vendor: \@CPACK_RPM_PACKAGE_VENDOR\@ \@TMP_RPM_AUTOREQPROV\@ \@TMP_RPM_BUILDARCH\@ \@TMP_RPM_PREFIXES\@ +\@TMP_RPM_EPOCH\@ \@TMP_RPM_DEBUGINFO\@ diff --git a/Modules/CheckForPthreads.c b/Modules/CheckForPthreads.c index 6fc6f26..e70ceb1 100644 --- a/Modules/CheckForPthreads.c +++ b/Modules/CheckForPthreads.c @@ -1,41 +1,15 @@ #include <pthread.h> -#include <stdio.h> -#include <unistd.h> -void* runner(void*); - -int res = 0; -#ifdef __CLASSIC_C__ -int main() -{ - int ac; - char* av[]; -#else -int main(int ac, char* av[]) +void* start_routine(void* args) { -#endif - pthread_t tid[2]; - pthread_create(&tid[0], 0, runner, (void*)1); - pthread_create(&tid[1], 0, runner, (void*)2); - -#if defined(__BEOS__) && !defined(__ZETA__) /* (no usleep on BeOS 5.) */ - usleep(1); /* for strange behavior on single-processor sun */ -#endif - - pthread_join(tid[0], 0); - pthread_join(tid[1], 0); - if (ac > 1000) { - return *av[0]; - } - return res; + return args; } -void* runner(void* args) +int main(void) { - int cc; - for (cc = 0; cc < 10; cc++) { - printf("%p CC: %d\n", args, cc); - } - res++; + /* This is a compile and link test, no code to actually run things. */ + pthread_t thread; + pthread_create(&thread, 0, start_routine, 0); + pthread_join(thread, 0); return 0; } diff --git a/Modules/Compiler/Flang-FindBinUtils.cmake b/Modules/Compiler/Flang-FindBinUtils.cmake new file mode 100644 index 0000000..e721c87 --- /dev/null +++ b/Modules/Compiler/Flang-FindBinUtils.cmake @@ -0,0 +1 @@ +include(Compiler/Clang-FindBinUtils) diff --git a/Modules/Compiler/Flang-Fortran.cmake b/Modules/Compiler/Flang-Fortran.cmake new file mode 100644 index 0000000..f17dec7 --- /dev/null +++ b/Modules/Compiler/Flang-Fortran.cmake @@ -0,0 +1,12 @@ +include(Compiler/Clang) +__compiler_clang(Fortran) + +set(CMAKE_Fortran_PREPROCESS_SOURCE + "<CMAKE_Fortran_COMPILER> -cpp <DEFINES> <INCLUDES> <FLAGS> -E <SOURCE> -o <PREPROCESSED_SOURCE>") + +set(CMAKE_Fortran_FORMAT_FIXED_FLAG "-ffixed-form") +set(CMAKE_Fortran_FORMAT_FREE_FLAG "-ffree-form") + +string(APPEND CMAKE_Fortran_FLAGS_DEBUG_INIT " -fbounds-check") + +set(CMAKE_Fortran_MODDIR_FLAG "-J") diff --git a/Modules/Compiler/MSVC-CXX.cmake b/Modules/Compiler/MSVC-CXX.cmake index f478b85..789fff5 100644 --- a/Modules/Compiler/MSVC-CXX.cmake +++ b/Modules/Compiler/MSVC-CXX.cmake @@ -3,7 +3,10 @@ include(Compiler/CMakeCommonCompilerMacros) -if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.10.25017) +if ((CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.0.24215.1 AND + CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.10) OR + CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.10.25017) + # VS 2015 Update 3 and above support language standard level flags, # with the default and minimum level being C++14. set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "") @@ -21,6 +24,16 @@ if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.10.25017) endif() __compiler_check_default_language_standard(CXX 19.0 14) + + # All features that we define are available in the base mode, except + # for meta-features for C++14 and above. Override the default macro + # to avoid doing unnecessary work. + macro(cmake_record_cxx_compile_features) + list(APPEND CMAKE_CXX17_COMPILE_FEATURES cxx_std_17) + list(APPEND CMAKE_CXX14_COMPILE_FEATURES cxx_std_14) + list(APPEND CMAKE_CXX98_COMPILE_FEATURES cxx_std_11) # no flag needed for 11 + _record_compiler_features_cxx(98) + endmacro() elseif (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16.0) # MSVC has no specific options to set language standards, but set them as # empty strings anyways so the feature test infrastructure can at least check @@ -36,4 +49,18 @@ elseif (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16.0) # There is no meaningful default for this set(CMAKE_CXX_STANDARD_DEFAULT "") + + # There are no compiler modes so we only need to test features once. + # Override the default macro for this special case. Pretend that + # all language standards are available so that at least compilation + # can be attempted. + macro(cmake_record_cxx_compile_features) + list(APPEND CMAKE_CXX_COMPILE_FEATURES + cxx_std_98 + cxx_std_11 + cxx_std_14 + cxx_std_17 + ) + _record_compiler_features(CXX "" CMAKE_CXX_COMPILE_FEATURES) + endmacro() endif() diff --git a/Modules/Compiler/PGI-Fortran.cmake b/Modules/Compiler/PGI-Fortran.cmake index 4783424..a183c33 100644 --- a/Modules/Compiler/PGI-Fortran.cmake +++ b/Modules/Compiler/PGI-Fortran.cmake @@ -7,7 +7,6 @@ set(CMAKE_Fortran_PREPROCESS_SOURCE set(CMAKE_Fortran_FORMAT_FIXED_FLAG "-Mnofreeform") set(CMAKE_Fortran_FORMAT_FREE_FLAG "-Mfreeform") -string(APPEND CMAKE_Fortran_FLAGS_INIT " -Mpreprocess -Kieee") string(APPEND CMAKE_Fortran_FLAGS_DEBUG_INIT " -Mbounds") set(CMAKE_Fortran_MODDIR_FLAG "-module ") diff --git a/Modules/Compiler/PGI.cmake b/Modules/Compiler/PGI.cmake index 0cbfd8a..d5a57ee 100644 --- a/Modules/Compiler/PGI.cmake +++ b/Modules/Compiler/PGI.cmake @@ -19,16 +19,20 @@ macro(__compiler_pgi lang) string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " -g -O0") string(APPEND CMAKE_${lang}_FLAGS_MINSIZEREL_INIT " -O2 -s") string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " -fast -O3") - # -Mipa was dropped with PGI 16.3 from Windows versions - if(NOT CMAKE_HOST_WIN32 OR CMAKE_${lang}_COMPILER_VERSION VERSION_LESS 16.3) - string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " -Mipa=fast") - endif() string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " -O2 -gopt") if(CMAKE_HOST_WIN32) string(APPEND CMAKE_${lang}_FLAGS_INIT " -Bdynamic") endif() + set(_CMAKE_${lang}_IPO_SUPPORTED_BY_CMAKE YES) + if(NOT CMAKE_SYSTEM_PROCESSOR STREQUAL ppc64le AND (NOT CMAKE_HOST_WIN32 OR CMAKE_${lang}_COMPILER_VERSION VERSION_LESS 16.3)) + set(_CMAKE_${lang}_IPO_MAY_BE_SUPPORTED_BY_COMPILER YES) + set(CMAKE_${lang}_COMPILE_OPTIONS_IPO "-Mipa=fast,inline") + else() + set(_CMAKE_${lang}_IPO_MAY_BE_SUPPORTED_BY_COMPILER NO) + endif() + # Preprocessing and assembly rules. set(CMAKE_${lang}_CREATE_PREPROCESSED_SOURCE "<CMAKE_${lang}_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -E <SOURCE> > <PREPROCESSED_SOURCE>") set(CMAKE_${lang}_CREATE_ASSEMBLY_SOURCE "<CMAKE_${lang}_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -S <SOURCE> -o <ASSEMBLY_SOURCE>") diff --git a/Modules/CompilerId/Xcode-3.pbxproj.in b/Modules/CompilerId/Xcode-3.pbxproj.in index 84f48ae..1cbaa57 100644 --- a/Modules/CompilerId/Xcode-3.pbxproj.in +++ b/Modules/CompilerId/Xcode-3.pbxproj.in @@ -72,6 +72,7 @@ 1DEB928608733DD80010E9CD = { isa = XCBuildConfiguration; buildSettings = { + @id_development_team@ PRODUCT_NAME = CompilerId@id_lang@; }; name = Debug; diff --git a/Modules/ExternalProject.cmake b/Modules/ExternalProject.cmake index d92eb5f..912c5ac 100644 --- a/Modules/ExternalProject.cmake +++ b/Modules/ExternalProject.cmake @@ -870,6 +870,14 @@ foreach(line IN LISTS lines) set(_ep_keyword_sep) elseif("${line}" MATCHES "^ +``([A-Z0-9_]+) [^`]*``$") set(_ep_key "${CMAKE_MATCH_1}") + # COMMAND should never be included as a keyword, + # for ExternalProject_Add(), as it is treated as a + # special case by argument parsing as an extension + # of a previous ..._COMMAND + if("x${_ep_key}x" STREQUAL "xCOMMANDx" AND + "x${_ep_func}x" STREQUAL "xExternalProject_Addx") + continue() + endif() #message(" keyword [${_ep_key}]") string(APPEND _ep_keywords_${_ep_func} "${_ep_keyword_sep}${_ep_key}") diff --git a/Modules/FindBoost.cmake b/Modules/FindBoost.cmake index b28f2b8..6d1514d 100644 --- a/Modules/FindBoost.cmake +++ b/Modules/FindBoost.cmake @@ -76,7 +76,7 @@ # Boost::system will be automatically detected and satisfied, even # if system is not specified when using find_package and if # Boost::system is not added to target_link_libraries. If using -# Boost::thread, then Thread::Thread will also be added automatically. +# Boost::thread, then Threads::Threads will also be added automatically. # # It is important to note that the imported targets behave differently # than variables created by this module: multiple calls to @@ -107,6 +107,10 @@ # Users or projects may tell this module which variant to find by # setting variables:: # +# Boost_USE_DEBUG_LIBS - Set to ON or OFF to specify whether to search +# and use the debug libraries. Default is ON. +# Boost_USE_RELEASE_LIBS - Set to ON or OFF to specify whether to search +# and use the release libraries. Default is ON. # Boost_USE_MULTITHREADED - Set to OFF to use the non-multithreaded # libraries ('mt' tag). Default is ON. # Boost_USE_STATIC_LIBS - Set to ON to force the use of the static @@ -183,9 +187,11 @@ # target_link_libraries(foo Boost::date_time Boost::filesystem # Boost::iostreams) # -# Example to find Boost headers and some *static* libraries:: +# Example to find Boost headers and some *static* (release only) libraries:: # -# set(Boost_USE_STATIC_LIBS ON) # only find static libs +# set(Boost_USE_STATIC_LIBS ON) # only find static libs +# set(Boost_USE_DEBUG_LIBS OFF) # ignore debug libs and +# set(Boost_USE_RELEASE_LIBS ON) # only find release libs # set(Boost_USE_MULTITHREADED ON) # set(Boost_USE_STATIC_RUNTIME OFF) # find_package(Boost 1.36.0 COMPONENTS date_time filesystem system ...) @@ -298,13 +304,17 @@ macro(_Boost_ADJUST_LIB_VARS basename) endif() # If the debug & release library ends up being the same, omit the keywords - if(${Boost_${basename}_LIBRARY_RELEASE} STREQUAL ${Boost_${basename}_LIBRARY_DEBUG}) + if("${Boost_${basename}_LIBRARY_RELEASE}" STREQUAL "${Boost_${basename}_LIBRARY_DEBUG}") set(Boost_${basename}_LIBRARY ${Boost_${basename}_LIBRARY_RELEASE} ) set(Boost_${basename}_LIBRARIES ${Boost_${basename}_LIBRARY_RELEASE} ) endif() if(Boost_${basename}_LIBRARY AND Boost_${basename}_HEADER) set(Boost_${basename}_FOUND ON) + if("x${basename}" STREQUAL "xTHREAD" AND NOT TARGET Threads::Threads) + string(APPEND Boost_ERROR_REASON_THREAD " (missing dependency: Threads)") + set(Boost_THREAD_FOUND OFF) + endif() endif() endif() @@ -996,8 +1006,14 @@ if(NOT Boost_LIBRARY_DIR_DEBUG AND Boost_LIBRARY_DIR) set(Boost_LIBRARY_DIR_DEBUG "${Boost_LIBRARY_DIR}") endif() +if(NOT DEFINED Boost_USE_DEBUG_LIBS) + set(Boost_USE_DEBUG_LIBS TRUE) +endif() +if(NOT DEFINED Boost_USE_RELEASE_LIBS) + set(Boost_USE_RELEASE_LIBS TRUE) +endif() if(NOT DEFINED Boost_USE_MULTITHREADED) - set(Boost_USE_MULTITHREADED TRUE) + set(Boost_USE_MULTITHREADED TRUE) endif() if(NOT DEFINED Boost_USE_DEBUG_RUNTIME) set(Boost_USE_DEBUG_RUNTIME TRUE) @@ -1023,7 +1039,7 @@ else() # _Boost_COMPONENT_HEADERS. See the instructions at the top of # _Boost_COMPONENT_DEPENDENCIES. set(_Boost_KNOWN_VERSIONS ${Boost_ADDITIONAL_VERSIONS} - "1.65.0" "1.65" + "1.65.1" "1.65.0" "1.65" "1.64.0" "1.64" "1.63.0" "1.63" "1.62.0" "1.62" "1.61.0" "1.61" "1.60.0" "1.60" "1.59.0" "1.59" "1.58.0" "1.58" "1.57.0" "1.57" "1.56.0" "1.56" "1.55.0" "1.55" "1.54.0" "1.54" "1.53.0" "1.53" "1.52.0" "1.52" "1.51.0" "1.51" @@ -1528,8 +1544,13 @@ _Boost_MISSING_DEPENDENCIES(Boost_FIND_COMPONENTS _Boost_EXTRA_FIND_COMPONENTS) # If thread is required, get the thread libs as a dependency if("thread" IN_LIST Boost_FIND_COMPONENTS) - include(CMakeFindDependencyMacro) - find_dependency(Threads) + if(Boost_FIND_QUIETLY) + set(_Boost_find_quiet QUIET) + else() + set(_Boost_find_quiet "") + endif() + find_package(Threads ${_Boost_find_quiet}) + unset(_Boost_find_quiet) endif() # If the user changed any of our control inputs flush previous results. @@ -1631,12 +1652,14 @@ foreach(COMPONENT ${Boost_FIND_COMPONENTS}) # Avoid passing backslashes to _Boost_FIND_LIBRARY due to macro re-parsing. string(REPLACE "\\" "/" _boost_LIBRARY_SEARCH_DIRS_tmp "${_boost_LIBRARY_SEARCH_DIRS_RELEASE}") - _Boost_FIND_LIBRARY(Boost_${UPPERCOMPONENT}_LIBRARY_RELEASE RELEASE - NAMES ${_boost_RELEASE_NAMES} - HINTS ${_boost_LIBRARY_SEARCH_DIRS_tmp} - NAMES_PER_DIR - DOC "${_boost_docstring_release}" - ) + if(Boost_USE_RELEASE_LIBS) + _Boost_FIND_LIBRARY(Boost_${UPPERCOMPONENT}_LIBRARY_RELEASE RELEASE + NAMES ${_boost_RELEASE_NAMES} + HINTS ${_boost_LIBRARY_SEARCH_DIRS_tmp} + NAMES_PER_DIR + DOC "${_boost_docstring_release}" + ) + endif() # # Find DEBUG libraries @@ -1680,12 +1703,14 @@ foreach(COMPONENT ${Boost_FIND_COMPONENTS}) # Avoid passing backslashes to _Boost_FIND_LIBRARY due to macro re-parsing. string(REPLACE "\\" "/" _boost_LIBRARY_SEARCH_DIRS_tmp "${_boost_LIBRARY_SEARCH_DIRS_DEBUG}") - _Boost_FIND_LIBRARY(Boost_${UPPERCOMPONENT}_LIBRARY_DEBUG DEBUG - NAMES ${_boost_DEBUG_NAMES} - HINTS ${_boost_LIBRARY_SEARCH_DIRS_tmp} - NAMES_PER_DIR - DOC "${_boost_docstring_debug}" - ) + if(Boost_USE_DEBUG_LIBS) + _Boost_FIND_LIBRARY(Boost_${UPPERCOMPONENT}_LIBRARY_DEBUG DEBUG + NAMES ${_boost_DEBUG_NAMES} + HINTS ${_boost_LIBRARY_SEARCH_DIRS_tmp} + NAMES_PER_DIR + DOC "${_boost_docstring_debug}" + ) + endif () if(Boost_REALPATH) _Boost_SWAP_WITH_REALPATH(Boost_${UPPERCOMPONENT}_LIBRARY_RELEASE "${_boost_docstring_release}") @@ -1755,8 +1780,9 @@ if(Boost_FOUND) string(APPEND Boost_ERROR_REASON " Boost libraries:\n") foreach(COMPONENT ${_Boost_MISSING_COMPONENTS}) + string(TOUPPER ${COMPONENT} UPPERCOMPONENT) string(APPEND Boost_ERROR_REASON - " ${Boost_NAMESPACE}_${COMPONENT}\n") + " ${Boost_NAMESPACE}_${COMPONENT}${Boost_ERROR_REASON_${UPPERCOMPONENT}}\n") endforeach() list(LENGTH Boost_FIND_COMPONENTS Boost_NUM_COMPONENTS_WANTED) diff --git a/Modules/FindEXPAT.cmake b/Modules/FindEXPAT.cmake index 09963fc..39086e4 100644 --- a/Modules/FindEXPAT.cmake +++ b/Modules/FindEXPAT.cmake @@ -5,15 +5,28 @@ # FindEXPAT # --------- # -# Find expat +# Find the native Expat headers and library. # -# Find the native EXPAT headers and libraries. +# Imported Targets +# ^^^^^^^^^^^^^^^^ # -# :: +# This module defines the following :prop_tgt:`IMPORTED` targets: +# +# ``EXPAT::EXPAT`` +# The Expat ``expat`` library, if found. +# +# Result Variables +# ^^^^^^^^^^^^^^^^ +# +# This module will set the following variables in your project: +# +# ``EXPAT_INCLUDE_DIRS`` +# where to find expat.h, etc. +# ``EXPAT_LIBRARIES`` +# the libraries to link against to use Expat. +# ``EXPAT_FOUND`` +# true if the Expat headers and libraries were found. # -# EXPAT_INCLUDE_DIRS - where to find expat.h, etc. -# EXPAT_LIBRARIES - List of libraries when using expat. -# EXPAT_FOUND - True if expat found. find_package(PkgConfig QUIET) @@ -49,10 +62,18 @@ FIND_PACKAGE_HANDLE_STANDARD_ARGS(EXPAT REQUIRED_VARS EXPAT_LIBRARY EXPAT_INCLUDE_DIR VERSION_VAR EXPAT_VERSION_STRING) -# Copy the results to the output variables. +# Copy the results to the output variables and target. if(EXPAT_FOUND) set(EXPAT_LIBRARIES ${EXPAT_LIBRARY}) set(EXPAT_INCLUDE_DIRS ${EXPAT_INCLUDE_DIR}) + + if(NOT TARGET EXPAT::EXPAT) + add_library(EXPAT::EXPAT UNKNOWN IMPORTED) + set_target_properties(EXPAT::EXPAT PROPERTIES + IMPORTED_LINK_INTERFACE_LANGUAGES "C" + IMPORTED_LOCATION "${EXPAT_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${EXPAT_INCLUDE_DIRS}") + endif() endif() mark_as_advanced(EXPAT_INCLUDE_DIR EXPAT_LIBRARY) diff --git a/Modules/FindFreetype.cmake b/Modules/FindFreetype.cmake index 9ea77df..0e6d336 100644 --- a/Modules/FindFreetype.cmake +++ b/Modules/FindFreetype.cmake @@ -5,24 +5,41 @@ # FindFreetype # ------------ # -# Locate FreeType library +# Find the FreeType font renderer includes and library. # -# This module defines +# Imported Targets +# ^^^^^^^^^^^^^^^^ # -# :: +# This module defines the following :prop_tgt:`IMPORTED` target: # -# FREETYPE_LIBRARIES, the library to link against -# FREETYPE_FOUND, if false, do not try to link to FREETYPE -# FREETYPE_INCLUDE_DIRS, where to find headers. -# FREETYPE_VERSION_STRING, the version of freetype found (since CMake 2.8.8) -# This is the concatenation of the paths: -# FREETYPE_INCLUDE_DIR_ft2build -# FREETYPE_INCLUDE_DIR_freetype2 +# ``Freetype::Freetype`` +# The Freetype ``freetype`` library, if found # +# Result Variables +# ^^^^^^^^^^^^^^^^ # +# This module will set the following variables in your project: # -# $FREETYPE_DIR is an environment variable that would correspond to the -# ./configure --prefix=$FREETYPE_DIR used in building FREETYPE. +# ``FREETYPE_FOUND`` +# true if the Freetype headers and libraries were found +# ``FREETYPE_INCLUDE_DIRS`` +# directories containing the Freetype headers. This is the +# concatenation of the variables: +# +# ``FREETYPE_INCLUDE_DIR_ft2build`` +# directory holding the main Freetype API configuration header +# ``FREETYPE_INCLUDE_DIR_freetype2`` +# directory holding Freetype public headers +# ``FREETYPE_LIBRARIES`` +# the library to link against +# ``FREETYPE_VERSION_STRING`` +# the version of freetype found (since CMake 2.8.8) +# +# Hints +# ^^^^^ +# +# The user may set the environment variable ``FREETYPE_DIR`` to the root +# directory of a Freetype installation. # Created by Eric Wing. # Modifications by Alexander Neundorf. @@ -150,3 +167,33 @@ mark_as_advanced( FREETYPE_INCLUDE_DIR_freetype2 FREETYPE_INCLUDE_DIR_ft2build ) + +if(Freetype_FOUND) + if(NOT TARGET Freetype::Freetype) + add_library(Freetype::Freetype UNKNOWN IMPORTED) + set_target_properties(Freetype::Freetype PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES "${FREETYPE_INCLUDE_DIRS}") + + if(FREETYPE_LIBRARY_RELEASE) + set_property(TARGET Freetype::Freetype APPEND PROPERTY + IMPORTED_CONFIGURATIONS RELEASE) + set_target_properties(Freetype::Freetype PROPERTIES + IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "C" + IMPORTED_LOCATION_RELEASE "${FREETYPE_LIBRARY_RELEASE}") + endif() + + if(FREETYPE_LIBRARY_DEBUG) + set_property(TARGET Freetype::Freetype APPEND PROPERTY + IMPORTED_CONFIGURATIONS DEBUG) + set_target_properties(Freetype::Freetype PROPERTIES + IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "C" + IMPORTED_LOCATION_DEBUG "${FREETYPE_LIBRARY_DEBUG}") + endif() + + if(NOT FREETYPE_LIBRARY_RELEASE AND NOT FREETYPE_LIBRARY_DEBUG) + set_target_properties(Freetype::Freetype PROPERTIES + IMPORTED_LINK_INTERFACE_LANGUAGES "C" + IMPORTED_LOCATION "${FREETYPE_LIBRARY}") + endif() + endif() +endif() diff --git a/Modules/FindGTest.cmake b/Modules/FindGTest.cmake index cb71ef1..b0579d9 100644 --- a/Modules/FindGTest.cmake +++ b/Modules/FindGTest.cmake @@ -75,7 +75,7 @@ include(${CMAKE_CURRENT_LIST_DIR}/GoogleTest.cmake) -function(_gtest_append_debugs _endvar _library) +function(__gtest_append_debugs _endvar _library) if(${_library} AND ${_library}_DEBUG) set(_output optimized ${${_library}} debug ${${_library}_DEBUG}) else() @@ -84,7 +84,7 @@ function(_gtest_append_debugs _endvar _library) set(${_endvar} ${_output} PARENT_SCOPE) endfunction() -function(_gtest_find_library _name) +function(__gtest_find_library _name) find_library(${_name} NAMES ${ARGN} HINTS @@ -95,6 +95,56 @@ function(_gtest_find_library _name) mark_as_advanced(${_name}) endfunction() +macro(__gtest_determine_windows_library_type _var) + if(EXISTS "${${_var}}") + file(TO_NATIVE_PATH "${${_var}}" _lib_path) + get_filename_component(_name "${${_var}}" NAME_WE) + file(STRINGS "${${_var}}" _match REGEX "${_name}\\.dll" LIMIT_COUNT 1) + if(NOT _match STREQUAL "") + set(${_var}_TYPE SHARED PARENT_SCOPE) + else() + set(${_var}_TYPE UNKNOWN PARENT_SCOPE) + endif() + return() + endif() +endmacro() + +function(__gtest_determine_library_type _var) + if(WIN32) + # For now, at least, only Windows really needs to know the library type + __gtest_determine_windows_library_type(${_var}) + __gtest_determine_windows_library_type(${_var}_RELEASE) + __gtest_determine_windows_library_type(${_var}_DEBUG) + endif() + # If we get here, no determination was made from the above checks + set(${_var}_TYPE UNKNOWN PARENT_SCOPE) +endfunction() + +function(__gtest_import_library _target _var _config) + if(_config) + set(_config_suffix "_${_config}") + else() + set(_config_suffix "") + endif() + + set(_lib "${${_var}${_config_suffix}}") + if(EXISTS "${_lib}") + if(_config) + set_property(TARGET ${_target} APPEND PROPERTY + IMPORTED_CONFIGURATIONS ${_config}) + endif() + set_target_properties(${_target} PROPERTIES + IMPORTED_LINK_INTERFACE_LANGUAGES${_config_suffix} "CXX") + if(WIN32 AND ${_var}_TYPE STREQUAL SHARED) + set_target_properties(${_target} PROPERTIES + IMPORTED_IMPLIB${_config_suffix} "${_lib}") + else() + set_target_properties(${_target} PROPERTIES + IMPORTED_LOCATION${_config_suffix} "${_lib}") + endif() + endif() +endfunction() + # if(NOT DEFINED GTEST_MSVC_SEARCH) @@ -131,15 +181,15 @@ mark_as_advanced(GTEST_INCLUDE_DIR) if(MSVC AND GTEST_MSVC_SEARCH STREQUAL "MD") # The provided /MD project files for Google Test add -md suffixes to the # library names. - _gtest_find_library(GTEST_LIBRARY gtest-md gtest) - _gtest_find_library(GTEST_LIBRARY_DEBUG gtest-mdd gtestd) - _gtest_find_library(GTEST_MAIN_LIBRARY gtest_main-md gtest_main) - _gtest_find_library(GTEST_MAIN_LIBRARY_DEBUG gtest_main-mdd gtest_maind) + __gtest_find_library(GTEST_LIBRARY gtest-md gtest) + __gtest_find_library(GTEST_LIBRARY_DEBUG gtest-mdd gtestd) + __gtest_find_library(GTEST_MAIN_LIBRARY gtest_main-md gtest_main) + __gtest_find_library(GTEST_MAIN_LIBRARY_DEBUG gtest_main-mdd gtest_maind) else() - _gtest_find_library(GTEST_LIBRARY gtest) - _gtest_find_library(GTEST_LIBRARY_DEBUG gtestd) - _gtest_find_library(GTEST_MAIN_LIBRARY gtest_main) - _gtest_find_library(GTEST_MAIN_LIBRARY_DEBUG gtest_maind) + __gtest_find_library(GTEST_LIBRARY gtest) + __gtest_find_library(GTEST_LIBRARY_DEBUG gtestd) + __gtest_find_library(GTEST_MAIN_LIBRARY gtest_main) + __gtest_find_library(GTEST_MAIN_LIBRARY_DEBUG gtest_maind) endif() include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) @@ -147,63 +197,38 @@ FIND_PACKAGE_HANDLE_STANDARD_ARGS(GTest DEFAULT_MSG GTEST_LIBRARY GTEST_INCLUDE_ if(GTEST_FOUND) set(GTEST_INCLUDE_DIRS ${GTEST_INCLUDE_DIR}) - _gtest_append_debugs(GTEST_LIBRARIES GTEST_LIBRARY) - _gtest_append_debugs(GTEST_MAIN_LIBRARIES GTEST_MAIN_LIBRARY) + __gtest_append_debugs(GTEST_LIBRARIES GTEST_LIBRARY) + __gtest_append_debugs(GTEST_MAIN_LIBRARIES GTEST_MAIN_LIBRARY) set(GTEST_BOTH_LIBRARIES ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES}) - include(CMakeFindDependencyMacro) - find_dependency(Threads) + find_package(Threads QUIET) if(NOT TARGET GTest::GTest) - add_library(GTest::GTest UNKNOWN IMPORTED) - set_target_properties(GTest::GTest PROPERTIES - INTERFACE_LINK_LIBRARIES "Threads::Threads") - if(GTEST_INCLUDE_DIRS) - set_target_properties(GTest::GTest PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES "${GTEST_INCLUDE_DIRS}") - endif() - if(EXISTS "${GTEST_LIBRARY}") + __gtest_determine_library_type(GTEST_LIBRARY) + add_library(GTest::GTest ${GTEST_LIBRARY_TYPE} IMPORTED) + if(TARGET Threads::Threads) set_target_properties(GTest::GTest PROPERTIES - IMPORTED_LINK_INTERFACE_LANGUAGES "CXX" - IMPORTED_LOCATION "${GTEST_LIBRARY}") + INTERFACE_LINK_LIBRARIES Threads::Threads) endif() - if(EXISTS "${GTEST_LIBRARY_RELEASE}") - set_property(TARGET GTest::GTest APPEND PROPERTY - IMPORTED_CONFIGURATIONS RELEASE) + if(GTEST_LIBRARY_TYPE STREQUAL "SHARED") set_target_properties(GTest::GTest PROPERTIES - IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "CXX" - IMPORTED_LOCATION_RELEASE "${GTEST_LIBRARY_RELEASE}") + INTERFACE_COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1") endif() - if(EXISTS "${GTEST_LIBRARY_DEBUG}") - set_property(TARGET GTest::GTest APPEND PROPERTY - IMPORTED_CONFIGURATIONS DEBUG) + if(GTEST_INCLUDE_DIRS) set_target_properties(GTest::GTest PROPERTIES - IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX" - IMPORTED_LOCATION_DEBUG "${GTEST_LIBRARY_DEBUG}") + INTERFACE_INCLUDE_DIRECTORIES "${GTEST_INCLUDE_DIRS}") endif() - endif() - if(NOT TARGET GTest::Main) - add_library(GTest::Main UNKNOWN IMPORTED) - set_target_properties(GTest::Main PROPERTIES - INTERFACE_LINK_LIBRARIES "GTest::GTest") - if(EXISTS "${GTEST_MAIN_LIBRARY}") - set_target_properties(GTest::Main PROPERTIES - IMPORTED_LINK_INTERFACE_LANGUAGES "CXX" - IMPORTED_LOCATION "${GTEST_MAIN_LIBRARY}") - endif() - if(EXISTS "${GTEST_MAIN_LIBRARY_RELEASE}") - set_property(TARGET GTest::Main APPEND PROPERTY - IMPORTED_CONFIGURATIONS RELEASE) - set_target_properties(GTest::Main PROPERTIES - IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "CXX" - IMPORTED_LOCATION_RELEASE "${GTEST_MAIN_LIBRARY_RELEASE}") - endif() - if(EXISTS "${GTEST_MAIN_LIBRARY_DEBUG}") - set_property(TARGET GTest::Main APPEND PROPERTY - IMPORTED_CONFIGURATIONS DEBUG) - set_target_properties(GTest::Main PROPERTIES - IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX" - IMPORTED_LOCATION_DEBUG "${GTEST_MAIN_LIBRARY_DEBUG}") - endif() + __gtest_import_library(GTest::GTest GTEST_LIBRARY "") + __gtest_import_library(GTest::GTest GTEST_LIBRARY "RELEASE") + __gtest_import_library(GTest::GTest GTEST_LIBRARY "DEBUG") + endif() + if(NOT TARGET GTest::Main) + __gtest_determine_library_type(GTEST_MAIN_LIBRARY) + add_library(GTest::Main ${GTEST_MAIN_LIBRARY_TYPE} IMPORTED) + set_target_properties(GTest::Main PROPERTIES + INTERFACE_LINK_LIBRARIES "GTest::GTest") + __gtest_import_library(GTest::Main GTEST_MAIN_LIBRARY "") + __gtest_import_library(GTest::Main GTEST_MAIN_LIBRARY "RELEASE") + __gtest_import_library(GTest::Main GTEST_MAIN_LIBRARY "DEBUG") endif() endif() diff --git a/Modules/FindMPI.cmake b/Modules/FindMPI.cmake index 37f3255..578fcd2 100644 --- a/Modules/FindMPI.cmake +++ b/Modules/FindMPI.cmake @@ -5,27 +5,45 @@ # FindMPI # ------- # -# Find a Message Passing Interface (MPI) implementation +# Find a Message Passing Interface (MPI) implementation. # # The Message Passing Interface (MPI) is a library used to write # high-performance distributed-memory parallel applications, and is # typically deployed on a cluster. MPI is a standard interface (defined # by the MPI forum) for which many implementations are available. # -# Variables -# ^^^^^^^^^ +# Variables for using MPI +# ^^^^^^^^^^^^^^^^^^^^^^^ +# +# The module exposes the components ``C``, ``CXX``, ``MPICXX`` and ``Fortran``. +# Each of these controls the various MPI languages to search for. +# The difference between ``CXX`` and ``MPICXX`` is that ``CXX`` refers to the +# MPI C API being usable from C++, whereas ``MPICXX`` refers to the MPI-2 C++ API +# that was removed again in MPI-3. +# +# Depending on the enabled components the following variables will be set: +# +# ``MPI_FOUND`` +# Variable indicating that MPI settings for all requested languages have been found. +# If no components are specified, this is true if MPI settings for all enabled languages +# were detected. Note that the ``MPICXX`` component does not affect this variable. +# ``MPI_VERSION`` +# Minimal version of MPI detected among the requested languages, or all enabled languages +# if no components were specified. # # This module will set the following variables per language in your # project, where ``<lang>`` is one of C, CXX, or Fortran: # # ``MPI_<lang>_FOUND`` -# Variable indicating the MPI settings for ``<lang>`` were found. +# Variable indicating the MPI settings for ``<lang>`` were found and that +# simple MPI test programs compile with the provided settings. # ``MPI_<lang>_COMPILER`` -# MPI Compiler wrapper for ``<lang>``. -# ``MPI_<lang>_COMPILE_FLAGS`` -# Compilation flags for MPI programs, separated by spaces. -# This is *not* a :ref:`;-list <CMake Language Lists>`. -# ``MPI_<lang>_INCLUDE_PATH`` +# MPI compiler for ``<lang>`` if such a program exists. +# ``MPI_<lang>_COMPILE_OPTIONS`` +# Compilation options for MPI programs in ``<lang>``, given as a :ref:`;-list <CMake Language Lists>`. +# ``MPI_<lang>_COMPILE_DEFINITIONS`` +# Compilation definitions for MPI programs in ``<lang>``, given as a :ref:`;-list <CMake Language Lists>`. +# ``MPI_<lang>_INCLUDE_DIRS`` # Include path(s) for MPI header. # ``MPI_<lang>_LINK_FLAGS`` # Linker flags for MPI programs. @@ -37,53 +55,172 @@ # ``MPI::MPI_<lang>`` # Target for using MPI from ``<lang>``. # -# Additionally, FindMPI sets the following variables for running MPI -# programs from the command line: +# The following variables indicating which bindings are present will be defined: # -# ``MPIEXEC`` -# Executable for running MPI programs, if provided. +# ``MPI_MPICXX_FOUND`` +# Variable indicating whether the MPI-2 C++ bindings are present (introduced in MPI-2, removed with MPI-3). +# ``MPI_Fortran_HAVE_F77_HEADER`` +# True if the Fortran 77 header ``mpif.h`` is available. +# ``MPI_Fortran_HAVE_F90_MODULE`` +# True if the Fortran 90 module ``mpi`` can be used for accessing MPI (MPI-2 and higher only). +# ``MPI_Fortran_HAVE_F08_MODULE`` +# True if the Fortran 2008 ``mpi_f08`` is available to MPI programs (MPI-3 and higher only). +# +# If possible, the MPI version will be determined by this module. The facilities to detect the MPI version +# were introduced with MPI-1.2, and therefore cannot be found for older MPI versions. +# +# ``MPI_<lang>_VERSION_MAJOR`` +# Major version of MPI implemented for ``<lang>`` by the MPI distribution. +# ``MPI_<lang>_VERSION_MINOR`` +# Minor version of MPI implemented for ``<lang>`` by the MPI distribution. +# ``MPI_<lang>_VERSION`` +# MPI version implemented for ``<lang>`` by the MPI distribution. +# +# Note that there's no variable for the C bindings being accessible through ``mpi.h``, since the MPI standards +# always have required this binding to work in both C and C++ code. +# +# For running MPI programs, the module sets the following variables +# +# ``MPIEXEC_EXECUTABLE`` +# Executable for running MPI programs, if such exists. # ``MPIEXEC_NUMPROC_FLAG`` -# Flag to pass to ``MPIEXEC`` before giving it the number of processors to run on. +# Flag to pass to ``mpiexec`` before giving it the number of processors to run on. # ``MPIEXEC_MAX_NUMPROCS`` # Number of MPI processors to utilize. Defaults to the number # of processors detected on the host system. # ``MPIEXEC_PREFLAGS`` -# Flags to pass to ``MPIEXEC`` directly before the executable to run. +# Flags to pass to ``mpiexec`` directly before the executable to run. # ``MPIEXEC_POSTFLAGS`` -# Flags to pass to ``MPIEXEC`` after other flags. +# Flags to pass to ``mpiexec`` after other flags. +# +# Variables for locating MPI +# ^^^^^^^^^^^^^^^^^^^^^^^^^^ +# +# This module performs a three step search for an MPI implementation: +# +# 1. Check if the compiler has MPI support built-in. This is the case if the user passed a +# compiler wrapper as ``CMAKE_<LANG>_COMPILER`` or if they're on a Cray system. +# 2. Attempt to find an MPI compiler wrapper and determine the compiler information from it. +# 3. Try to find an MPI implementation that does not ship such a wrapper by guessing settings. +# Currently, only Microsoft MPI and MPICH2 on Windows are supported. +# +# For controlling the second step, the following variables may be set: +# +# ``MPI_<lang>_COMPILER`` +# Search for the specified compiler wrapper and use it. +# ``MPI_<lang>_COMPILER_FLAGS`` +# Flags to pass to the MPI compiler wrapper during interrogation. Some compiler wrappers +# support linking debug or tracing libraries if a specific flag is passed and this variable +# may be used to obtain them. +# ``MPI_COMPILER_FLAGS`` +# Used to initialize ``MPI_<lang>_COMPILER_FLAGS`` if no language specific flag has been given. +# Empty by default. +# ``MPI_EXECUTABLE_SUFFIX`` +# A suffix which is appended to all names that are being looked for. For instance you may set this +# to ``.mpich`` or ``.openmpi`` to prefer the one or the other on Debian and its derivatives. # -# Usage -# ^^^^^ +# In order to control the guessing step, the following variable may be set: # -# To use this module, call ``find_package(MPI)``. If you are happy with the -# auto-detected configuration for your language, then you're done. If -# not, you have two options: +# ``MPI_GUESS_LIBRARY_NAME`` +# Valid values are ``MSMPI`` and ``MPICH2``. If set, only the given library will be searched for. +# By default, ``MSMPI`` will be preferred over ``MPICH2`` if both are available. +# This also sets ``MPI_SKIP_COMPILER_WRAPPER`` to ``true``, which may be overridden. # -# 1. Set ``MPI_<lang>_COMPILER`` to the MPI wrapper (e.g. ``mpicc``) of your -# choice and reconfigure. FindMPI will attempt to determine all the -# necessary variables using *that* compiler's compile and link flags. -# 2. If this fails, or if your MPI implementation does not come with -# a compiler wrapper, then set both ``MPI_<lang>_LIBRARIES`` and -# ``MPI_<lang>_INCLUDE_PATH``. You may also set any other variables -# listed above, but these two are required. This will circumvent -# autodetection entirely. +# Each of the search steps may be skipped with the following control variables: # -# When configuration is successful, ``MPI_<lang>_COMPILER`` will be set to -# the compiler wrapper for ``<lang>``, if it was found. ``MPI_<lang>_FOUND`` -# and other variables above will be set if any MPI implementation was -# found for ``<lang>``, regardless of whether a compiler was found. +# ``MPI_ASSUME_NO_BUILTIN_MPI`` +# If true, the module assumes that the compiler itself does not provide an MPI implementation and +# skips to step 2. +# ``MPI_SKIP_COMPILER_WRAPPER`` +# If true, no compiler wrapper will be searched for. +# ``MPI_SKIP_GUESSING`` +# If true, the guessing step will be skipped. # -# When using ``MPIEXEC`` to execute MPI applications, you should typically -# use all of the ``MPIEXEC`` flags as follows: +# Additionally, the following control variable is available to change search behavior: +# +# ``MPI_CXX_SKIP_MPICXX`` +# Add some definitions that will disable the MPI-2 C++ bindings. +# Currently supported are MPICH, Open MPI, Platform MPI and derivatives thereof, +# for example MVAPICH or Intel MPI. +# +# If the find procedure fails for a variable ``MPI_<lang>_WORKS``, then the settings detected by or passed to +# the module did not work and even a simple MPI test program failed to compile. +# +# If all of these parameters were not sufficient to find the right MPI implementation, a user may +# disable the entire autodetection process by specifying both a list of libraries in ``MPI_<lang>_LIBRARIES`` +# and a list of include directories in ``MPI_<lang>_ADDITIONAL_INCLUDE_DIRS``. +# Any other variable may be set in addition to these two. The module will then validate the MPI settings and store the +# settings in the cache. +# +# Cache variables for MPI +# ^^^^^^^^^^^^^^^^^^^^^^^ +# +# The variable ``MPI_<lang>_INCLUDE_DIRS`` will be assembled from the following variables. +# For C and CXX: +# +# ``MPI_<lang>_HEADER_DIR`` +# Location of the ``mpi.h`` header on disk. +# +# For Fortran: +# +# ``MPI_Fortran_F77_HEADER_DIR`` +# Location of the Fortran 77 header ``mpif.h``, if it exists. +# ``MPI_Fortran_MODULE_DIR`` +# Location of the ``mpi`` or ``mpi_f08`` modules, if available. +# +# For all languages the following variables are additionally considered: +# +# ``MPI_<lang>_ADDITIONAL_INCLUDE_DIRS`` +# A :ref:`;-list <CMake Language Lists>` of paths needed in addition to the normal include directories. +# ``MPI_<include_name>_INCLUDE_DIR`` +# Path variables for include folders referred to by ``<include_name>``. +# ``MPI_<lang>_ADDITIONAL_INCLUDE_VARS`` +# A :ref:`;-list <CMake Language Lists>` of ``<include_name>`` that will be added to the include locations of ``<lang>``. +# +# The variable ``MPI_<lang>_LIBRARIES`` will be assembled from the following variables: +# +# ``MPI_<lib_name>_LIBRARY`` +# The location of a library called ``<lib_name>`` for use with MPI. +# ``MPI_<lang>_LIB_NAMES`` +# A :ref:`;-list <CMake Language Lists>` of ``<lib_name>`` that will be added to the include locations of ``<lang>``. +# +# Usage of mpiexec +# ^^^^^^^^^^^^^^^^ +# +# When using ``MPIEXEC_EXECUTABLE`` to execute MPI applications, you should typically +# use all of the ``MPIEXEC_EXECUTABLE`` flags as follows: # # :: # -# ${MPIEXEC} ${MPIEXEC_NUMPROC_FLAG} ${MPIEXEC_MAX_NUMPROCS} +# ${MPIEXEC_EXECUTABLE} ${MPIEXEC_NUMPROC_FLAG} ${MPIEXEC_MAX_NUMPROCS} # ${MPIEXEC_PREFLAGS} EXECUTABLE ${MPIEXEC_POSTFLAGS} ARGS # # where ``EXECUTABLE`` is the MPI program, and ``ARGS`` are the arguments to # pass to the MPI program. # +# Advanced variables for using MPI +# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +# +# The module can perform some advanced feature detections upon explicit request. +# +# **Important notice:** The following checks cannot be performed without *executing* an MPI test program. +# Consider the special considerations for the behavior of :command:`try_run` during cross compilation. +# Moreover, running an MPI program can cause additional issues, like a firewall notification on some systems. +# You should only enable these detections if you absolutely need the information. +# +# If the following variables are set to true, the respective search will be performed: +# +# ``MPI_DETERMINE_Fortran_CAPABILITIES`` +# Determine for all available Fortran bindings what the values of ``MPI_SUBARRAYS_SUPPORTED`` and +# ``MPI_ASYNC_PROTECTS_NONBLOCKING`` are and make their values available as ``MPI_Fortran_<binding>_SUBARRAYS`` +# and ``MPI_Fortran_<binding>_ASYNCPROT``, where ``<binding>`` is one of ``F77_HEADER``, ``F90_MODULE`` and +# ``F08_MODULE``. +# ``MPI_DETERMINE_LIBRARY_VERSION`` +# For each language, find the output of ``MPI_Get_library_version`` and make it available as ``MPI_<lang>_LIBRARY_VERSION``. +# This information is usually tied to the runtime component of an MPI implementation and might differ depending on ``<lang>``. +# Note that the return value is entirely implementation defined. This information might be used to identify +# the MPI vendor and for example pick the correct one of multiple third party binaries that matches the MPI vendor. +# # Backward Compatibility # ^^^^^^^^^^^^^^^^^^^^^^ # @@ -92,52 +229,60 @@ # # :: # -# MPI_FOUND MPI_COMPILER MPI_LIBRARY -# MPI_COMPILE_FLAGS MPI_INCLUDE_PATH MPI_EXTRA_LIBRARY -# MPI_LINK_FLAGS MPI_LIBRARIES +# MPI_COMPILER MPI_LIBRARY MPI_EXTRA_LIBRARY +# MPI_COMPILE_FLAGS MPI_INCLUDE_PATH MPI_LINK_FLAGS +# MPI_LIBRARIES # # In new projects, please use the ``MPI_<lang>_XXX`` equivalents. +# Additionally, the following variables are deprecated: +# +# ``MPI_<lang>_COMPILE_FLAGS`` +# Use ``MPI_<lang>_COMPILE_OPTIONS`` and ``MPI_<lang>_COMPILE_DEFINITIONS`` instead. +# ``MPI_<lang>_INCLUDE_PATH`` +# For consumption use ``MPI_<lang>_INCLUDE_DIRS`` and for specifying folders use ``MPI_<lang>_ADDITIONAL_INCLUDE_DIRS`` instead. +# ``MPIEXEC`` +# Use ``MPIEXEC_EXECUTABLE`` instead. -include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) +cmake_policy(PUSH) +cmake_policy(SET CMP0057 NEW) # if IN_LIST -# -# This part detects MPI compilers, attempting to wade through the mess of compiler names in -# a sensible way. -# -# The compilers are detected in this order: -# -# 1. Try to find the most generic available MPI compiler, as this is usually set up by -# cluster admins, e.g. if plain old mpicc is available, we'll use it and assume it's -# the right compiler. -# -# 2. If a generic mpicc is NOT found, then we attempt to find one that matches -# CMAKE_<lang>_COMPILER_ID. e.g. if you are using XL compilers, we'll try to find mpixlc -# and company, but not mpiicc. This hopefully prevents toolchain mismatches. -# -# If you want to force a particular MPI compiler other than what we autodetect (e.g. if you -# want to compile regular stuff with GNU and parallel stuff with Intel), you can always set -# your favorite MPI_<lang>_COMPILER explicitly and this stuff will be ignored. -# +include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) -# Start out with the generic MPI compiler names, as these are most commonly used. -set(_MPI_C_COMPILER_NAMES mpicc mpcc mpicc_r mpcc_r mpicc.bat) -set(_MPI_CXX_COMPILER_NAMES mpicxx mpiCC mpcxx mpCC mpic++ mpc++ - mpicxx_r mpiCC_r mpcxx_r mpCC_r mpic++_r mpc++_r - mpicxx.bat) -set(_MPI_Fortran_COMPILER_NAMES mpif95 mpif95_r mpf95 mpf95_r +# Generic compiler names +set(_MPI_C_GENERIC_COMPILER_NAMES mpicc mpcc mpicc_r mpcc_r) +set(_MPI_CXX_GENERIC_COMPILER_NAMES mpicxx mpiCC mpcxx mpCC mpic++ mpc++ + mpicxx_r mpiCC_r mpcxx_r mpCC_r mpic++_r mpc++_r) +set(_MPI_Fortran_GENERIC_COMPILER_NAMES mpif95 mpif95_r mpf95 mpf95_r mpif90 mpif90_r mpf90 mpf90_r - mpif77 mpif77_r mpf77 mpf77_r) + mpif77 mpif77_r mpf77 mpf77_r + mpifc) # GNU compiler names set(_MPI_GNU_C_COMPILER_NAMES mpigcc mpgcc mpigcc_r mpgcc_r) -set(_MPI_GNU_CXX_COMPILER_NAMES mpig++ mpg++ mpig++_r mpg++_r) +set(_MPI_GNU_CXX_COMPILER_NAMES mpig++ mpg++ mpig++_r mpg++_r mpigxx) set(_MPI_GNU_Fortran_COMPILER_NAMES mpigfortran mpgfortran mpigfortran_r mpgfortran_r mpig77 mpig77_r mpg77 mpg77_r) -# Intel MPI compiler names -set(_MPI_Intel_C_COMPILER_NAMES mpiicc mpiicc.bat) -set(_MPI_Intel_CXX_COMPILER_NAMES mpiicpc mpiicxx mpiic++ mpiiCC mpiicpc.bat) -set(_MPI_Intel_Fortran_COMPILER_NAMES mpiifort mpiif95 mpiif90 mpiif77 mpiifort.bat) +# Intel MPI compiler names on Windows +if(WIN32) + list(APPEND _MPI_C_GENERIC_COMPILER_NAMES mpicc.bat) + list(APPEND _MPI_CXX_GENERIC_COMPILER_NAMES mpicxx.bat) + list(APPEND _MPI_Fortran_GENERIC_COMPILER_NAMES mpifc.bat) + + # Intel MPI compiler names + set(_MPI_Intel_C_COMPILER_NAMES mpiicc.bat) + set(_MPI_Intel_CXX_COMPILER_NAMES mpiicpc.bat) + set(_MPI_Intel_Fortran_COMPILER_NAMES mpiifort.bat mpif77.bat mpif90.bat) + + # Intel MPI compiler names for MSMPI + set(_MPI_MSVC_C_COMPILER_NAMES mpicl.bat) + set(_MPI_MSVC_CXX_COMPILER_NAMES mpicl.bat) +else() + # Intel compiler names + set(_MPI_Intel_C_COMPILER_NAMES mpiicc) + set(_MPI_Intel_CXX_COMPILER_NAMES mpiicpc mpiicxx mpiic++) + set(_MPI_Intel_Fortran_COMPILER_NAMES mpiifort mpiif95 mpiif90 mpiif77) +endif() # PGI compiler names set(_MPI_PGI_C_COMPILER_NAMES mpipgcc mppgcc) @@ -153,411 +298,743 @@ set(_MPI_XL_Fortran_COMPILER_NAMES mpixlf95 mpixlf95_r mpxlf95 mpxlf95 mpixlf77 mpixlf77_r mpxlf77 mpxlf77_r mpixlf mpixlf_r mpxlf mpxlf_r) -# append vendor-specific compilers to the list if we either don't know the compiler id, -# or if we know it matches the regular compiler. -foreach (lang C CXX Fortran) - foreach (id GNU Intel PGI XL) - if (NOT CMAKE_${lang}_COMPILER_ID OR CMAKE_${lang}_COMPILER_ID STREQUAL id) - list(APPEND _MPI_${lang}_COMPILER_NAMES ${_MPI_${id}_${lang}_COMPILER_NAMES}) +# Prepend vendor-specific compiler wrappers to the list. If we don't know the compiler, +# attempt all of them. +# By attempting vendor-specific compiler names first, we should avoid situations where the compiler wrapper +# stems from a proprietary MPI and won't know which compiler it's being used for. For instance, Intel MPI +# controls its settings via the I_MPI_CC environment variables if the generic name is being used. +# If we know which compiler we're working with, we can use the most specialized wrapper there is in order to +# pick up the right settings for it. +foreach (LANG IN ITEMS C CXX Fortran) + set(_MPI_${LANG}_COMPILER_NAMES "") + foreach (id IN ITEMS GNU Intel MSVC PGI XL) + if (NOT CMAKE_${LANG}_COMPILER_ID OR CMAKE_${LANG}_COMPILER_ID STREQUAL id) + list(APPEND _MPI_${LANG}_COMPILER_NAMES ${_MPI_${id}_${LANG}_COMPILER_NAMES}${MPI_EXECUTABLE_SUFFIX}) endif() - unset(_MPI_${id}_${lang}_COMPILER_NAMES) # clean up the namespace here + unset(_MPI_${id}_${LANG}_COMPILER_NAMES) endforeach() + list(APPEND _MPI_${LANG}_COMPILER_NAMES ${_MPI_${LANG}_GENERIC_COMPILER_NAMES}${MPI_EXECUTABLE_SUFFIX}) + unset(_MPI_${LANG}_GENERIC_COMPILER_NAMES) endforeach() +# Names to try for mpiexec +# Only mpiexec commands are guaranteed to behave as described in the standard, +# mpirun commands are not covered by the standard in any way whatsoever. +# lamexec is the executable for LAM/MPI, srun is for SLURM or Open MPI with SLURM support. +# srun -n X <executable> is however a valid command, so it behaves 'like' mpiexec. +set(_MPIEXEC_NAMES_BASE mpiexec mpiexec.hydra mpiexec.mpd mpirun lamexec srun) -# Names to try for MPI exec -set(_MPI_EXEC_NAMES mpiexec mpirun lamexec srun) - -# Grab the path to MPI from the registry if we're on windows. -set(_MPI_PREFIX_PATH) -if(WIN32) - # MSMPI - file(TO_CMAKE_PATH "$ENV{MSMPI_BIN}" msmpi_bin_path) # The default path ends with a '\' and doesn't mix with ';' when appending. - list(APPEND _MPI_PREFIX_PATH "${msmpi_bin_path}") - unset(msmpi_bin_path) - list(APPEND _MPI_PREFIX_PATH "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MPI;InstallRoot]/Bin") - list(APPEND _MPI_PREFIX_PATH "$ENV{MSMPI_INC}/..") # The SDK is installed separately from the runtime - # MPICH - list(APPEND _MPI_PREFIX_PATH "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MPICH\\SMPD;binary]/..") - list(APPEND _MPI_PREFIX_PATH "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MPICH2;Path]") - list(APPEND _MPI_PREFIX_PATH "$ENV{ProgramW6432}/MPICH2/") -endif() - -# Build a list of prefixes to search for MPI. -foreach(SystemPrefixDir ${CMAKE_SYSTEM_PREFIX_PATH}) - foreach(MpiPackageDir ${_MPI_PREFIX_PATH}) - if(EXISTS ${SystemPrefixDir}/${MpiPackageDir}) - list(APPEND _MPI_PREFIX_PATH "${SystemPrefixDir}/${MpiPackageDir}") - endif() - endforeach() +unset(_MPIEXEC_NAMES) +foreach(_MPIEXEC_NAME IN LISTS _MPIEXEC_NAMES_BASE) + list(APPEND _MPIEXEC_NAMES "${_MPIEXEC_NAME}${MPI_EXECUTABLE_SUFFIX}") endforeach() +unset(_MPIEXEC_NAMES_BASE) -function (_mpi_check_compiler compiler options cmdvar resvar) +function (_MPI_check_compiler LANG QUERY_FLAG OUTPUT_VARIABLE RESULT_VARIABLE) + if(DEFINED MPI_${LANG}_COMPILER_FLAGS) + separate_arguments(_MPI_COMPILER_WRAPPER_OPTIONS NATIVE_COMMAND "${MPI_${LANG}_COMPILER_FLAGS}") + else() + separate_arguments(_MPI_COMPILER_WRAPPER_OPTIONS NATIVE_COMMAND "${MPI_COMPILER_FLAGS}") + endif() execute_process( - COMMAND "${compiler}" ${options} - OUTPUT_VARIABLE cmdline OUTPUT_STRIP_TRAILING_WHITESPACE - ERROR_VARIABLE cmdline ERROR_STRIP_TRAILING_WHITESPACE - RESULT_VARIABLE success) - # Intel MPI 5.0.1 will return a zero return code even when the - # argument to the MPI compiler wrapper is unknown. Attempt to - # catch this case. - if(cmdline MATCHES "undefined reference" OR cmdline MATCHES "unrecognized") - set(success 255 ) - endif() - set(${cmdvar} "${cmdline}" PARENT_SCOPE) - set(${resvar} "${success}" PARENT_SCOPE) + COMMAND ${MPI_${LANG}_COMPILER} ${_MPI_COMPILER_WRAPPER_OPTIONS} ${QUERY_FLAG} + OUTPUT_VARIABLE WRAPPER_OUTPUT OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_VARIABLE WRAPPER_OUTPUT ERROR_STRIP_TRAILING_WHITESPACE + RESULT_VARIABLE WRAPPER_RETURN) + # Some compiler wrappers will yield spurious zero return values, for example + # Intel MPI tolerates unknown arguments and if the MPI wrappers loads a shared + # library that has invalid or missing version information there would be warning + # messages emitted by ld.so in the compiler output. In either case, we'll treat + # the output as invalid. + if("${WRAPPER_OUTPUT}" MATCHES "undefined reference|unrecognized|need to set|no version information available") + set(WRAPPER_RETURN 255) + endif() + # Ensure that no error output might be passed upwards. + if(NOT WRAPPER_RETURN EQUAL 0) + unset(WRAPPER_OUTPUT) + endif() + set(${OUTPUT_VARIABLE} "${WRAPPER_OUTPUT}" PARENT_SCOPE) + set(${RESULT_VARIABLE} "${WRAPPER_RETURN}" PARENT_SCOPE) endfunction() -# -# interrogate_mpi_compiler(lang try_libs) -# -# Attempts to extract compiler and linker args from an MPI compiler. The arguments set -# by this function are: -# -# MPI_<lang>_INCLUDE_PATH MPI_<lang>_LINK_FLAGS MPI_<lang>_FOUND -# MPI_<lang>_COMPILE_FLAGS MPI_<lang>_LIBRARIES -# -# MPI_<lang>_COMPILER must be set beforehand to the absolute path to an MPI compiler for -# <lang>. Additionally, MPI_<lang>_INCLUDE_PATH and MPI_<lang>_LIBRARIES may be set -# to skip autodetection. -# -# If try_libs is TRUE, this will also attempt to find plain MPI libraries in the usual -# way. In general, this is not as effective as interrogating the compilers, as it -# ignores language-specific flags and libraries. However, some MPI implementations -# (Windows implementations) do not have compiler wrappers, so this approach must be used. -# -function (interrogate_mpi_compiler lang try_libs) - # MPI_${lang}_NO_INTERROGATE will be set to a compiler name when the *regular* compiler was - # discovered to be the MPI compiler. This happens on machines like the Cray XE6 that use - # modules to set cc, CC, and ftn to the MPI compilers. If the user force-sets another MPI - # compiler, MPI_${lang}_COMPILER won't be equal to MPI_${lang}_NO_INTERROGATE, and we'll - # inspect that compiler anew. This allows users to set new compilers w/o rm'ing cache. - string(COMPARE NOTEQUAL "${MPI_${lang}_NO_INTERROGATE}" "${MPI_${lang}_COMPILER}" interrogate) - - # If MPI is set already in the cache, don't bother with interrogating the compiler. - if (interrogate AND ((NOT MPI_${lang}_INCLUDE_PATH) OR (NOT MPI_${lang}_LIBRARIES))) - if (MPI_${lang}_COMPILER) - # Check whether the -showme:compile option works. This indicates that we have either OpenMPI - # or a newer version of LAM-MPI, and implies that -showme:link will also work. - _mpi_check_compiler("${MPI_${lang}_COMPILER}" "-showme:compile" MPI_COMPILE_CMDLINE MPI_COMPILER_RETURN) - if (MPI_COMPILER_RETURN EQUAL 0) - # If we appear to have -showme:compile, then we should - # also have -showme:link. Try it. - execute_process( - COMMAND ${MPI_${lang}_COMPILER} -showme:link - OUTPUT_VARIABLE MPI_LINK_CMDLINE OUTPUT_STRIP_TRAILING_WHITESPACE - ERROR_VARIABLE MPI_LINK_CMDLINE ERROR_STRIP_TRAILING_WHITESPACE - RESULT_VARIABLE MPI_COMPILER_RETURN) - - if (MPI_COMPILER_RETURN EQUAL 0) - # We probably have -showme:incdirs and -showme:libdirs as well, - # so grab that while we're at it. - execute_process( - COMMAND ${MPI_${lang}_COMPILER} -showme:incdirs - OUTPUT_VARIABLE MPI_INCDIRS OUTPUT_STRIP_TRAILING_WHITESPACE - ERROR_VARIABLE MPI_INCDIRS ERROR_STRIP_TRAILING_WHITESPACE) - - execute_process( - COMMAND ${MPI_${lang}_COMPILER} -showme:libdirs - OUTPUT_VARIABLE MPI_LIBDIRS OUTPUT_STRIP_TRAILING_WHITESPACE - ERROR_VARIABLE MPI_LIBDIRS ERROR_STRIP_TRAILING_WHITESPACE) +function (_MPI_interrogate_compiler lang) + unset(MPI_COMPILE_CMDLINE) + unset(MPI_LINK_CMDLINE) + + unset(MPI_COMPILE_OPTIONS_WORK) + unset(MPI_COMPILE_DEFINITIONS_WORK) + unset(MPI_INCLUDE_DIRS_WORK) + unset(MPI_LINK_FLAGS_WORK) + unset(MPI_LIB_NAMES_WORK) + unset(MPI_LIB_FULLPATHS_WORK) + + # Check whether the -showme:compile option works. This indicates that we have either Open MPI + # or a newer version of LAM/MPI, and implies that -showme:link will also work. + # Open MPI also supports -show, but separates linker and compiler information + _MPI_check_compiler(${LANG} "-showme:compile" MPI_COMPILE_CMDLINE MPI_COMPILER_RETURN) + if (MPI_COMPILER_RETURN EQUAL 0) + _MPI_check_compiler(${LANG} "-showme:link" MPI_LINK_CMDLINE MPI_COMPILER_RETURN) + + if (NOT MPI_COMPILER_RETURN EQUAL 0) + unset(MPI_COMPILE_CMDLINE) + endif() + endif() - else() - # reset things here if something went wrong. - set(MPI_COMPILE_CMDLINE) - set(MPI_LINK_CMDLINE) - endif() - endif () + # MPICH and MVAPICH offer -compile-info and -link-info. + # For modern versions, both do the same as -show. However, for old versions, they do differ + # when called for mpicxx and mpif90 and it's necessary to use them over -show in order to find the + # removed MPI C++ bindings. + if (NOT MPI_COMPILER_RETURN EQUAL 0) + _MPI_check_compiler(${LANG} "-compile-info" MPI_COMPILE_CMDLINE MPI_COMPILER_RETURN) + + if (MPI_COMPILER_RETURN EQUAL 0) + _MPI_check_compiler(${LANG} "-link-info" MPI_LINK_CMDLINE MPI_COMPILER_RETURN) - # Older versions of LAM-MPI have "-showme". Try to find that. if (NOT MPI_COMPILER_RETURN EQUAL 0) - _mpi_check_compiler("${MPI_${lang}_COMPILER}" "-showme" MPI_COMPILE_CMDLINE MPI_COMPILER_RETURN) + unset(MPI_COMPILE_CMDLINE) endif() + endif() + endif() - # MVAPICH uses -compile-info and -link-info. Try them. - if (NOT MPI_COMPILER_RETURN EQUAL 0) - _mpi_check_compiler("${MPI_${lang}_COMPILER}" "-compile-info" MPI_COMPILE_CMDLINE MPI_COMPILER_RETURN) - - # If we have compile-info, also have link-info. - if (MPI_COMPILER_RETURN EQUAL 0) - execute_process( - COMMAND ${MPI_${lang}_COMPILER} -link-info - OUTPUT_VARIABLE MPI_LINK_CMDLINE OUTPUT_STRIP_TRAILING_WHITESPACE - ERROR_VARIABLE MPI_LINK_CMDLINE ERROR_STRIP_TRAILING_WHITESPACE - RESULT_VARIABLE MPI_COMPILER_RETURN) - endif() + # MPICH, MVAPICH2 and Intel MPI just use "-show". Open MPI also offers this, but the + # -showme commands are more specialized. + if (NOT MPI_COMPILER_RETURN EQUAL 0) + _MPI_check_compiler(${LANG} "-show" MPI_COMPILE_CMDLINE MPI_COMPILER_RETURN) + endif() - # make sure we got compile and link. Reset vars if something's wrong. - if (NOT MPI_COMPILER_RETURN EQUAL 0) - set(MPI_COMPILE_CMDLINE) - set(MPI_LINK_CMDLINE) - endif() - endif() + # Older versions of LAM/MPI have "-showme". Open MPI also supports this. + # Unknown to MPICH, MVAPICH and Intel MPI. + if (NOT MPI_COMPILER_RETURN EQUAL 0) + _MPI_check_compiler(${LANG} "-showme" MPI_COMPILE_CMDLINE MPI_COMPILER_RETURN) + endif() - # MPICH just uses "-show". Try it. - if (NOT MPI_COMPILER_RETURN EQUAL 0) - _mpi_check_compiler("${MPI_${lang}_COMPILER}" "-show" MPI_COMPILE_CMDLINE MPI_COMPILER_RETURN) - endif() + if (NOT (MPI_COMPILER_RETURN EQUAL 0) OR NOT (DEFINED MPI_COMPILE_CMDLINE)) + # Cannot interrogate this compiler, so exit. + set(MPI_${LANG}_WRAPPER_FOUND FALSE PARENT_SCOPE) + return() + endif() + unset(MPI_COMPILER_RETURN) - if (MPI_COMPILER_RETURN EQUAL 0) - # We have our command lines, but we might need to copy MPI_COMPILE_CMDLINE - # into MPI_LINK_CMDLINE, if we didn't find the link line. - if (NOT MPI_LINK_CMDLINE) - set(MPI_LINK_CMDLINE ${MPI_COMPILE_CMDLINE}) - endif() + # We have our command lines, but we might need to copy MPI_COMPILE_CMDLINE + # into MPI_LINK_CMDLINE, if we didn't find the link line. + if (NOT DEFINED MPI_LINK_CMDLINE) + set(MPI_LINK_CMDLINE "${MPI_COMPILE_CMDLINE}") + endif() + + # At this point, we obtained some output from a compiler wrapper that works. + # We'll now try to parse it into variables with meaning to us. + if("${LANG}" STREQUAL "Fortran") + # Some MPICH-1 and MVAPICH-1 versions return a three command answer for Fortran, consisting + # out of a symlink command for mpif.h, the actual compiler command and a deletion of the + # created symlink. We need to detect that case, remember the include path and drop the + # symlink/deletion operation to obtain the link/compile lines we'd usually expect. + if("${MPI_COMPILE_CMDLINE}" MATCHES "^ln -s ([^\" ]+|\"[^\"]+\") mpif.h") + get_filename_component(MPI_INCLUDE_DIRS_WORK "${CMAKE_MATCH_1}" DIRECTORY) + string(REGEX REPLACE "^ln -s ([^\" ]+|\"[^\"]+\") mpif.h\n" "" MPI_COMPILE_CMDLINE "${MPI_COMPILE_CMDLINE}") + string(REGEX REPLACE "^ln -s ([^\" ]+|\"[^\"]+\") mpif.h\n" "" MPI_LINK_CMDLINE "${MPI_LINK_CMDLINE}") + string(REGEX REPLACE "\nrm -f mpif.h$" "" MPI_COMPILE_CMDLINE "${MPI_COMPILE_CMDLINE}") + string(REGEX REPLACE "\nrm -f mpif.h$" "" MPI_LINK_CMDLINE "${MPI_LINK_CMDLINE}") + endif() + endif() + + # The Intel MPI wrapper on Linux will emit some objcopy commands after its compile command + # if -static_mpi was passed to the wrapper. To avoid spurious matches, we need to drop these lines. + if(UNIX) + string(REGEX REPLACE "(^|\n)objcopy[^\n]+(\n|$)" "" MPI_COMPILE_CMDLINE "${MPI_COMPILE_CMDLINE}") + string(REGEX REPLACE "(^|\n)objcopy[^\n]+(\n|$)" "" MPI_LINK_CMDLINE "${MPI_LINK_CMDLINE}") + endif() + + # Extract compile options from the compile command line. + string(REGEX MATCHALL "(^| )-f([^\" ]+|\"[^\"]+\")" MPI_ALL_COMPILE_OPTIONS "${MPI_COMPILE_CMDLINE}") + + foreach(_MPI_COMPILE_OPTION IN LISTS MPI_ALL_COMPILE_OPTIONS) + string(REGEX REPLACE "^ " "" _MPI_COMPILE_OPTION "${_MPI_COMPILE_OPTION}") + # Ignore -fstack-protector directives: These occur on MPICH and MVAPICH when the libraries + # themselves were built with this flag. However, this flag is unrelated to using MPI, and + # we won't match the accompanying --param-ssp-size and -Wp,-D_FORTIFY_SOURCE flags and therefore + # produce inconsistent results with the regularly flags. + # Similarly, aliasing flags do not belong into our flag array. + if(NOT "${_MPI_COMPILE_OPTION}" MATCHES "^-f(stack-protector|(no-|)strict-aliasing|PI[CE]|pi[ce])") + list(APPEND MPI_COMPILE_OPTIONS_WORK "${_MPI_COMPILE_OPTION}") + endif() + endforeach() + + # Same deal, with the definitions. We also treat arguments passed to the preprocessor directly. + string(REGEX MATCHALL "(^| )(-Wp,|-Xpreprocessor |)[-/]D([^\" ]+|\"[^\"]+\")" MPI_ALL_COMPILE_DEFINITIONS "${MPI_COMPILE_CMDLINE}") + + foreach(_MPI_COMPILE_DEFINITION IN LISTS MPI_ALL_COMPILE_DEFINITIONS) + string(REGEX REPLACE "^ ?(-Wp,|-Xpreprocessor )?[-/]D" "" _MPI_COMPILE_DEFINITION "${_MPI_COMPILE_DEFINITION}") + string(REPLACE "\"" "" _MPI_COMPILE_DEFINITION "${_MPI_COMPILE_DEFINITION}") + if(NOT "${_MPI_COMPILE_DEFINITION}" MATCHES "^_FORTIFY_SOURCE.*") + list(APPEND MPI_COMPILE_DEFINITIONS_WORK "${_MPI_COMPILE_DEFINITION}") + endif() + endforeach() + + # Extract include paths from compile command line + string(REGEX MATCHALL "(^| )[-/]I([^\" ]+|\"[^\"]+\")" MPI_ALL_INCLUDE_PATHS "${MPI_COMPILE_CMDLINE}") + + # If extracting failed to work, we'll try using -showme:incdirs. + if (NOT MPI_ALL_INCLUDE_PATHS) + _MPI_check_compiler(${LANG} "-showme:incdirs" MPI_INCDIRS_CMDLINE MPI_INCDIRS_COMPILER_RETURN) + if(MPI_INCDIRS_COMPILER_RETURN) + separate_arguments(MPI_ALL_INCLUDE_PATHS NATIVE_COMMAND "${MPI_INCDIRS_CMDLINE}") + endif() + endif() + + foreach(_MPI_INCLUDE_PATH IN LISTS MPI_ALL_INCLUDE_PATHS) + string(REGEX REPLACE "^ ?[-/]I" "" _MPI_INCLUDE_PATH "${_MPI_INCLUDE_PATH}") + string(REPLACE "\"" "" _MPI_INCLUDE_PATH "${_MPI_INCLUDE_PATH}") + get_filename_component(_MPI_INCLUDE_PATH "${_MPI_INCLUDE_PATH}" REALPATH) + list(APPEND MPI_INCLUDE_DIRS_WORK "${_MPI_INCLUDE_PATH}") + endforeach() + + # Extract linker paths from the link command line + string(REGEX MATCHALL "(^| )(-Wl,|-Xlinker |)(-L|[/-]LIBPATH:|[/-]libpath:)([^\" ]+|\"[^\"]+\")" MPI_ALL_LINK_PATHS "${MPI_LINK_CMDLINE}") + + # If extracting failed to work, we'll try using -showme:libdirs. + if (NOT MPI_ALL_LINK_PATHS) + _MPI_check_compiler(${LANG} "-showme:libdirs" MPI_LIBDIRS_CMDLINE MPI_LIBDIRS_COMPILER_RETURN) + if(MPI_LIBDIRS_COMPILER_RETURN) + separate_arguments(MPI_ALL_LINK_PATHS NATIVE_COMMAND "${MPI_LIBDIRS_CMDLINE}") + endif() + endif() + + foreach(_MPI_LPATH IN LISTS MPI_ALL_LINK_PATHS) + string(REGEX REPLACE "^ ?(-Wl,|-Xlinker )?(-L|[/-]LIBPATH:|[/-]libpath:)" "" _MPI_LPATH "${_MPI_LPATH}") + string(REPLACE "\"" "" _MPI_LPATH "${_MPI_LPATH}") + get_filename_component(_MPI_LPATH "${_MPI_LPATH}" REALPATH) + list(APPEND MPI_LINK_DIRECTORIES_WORK "${_MPI_LPATH}") + endforeach() + + # Extract linker flags from the link command line + string(REGEX MATCHALL "(^| )(-Wl,|-Xlinker )([^\" ]+|\"[^\"]+\")" MPI_ALL_LINK_FLAGS "${MPI_LINK_CMDLINE}") + + foreach(_MPI_LINK_FLAG IN LISTS MPI_ALL_LINK_FLAGS) + string(STRIP "${_MPI_LINK_FLAG}" _MPI_LINK_FLAG) + # MPI might be marked to build with non-executable stacks but this should not propagate. + if (NOT "${_MPI_LINK_FLAG}" MATCHES "(-Wl,|-Xlinker )-z,noexecstack") + if (MPI_LINK_FLAGS_WORK) + string(APPEND MPI_LINK_FLAGS_WORK " ${_MPI_LINK_FLAG}") else() - message(STATUS "Unable to determine MPI from MPI driver ${MPI_${lang}_COMPILER}") - set(MPI_COMPILE_CMDLINE) - set(MPI_LINK_CMDLINE) + set(MPI_LINK_FLAGS_WORK "${_MPI_LINK_FLAG}") endif() + endif() + endforeach() - # Here, we're done with the interrogation part, and we'll try to extract args we care - # about from what we learned from the compiler wrapper scripts. - - # If interrogation came back with something, extract our variable from the MPI command line - if (MPI_COMPILE_CMDLINE OR MPI_LINK_CMDLINE) - # Extract compile flags from the compile command line. - string(REGEX MATCHALL "(^| )-[Df]([^\" ]+|\"[^\"]+\")" MPI_ALL_COMPILE_FLAGS "${MPI_COMPILE_CMDLINE}") - set(MPI_COMPILE_FLAGS_WORK) + # Extract the set of libraries to link against from the link command + # line + string(REGEX MATCHALL "(^| )-l([^\" ]+|\"[^\"]+\")" MPI_LIBNAMES "${MPI_LINK_CMDLINE}") - foreach(FLAG ${MPI_ALL_COMPILE_FLAGS}) - string(REGEX REPLACE "^ " "" FLAG ${FLAG}) - if (MPI_COMPILE_FLAGS_WORK) - string(APPEND MPI_COMPILE_FLAGS_WORK " ${FLAG}") - else() - set(MPI_COMPILE_FLAGS_WORK ${FLAG}) - endif() - endforeach() + foreach(_MPI_LIB_NAME IN LISTS MPI_LIBNAMES) + string(REGEX REPLACE "^ ?-l" "" _MPI_LIB_NAME "${_MPI_LIB_NAME}") + string(REPLACE "\"" "" _MPI_LIB_NAME "${_MPI_LIB_NAME}") + get_filename_component(_MPI_LIB_PATH "${_MPI_LIB_NAME}" DIRECTORY) + if(NOT "${_MPI_LIB_PATH}" STREQUAL "") + list(APPEND MPI_LIB_FULLPATHS_WORK "${_MPI_LIB_NAME}") + else() + list(APPEND MPI_LIB_NAMES_WORK "${_MPI_LIB_NAME}") + endif() + endforeach() - # Extract include paths from compile command line - string(REGEX MATCHALL "(^| )-I([^\" ]+|\"[^\"]+\")" MPI_ALL_INCLUDE_PATHS "${MPI_COMPILE_CMDLINE}") - set(MPI_INCLUDE_PATH_WORK) + if(WIN32) + # A compiler wrapper on Windows will just have the name of the + # library to link on its link line, potentially with a full path + string(REGEX MATCHALL "(^| )([^\" ]+\\.lib|\"[^\"]+\\.lib\")" MPI_LIBNAMES "${MPI_LINK_CMDLINE}") + foreach(_MPI_LIB_NAME IN LISTS MPI_LIBNAMES) + string(REGEX REPLACE "^ " "" _MPI_LIB_NAME "${_MPI_LIB_NAME}") + string(REPLACE "\"" "" _MPI_LIB_NAME "${_MPI_LIB_NAME}") + get_filename_component(_MPI_LIB_PATH "${_MPI_LIB_NAME}" DIRECTORY) + if(NOT "${_MPI_LIB_PATH}" STREQUAL "") + list(APPEND MPI_LIB_FULLPATHS_WORK "${_MPI_LIB_NAME}") + else() + list(APPEND MPI_LIB_NAMES_WORK "${_MPI_LIB_NAME}") + endif() + endforeach() + else() + # On UNIX platforms, archive libraries can be given with full path. + string(REGEX MATCHALL "(^| )([^\" ]+\\.a|\"[^\"]+\\.a\")" MPI_LIBFULLPATHS "${MPI_LINK_CMDLINE}") + foreach(_MPI_LIB_NAME IN LISTS MPI_LIBFULLPATHS) + string(REGEX REPLACE "^ " "" _MPI_LIB_NAME "${_MPI_LIB_NAME}") + string(REPLACE "\"" "" _MPI_LIB_NAME "${_MPI_LIB_NAME}") + get_filename_component(_MPI_LIB_PATH "${_MPI_LIB_NAME}" DIRECTORY) + if(NOT "${_MPI_LIB_PATH}" STREQUAL "") + list(APPEND MPI_LIB_FULLPATHS_WORK "${_MPI_LIB_NAME}") + else() + list(APPEND MPI_LIB_NAMES_WORK "${_MPI_LIB_NAME}") + endif() + endforeach() + endif() - foreach(IPATH ${MPI_ALL_INCLUDE_PATHS}) - string(REGEX REPLACE "^ ?-I" "" IPATH ${IPATH}) - string(REPLACE "//" "/" IPATH ${IPATH}) - string(REPLACE "\"" "" IPATH ${IPATH}) - file(TO_CMAKE_PATH "${IPATH}" IPATH) - list(APPEND MPI_INCLUDE_PATH_WORK ${IPATH}) - endforeach() + # An MPI compiler wrapper could have its MPI libraries in the implictly + # linked directories of the compiler itself. + if(DEFINED CMAKE_${LANG}_IMPLICIT_LINK_DIRECTORIES) + list(APPEND MPI_LINK_DIRECTORIES_WORK "${CMAKE_${LANG}_IMPLICIT_LINK_DIRECTORIES}") + endif() - # try using showme:incdirs if extracting didn't work. - if (NOT MPI_INCLUDE_PATH_WORK) - set(MPI_INCLUDE_PATH_WORK ${MPI_INCDIRS}) - separate_arguments(MPI_INCLUDE_PATH_WORK) - endif() + # Determine full path names for all of the libraries that one needs + # to link against in an MPI program + unset(MPI_PLAIN_LIB_NAMES_WORK) + foreach(_MPI_LIB_NAME IN LISTS MPI_LIB_NAMES_WORK) + get_filename_component(_MPI_PLAIN_LIB_NAME "${_MPI_LIB_NAME}" NAME_WE) + list(APPEND MPI_PLAIN_LIB_NAMES_WORK "${_MPI_PLAIN_LIB_NAME}") + find_library(MPI_${_MPI_PLAIN_LIB_NAME}_LIBRARY + NAMES "${_MPI_LIB_NAME}" "lib${_MPI_LIB_NAME}" + HINTS ${MPI_LINK_DIRECTORIES_WORK} + DOC "Location of the ${_MPI_PLAIN_LIB_NAME} library for MPI" + ) + mark_as_advanced(MPI_${_MPI_PLAIN_LIB_NAME}_LIBRARY) + endforeach() - # If all else fails, just search for mpi.h in the normal include paths. - if (NOT MPI_INCLUDE_PATH_WORK) - set(MPI_HEADER_PATH "MPI_HEADER_PATH-NOTFOUND" CACHE FILEPATH "Cleared" FORCE) - find_path(MPI_HEADER_PATH mpi.h - HINTS ${_MPI_BASE_DIR} ${_MPI_PREFIX_PATH} - PATH_SUFFIXES include) - set(MPI_INCLUDE_PATH_WORK ${MPI_HEADER_PATH}) - endif() + # Deal with the libraries given with full path next + unset(MPI_DIRECT_LIB_NAMES_WORK) + foreach(_MPI_LIB_FULLPATH IN LISTS MPI_LIB_FULLPATHS_WORK) + get_filename_component(_MPI_PLAIN_LIB_NAME "${_MPI_LIB_FULLPATH}" NAME_WE) + get_filename_component(_MPI_LIB_NAME "${_MPI_LIB_FULLPATH}" NAME) + get_filename_component(_MPI_LIB_PATH "${_MPI_LIB_FULLPATH}" DIRECTORY) + list(APPEND MPI_DIRECT_LIB_NAMES_WORK "${_MPI_PLAIN_LIB_NAME}") + find_library(MPI_${_MPI_PLAIN_LIB_NAME}_LIBRARY + NAMES "${_MPI_LIB_NAME}" + HINTS ${_MPI_LIB_PATH} + DOC "Location of the ${_MPI_PLAIN_LIB_NAME} library for MPI" + ) + mark_as_advanced(MPI_${_MPI_PLAIN_LIB_NAME}_LIBRARY) + endforeach() + if(MPI_DIRECT_LIB_NAMES_WORK) + set(MPI_PLAIN_LIB_NAMES_WORK "${MPI_DIRECT_LIB_NAMES_WORK};${MPI_PLAIN_LIB_NAMES_WORK}") + endif() - # Extract linker paths from the link command line - string(REGEX MATCHALL "(^| |-Wl,)(-L|/LIBPATH:)([^\" ]+|\"[^\"]+\")" MPI_ALL_LINK_PATHS "${MPI_LINK_CMDLINE}") - set(MPI_LINK_PATH) - foreach(LPATH ${MPI_ALL_LINK_PATHS}) - string(REGEX REPLACE "^(| |-Wl,)(-L|/LIBPATH:)" "" LPATH ${LPATH}) - string(REPLACE "//" "/" LPATH ${LPATH}) - list(APPEND MPI_LINK_PATH ${LPATH}) - endforeach() + # MPI might require pthread to work. The above mechanism wouldn't detect it, but we need to + # link it in that case. -lpthread is covered by the normal library treatment on the other hand. + if("${MPI_COMPILE_CMDLINE}" MATCHES "-pthread") + list(APPEND MPI_COMPILE_OPTIONS_WORK "-pthread") + if(MPI_LINK_FLAGS_WORK) + string(APPEND MPI_LINK_FLAGS_WORK " -pthread") + else() + set(MPI_LINK_FLAGS_WORK "-pthread") + endif() + endif() - # try using showme:libdirs if extracting didn't work. - if (NOT MPI_LINK_PATH) - set(MPI_LINK_PATH ${MPI_LIBDIRS}) - separate_arguments(MPI_LINK_PATH) - endif() + # If we found MPI, set up all of the appropriate cache entries + if(NOT MPI_${LANG}_COMPILE_OPTIONS) + set(MPI_${LANG}_COMPILE_OPTIONS ${MPI_COMPILE_OPTIONS_WORK} CACHE STRING "MPI ${LANG} compilation options" FORCE) + endif() + if(NOT MPI_${LANG}_COMPILE_DEFINITIONS) + set(MPI_${LANG}_COMPILE_DEFINITIONS ${MPI_COMPILE_DEFINITIONS_WORK} CACHE STRING "MPI ${LANG} compilation definitions" FORCE) + endif() + if(NOT MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS) + set(MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS ${MPI_INCLUDE_DIRS_WORK} CACHE STRING "MPI ${LANG} additional include directories" FORCE) + endif() + if(NOT MPI_${LANG}_LINK_FLAGS) + set(MPI_${LANG}_LINK_FLAGS ${MPI_LINK_FLAGS_WORK} CACHE STRING "MPI ${LANG} linker flags" FORCE) + endif() + if(NOT MPI_${LANG}_LIB_NAMES) + set(MPI_${LANG}_LIB_NAMES ${MPI_PLAIN_LIB_NAMES_WORK} CACHE STRING "MPI ${LANG} libraries to link against" FORCE) + endif() + set(MPI_${LANG}_WRAPPER_FOUND TRUE PARENT_SCOPE) +endfunction() - # Extract linker flags from the link command line - string(REGEX MATCHALL "(^| )(-Wl,|-Xlinker )([^\" ]+|\"[^\"]+\")" MPI_ALL_LINK_FLAGS "${MPI_LINK_CMDLINE}") - set(MPI_LINK_FLAGS_WORK) - foreach(FLAG ${MPI_ALL_LINK_FLAGS}) - string(REGEX REPLACE "^ " "" FLAG ${FLAG}) - if (MPI_LINK_FLAGS_WORK) - string(APPEND MPI_LINK_FLAGS_WORK " ${FLAG}") - else() - set(MPI_LINK_FLAGS_WORK ${FLAG}) - endif() - endforeach() +function(_MPI_guess_settings LANG) + set(MPI_GUESS_FOUND FALSE) + # Currently only MSMPI and MPICH2 on Windows are supported, so we can skip this search if we're not targeting that. + if(WIN32) + # MSMPI + + # The environment variables MSMPI_INC and MSMPILIB32/64 are the only ways of locating the MSMPI_SDK, + # which is installed separately from the runtime. Thus it's possible to have mpiexec but not MPI headers + # or import libraries and vice versa. + if(NOT MPI_GUESS_LIBRARY_NAME OR "${MPI_GUESS_LIBRARY_NAME}" STREQUAL "MSMPI") + # We first attempt to locate the msmpi.lib. Should be find it, we'll assume that the MPI present is indeed + # Microsoft MPI. + if("${CMAKE_SIZEOF_VOID_P}" EQUAL 8) + set(MPI_MSMPI_LIB_PATH "$ENV{MSMPI_LIB64}") + set(MPI_MSMPI_INC_PATH_EXTRA "$ENV{MSMPI_INC}/x64") + else() + set(MPI_MSMPI_LIB_PATH "$ENV{MSMPI_LIB32}") + set(MPI_MSMPI_INC_PATH_EXTRA "$ENV{MSMPI_INC}/x86") + endif() - # Extract the set of libraries to link against from the link command - # line - string(REGEX MATCHALL "(^| )-l([^\" ]+|\"[^\"]+\")" MPI_LIBNAMES "${MPI_LINK_CMDLINE}") - if(WIN32) - # The intel wrappers on windows link against static versions of the MPI libraries. - # The static libraries are simply listed on the command line without -l. - # For instance: " icl ... impi.lib " - string(REGEX MATCHALL "(^| )([^\" ]+)\\.lib" tmp "${MPI_LINK_CMDLINE}") - list(APPEND MPI_LIBNAMES ${tmp}) + find_library(MPI_msmpi_LIBRARY + NAMES msmpi + HINTS ${MPI_MSMPI_LIB_PATH} + DOC "Location of the msmpi library for Microsoft MPI") + mark_as_advanced(MPI_msmpi_LIBRARY) + + if(MPI_msmpi_LIBRARY) + # Next, we attempt to locate the MPI header. Note that for Fortran we know that mpif.h is a way + # MSMPI can be used and therefore that header has to be present. + if(NOT MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS) + get_filename_component(MPI_MSMPI_INC_DIR "$ENV{MSMPI_INC}" REALPATH) + set(MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS "${MPI_MSMPI_INC_DIR}" CACHE STRING "MPI ${LANG} additional include directories" FORCE) + unset(MPI_MSMPI_INC_DIR) endif() - # add the compiler implicit directories because some compilers - # such as the intel compiler have libraries that show up - # in the showme list that can only be found in the implicit - # link directories of the compiler. - if (DEFINED CMAKE_${lang}_IMPLICIT_LINK_DIRECTORIES) - string(APPEND MPI_LINK_PATH - ";${CMAKE_${lang}_IMPLICIT_LINK_DIRECTORIES}") - endif () - - # Determine full path names for all of the libraries that one needs - # to link against in an MPI program - foreach(LIB ${MPI_LIBNAMES}) - string(REGEX REPLACE "^ ?-l" "" LIB ${LIB}) - if(WIN32) - string(REGEX REPLACE "\\.lib$" "" LIB ${LIB}) + # For MSMPI, one can compile the MPI module by building the mpi.f90 shipped with the MSMPI SDK, + # thus it might be present or provided by the user. Figuring out which is supported is done later on. + # The PGI Fortran compiler for instance ships a prebuilt set of modules in its own include folder. + # Should a user be employing PGI or have built its own set and provided it via cache variables, the + # splitting routine would have located the module files. + + # For C and C++, we're done here (MSMPI does not ship the MPI-2 C++ bindings) - however, for Fortran + # we need some extra library to glue Fortran support together: + # MSMPI ships 2-4 Fortran libraries, each for different Fortran compiler behaviors. The library names + # ending with a c are using the cdecl calling convention, whereas those ending with an s are for Fortran + # implementations using stdcall. Therefore, the 64-bit MSMPI only ships those ending in 'c', whereas the 32-bit + # has both variants available. + # The second difference is the last but one letter, if it's an e(nd), the length of a string argument is + # passed by the Fortran compiler after all other arguments on the parameter list, if it's an m(ixed), + # it's passed immediately after the string address. + + # To summarize: + # - msmpifec: CHARACTER length passed after the parameter list and using cdecl calling convention + # - msmpifmc: CHARACTER length passed directly after string address and using cdecl calling convention + # - msmpifes: CHARACTER length passed after the parameter list and using stdcall calling convention + # - msmpifms: CHARACTER length passed directly after string address and using stdcall calling convention + # 32-bit MSMPI ships all four libraries, 64-bit MSMPI ships only the first two. + + # As is, Intel Fortran and PGI Fortran both use the 'ec' variant of the calling convention, whereas + # the old Compaq Visual Fortran compiler defaulted to the 'ms' version. It's possible to make Intel Fortran + # use the CVF calling convention using /iface:cvf, but we assume - and this is also assumed in FortranCInterface - + # this isn't the case. It's also possible to make CVF use the 'ec' variant, using /iface=(cref,nomixed_str_len_arg). + + # Our strategy is now to locate all libraries, but enter msmpifec into the LIB_NAMES array. + # Should this not be adequate it's a straightforward way for a user to change the LIB_NAMES array and + # have his library found. Still, this should not be necessary outside of exceptional cases, as reasoned. + if ("${LANG}" STREQUAL "Fortran") + set(MPI_MSMPI_CALLINGCONVS c) + if("${CMAKE_SIZEOF_VOID_P}" EQUAL 4) + list(APPEND MPI_MSMPI_CALLINGCONVS s) endif() - string(STRIP ${LIB} LIB) - # MPI_LIB is cached by find_library, but we don't want that. Clear it first. - set(MPI_LIB "MPI_LIB-NOTFOUND" CACHE FILEPATH "Cleared" FORCE) - find_library(MPI_LIB NAMES ${LIB} HINTS ${MPI_LINK_PATH}) - - if (MPI_LIB) - list(APPEND MPI_LIBRARIES_WORK ${MPI_LIB}) - elseif (NOT MPI_FIND_QUIETLY) - message(WARNING "Unable to find MPI library ${LIB}") + foreach(mpistrlenpos IN ITEMS e m) + foreach(mpicallingconv IN LISTS MPI_MSMPI_CALLINGCONVS) + find_library(MPI_msmpif${mpistrlenpos}${mpicallingconv}_LIBRARY + NAMES msmpif${mpistrlenpos}${mpicallingconv} + HINTS "${MPI_MSMPI_LIB_PATH}" + DOC "Location of the msmpi${mpistrlenpos}${mpicallingconv} library for Microsoft MPI") + mark_as_advanced(MPI_msmpif${mpistrlenpos}${mpicallingconv}_LIBRARY) + endforeach() + endforeach() + if(NOT MPI_${LANG}_LIB_NAMES) + set(MPI_${LANG}_LIB_NAMES "msmpi;msmpifec" CACHE STRING "MPI ${LANG} libraries to link against" FORCE) endif() - endforeach() - # Sanity check MPI_LIBRARIES to make sure there are enough libraries - list(LENGTH MPI_LIBRARIES_WORK MPI_NUMLIBS) - list(LENGTH MPI_LIBNAMES MPI_NUMLIBS_EXPECTED) - if (NOT MPI_NUMLIBS EQUAL MPI_NUMLIBS_EXPECTED) - set(MPI_LIBRARIES_WORK "MPI_${lang}_LIBRARIES-NOTFOUND") + # At this point we're *not* done. MSMPI requires an additional include file for Fortran giving the value + # of MPI_AINT. This file is called mpifptr.h located in the x64 and x86 subfolders, respectively. + find_path(MPI_mpifptr_INCLUDE_DIR + NAMES "mpifptr.h" + HINTS "${MPI_MSMPI_INC_PATH_EXTRA}" + DOC "Location of the mpifptr.h extra header for Microsoft MPI") + if(NOT MPI_${LANG}_ADDITIONAL_INCLUDE_VARS) + set(MPI_${LANG}_ADDITIONAL_INCLUDE_VARS "mpifptr" CACHE STRING "MPI ${LANG} additional include directory variables, given in the form MPI_<name>_INCLUDE_DIR." FORCE) + endif() + mark_as_advanced(MPI_${LANG}_ADDITIONAL_INCLUDE_VARS MPI_mpifptr_INCLUDE_DIR) + else() + if(NOT MPI_${LANG}_LIB_NAMES) + set(MPI_${LANG}_LIB_NAMES "msmpi" CACHE STRING "MPI ${LANG} libraries to link against" FORCE) + endif() endif() + mark_as_advanced(MPI_${LANG}_LIB_NAMES) + set(MPI_GUESS_FOUND TRUE) endif() + endif() - elseif(try_libs) - # If we didn't have an MPI compiler script to interrogate, attempt to find everything - # with plain old find functions. This is nasty because MPI implementations have LOTS of - # different library names, so this section isn't going to be very generic. We need to - # make sure it works for MS MPI, though, since there are no compiler wrappers for that. - find_path(MPI_HEADER_PATH mpi.h - HINTS ${_MPI_BASE_DIR} ${_MPI_PREFIX_PATH} - PATH_SUFFIXES include Inc) - set(MPI_INCLUDE_PATH_WORK ${MPI_HEADER_PATH}) - - # Decide between 32-bit and 64-bit libraries for Microsoft's MPI - if("${CMAKE_SIZEOF_VOID_P}" EQUAL 8) - set(MS_MPI_ARCH_DIR x64) - set(MS_MPI_ARCH_DIR2 amd64) - else() - set(MS_MPI_ARCH_DIR x86) - set(MS_MPI_ARCH_DIR2 i386) - endif() + # At this point there's not many MPIs that we could still consider. + # OpenMPI 1.6.x and below supported Windows, but these ship compiler wrappers that still work. + # The only other relevant MPI implementation without a wrapper is MPICH2, which had Windows support in 1.4.1p1 and older. + if(NOT MPI_GUESS_LIBRARY_NAME OR "${MPI_GUESS_LIBRARY_NAME}" STREQUAL "MPICH2") + set(MPI_MPICH_PREFIX_PATHS + "$ENV{ProgramW6432}/MPICH2/lib" + "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MPICH\\SMPD;binary]/../lib" + "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MPICH2;Path]/lib" + ) - set(MPI_LIB "MPI_LIB-NOTFOUND" CACHE FILEPATH "Cleared" FORCE) - find_library(MPI_LIB - NAMES mpi mpich mpich2 msmpi - HINTS ${_MPI_BASE_DIR} ${_MPI_PREFIX_PATH} - PATH_SUFFIXES lib lib/${MS_MPI_ARCH_DIR} Lib Lib/${MS_MPI_ARCH_DIR} Lib/${MS_MPI_ARCH_DIR2}) - set(MPI_LIBRARIES_WORK ${MPI_LIB}) - - # Right now, we only know about the extra libs for C++. - # We could add Fortran here (as there is usually libfmpich, etc.), but - # this really only has to work with MS MPI on Windows. - # Assume that other MPI's are covered by the compiler wrappers. - if (${lang} STREQUAL CXX) - set(MPI_LIB "MPI_LIB-NOTFOUND" CACHE FILEPATH "Cleared" FORCE) - find_library(MPI_LIB - NAMES mpi++ mpicxx cxx mpi_cxx - HINTS ${_MPI_BASE_DIR} ${_MPI_PREFIX_PATH} - PATH_SUFFIXES lib) - if (MPI_LIBRARIES_WORK AND MPI_LIB) - list(APPEND MPI_LIBRARIES_WORK ${MPI_LIB}) + # All of C, C++ and Fortran will need mpi.lib, so we'll look for this first + find_library(MPI_mpi_LIBRARY + NAMES mpi + HINTS ${MPI_MPICH_PREFIX_PATHS}) + mark_as_advanced(MPI_mpi_LIBRARY) + # If we found mpi.lib, we detect the rest of MPICH2 + if(MPI_mpi_LIBRARY) + set(MPI_MPICH_LIB_NAMES "mpi") + # If MPI-2 C++ bindings are requested, we need to locate cxx.lib as well. + # Otherwise, MPICH_SKIP_MPICXX will be defined and these bindings aren't needed. + if("${LANG}" STREQUAL "CXX" AND NOT MPI_CXX_SKIP_MPICXX) + find_library(MPI_cxx_LIBRARY + NAMES cxx + HINTS ${MPI_MPICH_PREFIX_PATHS}) + mark_as_advanced(MPI_cxx_LIBRARY) + list(APPEND MPI_MPICH_LIB_NAMES "cxx") + # For Fortran, MPICH2 provides three different libraries: + # fmpich2.lib which uses uppercase symbols and cdecl, + # fmpich2s.lib which uses uppercase symbols and stdcall (32-bit only), + # fmpich2g.lib which uses lowercase symbols with double underscores and cdecl. + # fmpich2s.lib would be useful for Compaq Visual Fortran, fmpich2g.lib has to be used with GNU g77 and is also + # provided in the form of an .a archive for MinGW and Cygwin. From our perspective, fmpich2.lib is the only one + # we need to try, and if it doesn't work with the given Fortran compiler we'd find out later on during validation + elseif("${LANG}" STREQUAL "Fortran") + find_library(MPI_fmpich2_LIBRARY + NAMES fmpich2 + HINTS ${MPI_MPICH_PREFIX_PATHS}) + find_library(MPI_fmpich2s_LIBRARY + NAMES fmpich2s + HINTS ${MPI_MPICH_PREFIX_PATHS}) + find_library(MPI_fmpich2g_LIBRARY + NAMES fmpich2g + HINTS ${MPI_MPICH_PREFIX_PATHS}) + mark_as_advanced(MPI_fmpich2_LIBRARY MPI_fmpich2s_LIBRARY MPI_fmpich2g_LIBRARY) + list(APPEND MPI_MPICH_LIB_NAMES "fmpich2") endif() - endif() - if (NOT MPI_LIBRARIES_WORK) - set(MPI_LIBRARIES_WORK "MPI_${lang}_LIBRARIES-NOTFOUND") + if(NOT MPI_${LANG}_LIB_NAMES) + set(MPI_${LANG}_LIB_NAMES "${MPI_MPICH_LIB_NAMES}" CACHE STRING "MPI ${LANG} libraries to link against" FORCE) + endif() + unset(MPI_MPICH_LIB_NAMES) + + if(NOT MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS) + # For MPICH2, the include folder would be in ../include relative to the library folder. + get_filename_component(MPI_MPICH_ROOT_DIR "${MPI_mpi_LIBRARY}" DIRECTORY) + get_filename_component(MPI_MPICH_ROOT_DIR "${MPI_MPICH_ROOT_DIR}" DIRECTORY) + if(IS_DIRECTORY "${MPI_MPICH_ROOT_DIR}/include") + set(MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS "${MPI_MPICH_ROOT_DIR}/include" CACHE STRING "MPI ${LANG} additional include directory variables, given in the form MPI_<name>_INCLUDE_DIR." FORCE) + endif() + unset(MPI_MPICH_ROOT_DIR) + endif() + set(MPI_GUESS_FOUND TRUE) endif() + unset(MPI_MPICH_PREFIX_PATHS) endif() + endif() + set(MPI_${LANG}_GUESS_FOUND "${MPI_GUESS_FOUND}" PARENT_SCOPE) +endfunction() - # If we found MPI, set up all of the appropriate cache entries - set(MPI_${lang}_COMPILE_FLAGS ${MPI_COMPILE_FLAGS_WORK} CACHE STRING "MPI ${lang} compilation flags" FORCE) - set(MPI_${lang}_INCLUDE_PATH ${MPI_INCLUDE_PATH_WORK} CACHE STRING "MPI ${lang} include path" FORCE) - set(MPI_${lang}_LINK_FLAGS ${MPI_LINK_FLAGS_WORK} CACHE STRING "MPI ${lang} linking flags" FORCE) - set(MPI_${lang}_LIBRARIES ${MPI_LIBRARIES_WORK} CACHE STRING "MPI ${lang} libraries to link against" FORCE) - mark_as_advanced(MPI_${lang}_COMPILE_FLAGS MPI_${lang}_INCLUDE_PATH MPI_${lang}_LINK_FLAGS MPI_${lang}_LIBRARIES) +function(_MPI_adjust_compile_definitions LANG) + if("${LANG}" STREQUAL "CXX") + # To disable the C++ bindings, we need to pass some definitions since the mpi.h header has to deal with both C and C++ + # bindings in MPI-2. + if(MPI_CXX_SKIP_MPICXX AND NOT MPI_${LANG}_COMPILE_DEFINITIONS MATCHES "SKIP_MPICXX") + # MPICH_SKIP_MPICXX is being used in MPICH and derivatives like MVAPICH or Intel MPI + # OMPI_SKIP_MPICXX is being used in Open MPI + # _MPICC_H is being used for IBM Platform MPI + list(APPEND MPI_${LANG}_COMPILE_DEFINITIONS "MPICH_SKIP_MPICXX" "OMPI_SKIP_MPICXX" "_MPICC_H") + set(MPI_${LANG}_COMPILE_DEFINITIONS "${MPI_${LANG}_COMPILE_DEFINITIONS}" CACHE STRING "MPI ${LANG} compilation definitions" FORCE) + endif() + endif() +endfunction() + +macro(_MPI_assemble_libraries LANG) + set(MPI_${LANG}_LIBRARIES "") + foreach(mpilib IN LISTS MPI_${LANG}_LIB_NAMES) + list(APPEND MPI_${LANG}_LIBRARIES ${MPI_${mpilib}_LIBRARY}) + endforeach() +endmacro() + +macro(_MPI_assemble_include_dirs LANG) + set(MPI_${LANG}_INCLUDE_DIRS "${MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS}") + if("${LANG}" MATCHES "(C|CXX)") + if(MPI_${LANG}_HEADER_DIR) + list(APPEND MPI_${LANG}_INCLUDE_DIRS "${MPI_${LANG}_HEADER_DIR}") + endif() + else() # Fortran + if(MPI_${LANG}_F77_HEADER_DIR) + list(APPEND MPI_${LANG}_INCLUDE_DIRS "${MPI_${LANG}_F77_HEADER_DIR}") + endif() + if(MPI_${LANG}_MODULE_DIR AND NOT "${MPI_${LANG}_MODULE_DIR}" IN_LIST MPI_${LANG}_INCLUDE_DIRS) + list(APPEND MPI_${LANG}_INCLUDE_DIRS "${MPI_${LANG}_MODULE_DIR}") + endif() + endif() + if(MPI_${LANG}_ADDITIONAL_INCLUDE_VARS) + foreach(mpiadditionalinclude IN LISTS MPI_${LANG}_ADDITIONAL_INCLUDE_VARS) + list(APPEND MPI_${LANG}_INCLUDE_DIRS "${MPI_${mpiadditionalinclude}_INCLUDE_DIR}") + endforeach() + endif() +endmacro() - # clear out our temporary lib/header detection variable here. - set(MPI_LIB "MPI_LIB-NOTFOUND" CACHE INTERNAL "Scratch variable for MPI lib detection" FORCE) - set(MPI_HEADER_PATH "MPI_HEADER_PATH-NOTFOUND" CACHE INTERNAL "Scratch variable for MPI header detection" FORCE) +function(_MPI_split_include_dirs LANG) + # Backwards compatibility: Search INCLUDE_PATH if given. + if(MPI_${LANG}_INCLUDE_PATH) + list(APPEND MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS "${MPI_${LANG}_INCLUDE_PATH}") endif() - # finally set a found variable for each MPI language - if (MPI_${lang}_INCLUDE_PATH AND MPI_${lang}_LIBRARIES) - set(MPI_${lang}_FOUND TRUE PARENT_SCOPE) - else() - set(MPI_${lang}_FOUND FALSE PARENT_SCOPE) + # We try to find the headers/modules among those paths (and system paths) + # For C/C++, we just need to have a look for mpi.h. + if("${LANG}" MATCHES "(C|CXX)") + find_path(MPI_${LANG}_HEADER_DIR "mpi.h" + HINTS ${MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS} + ) + mark_as_advanced(MPI_${LANG}_HEADER_DIR) + if(MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS) + list(REMOVE_ITEM MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS "${MPI_${LANG}_HEADER_DIR}") + endif() + # Fortran is more complicated here: An implementation could provide + # any of the Fortran 77/90/2008 APIs for MPI. For example, MSMPI + # only provides Fortran 77 and - if mpi.f90 is built - potentially + # a Fortran 90 module. + elseif("${LANG}" STREQUAL "Fortran") + find_path(MPI_${LANG}_F77_HEADER_DIR "mpif.h" + HINTS ${MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS} + ) + find_path(MPI_${LANG}_MODULE_DIR + NAMES "mpi.mod" "mpi_f08.mod" + HINTS ${MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS} + ) + if(MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS) + list(REMOVE_ITEM MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS + "${MPI_${LANG}_F77_HEADER_DIR}" + "${MPI_${LANG}_MODULE_DIR}" + ) + endif() + mark_as_advanced(MPI_${LANG}_F77_HEADER_DIR MPI_${LANG}_MODULE_DIR) endif() + set(MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS ${MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS} CACHE STRING "MPI ${LANG} additional include directories" FORCE) endfunction() +macro(_MPI_create_imported_target LANG) + if(NOT TARGET MPI::MPI_${LANG}) + add_library(MPI::MPI_${LANG} INTERFACE IMPORTED) + endif() + + set_property(TARGET MPI::MPI_${LANG} PROPERTY INTERFACE_COMPILE_OPTIONS "${MPI_${LANG}_COMPILE_OPTIONS}") + set_property(TARGET MPI::MPI_${LANG} PROPERTY INTERFACE_COMPILE_DEFINITIONS "${MPI_${LANG}_COMPILE_DEFINITIONS}") -# This function attempts to compile with the regular compiler, to see if MPI programs -# work with it. This is a last ditch attempt after we've tried interrogating mpicc and -# friends, and after we've tried to find generic libraries. Works on machines like -# Cray XE6, where the modules environment changes what MPI version cc, CC, and ftn use. -function(try_regular_compiler lang success) - set(scratch_directory ${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}) - if (${lang} STREQUAL Fortran) - set(test_file ${scratch_directory}/cmake_mpi_test.f90) - file(WRITE ${test_file} - "program hello\n" - "include 'mpif.h'\n" - "integer ierror\n" - "call MPI_INIT(ierror)\n" - "call MPI_FINALIZE(ierror)\n" - "end\n") + set_property(TARGET MPI::MPI_${LANG} PROPERTY INTERFACE_LINK_LIBRARIES "") + if(MPI_${LANG}_LINK_FLAGS) + set_property(TARGET MPI::MPI_${LANG} APPEND PROPERTY INTERFACE_LINK_LIBRARIES "${MPI_${LANG}_LINK_FLAGS}") + endif() + # If the compiler links MPI implicitly, no libraries will be found as they're contained within + # CMAKE_<LANG>_IMPLICIT_LINK_LIBRARIES already. + if(MPI_${LANG}_LIBRARIES) + set_property(TARGET MPI::MPI_${LANG} APPEND PROPERTY INTERFACE_LINK_LIBRARIES "${MPI_${LANG}_LIBRARIES}") + endif() + # Given the new design of FindMPI, INCLUDE_DIRS will always be located, even under implicit linking. + set_property(TARGET MPI::MPI_${LANG} PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${MPI_${LANG}_INCLUDE_DIRS}") +endmacro() + +function(_MPI_try_staged_settings LANG MPI_TEST_FILE_NAME MODE RUN_BINARY) + set(WORK_DIR "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/FindMPI") + set(SRC_DIR "${CMAKE_ROOT}/Modules/FindMPI") + set(BIN_FILE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/FindMPI/${MPI_TEST_FILE_NAME}_${LANG}.bin") + unset(MPI_TEST_COMPILE_DEFINITIONS) + if("${LANG}" STREQUAL "Fortran") + if("${MODE}" STREQUAL "F90_MODULE") + set(MPI_Fortran_INCLUDE_LINE "use mpi\n implicit none") + elseif("${MODE}" STREQUAL "F08_MODULE") + set(MPI_Fortran_INCLUDE_LINE "use mpi_f08\n implicit none") + else() # F77 header + set(MPI_Fortran_INCLUDE_LINE "implicit none\n include 'mpif.h'") + endif() + configure_file("${SRC_DIR}/${MPI_TEST_FILE_NAME}.f90.in" "${WORK_DIR}/${MPI_TEST_FILE_NAME}.f90" @ONLY) + set(MPI_TEST_SOURCE_FILE "${WORK_DIR}/${MPI_TEST_FILE_NAME}.f90") + elseif("${LANG}" STREQUAL "CXX") + configure_file("${SRC_DIR}/${MPI_TEST_FILE_NAME}.c" "${WORK_DIR}/${MPI_TEST_FILE_NAME}.cpp" COPYONLY) + set(MPI_TEST_SOURCE_FILE "${WORK_DIR}/${MPI_TEST_FILE_NAME}.cpp") + if("${MODE}" STREQUAL "TEST_MPICXX") + set(MPI_TEST_COMPILE_DEFINITIONS TEST_MPI_MPICXX) + endif() + else() # C + set(MPI_TEST_SOURCE_FILE "${SRC_DIR}/${MPI_TEST_FILE_NAME}.c") + endif() + if(RUN_BINARY) + try_run(MPI_RUN_RESULT_${LANG}_${MPI_TEST_FILE_NAME}_${MODE} MPI_RESULT_${LANG}_${MPI_TEST_FILE_NAME}_${MODE} + "${CMAKE_BINARY_DIR}" SOURCES "${MPI_TEST_SOURCE_FILE}" + COMPILE_DEFINITIONS ${MPI_TEST_COMPILE_DEFINITIONS} + LINK_LIBRARIES MPI::MPI_${LANG} + RUN_OUTPUT_VARIABLE MPI_RUN_OUTPUT_${LANG}_${MPI_TEST_FILE_NAME}_${MODE}) + set(MPI_RUN_OUTPUT_${LANG}_${MPI_TEST_FILE_NAME}_${MODE} "${MPI_RUN_OUTPUT_${LANG}_${MPI_TEST_FILE_NAME}_${MODE}}" PARENT_SCOPE) else() - if (${lang} STREQUAL CXX) - set(test_file ${scratch_directory}/cmake_mpi_test.cpp) - else() - set(test_file ${scratch_directory}/cmake_mpi_test.c) - endif() - file(WRITE ${test_file} - "#include <mpi.h>\n" - "int main(int argc, char **argv) {\n" - " MPI_Init(&argc, &argv);\n" - " MPI_Finalize();\n" - "}\n") - endif() - try_compile(compiler_has_mpi ${scratch_directory} ${test_file}) - if (compiler_has_mpi) - set(MPI_${lang}_NO_INTERROGATE ${CMAKE_${lang}_COMPILER} CACHE STRING "Whether to interrogate MPI ${lang} compiler" FORCE) - set(MPI_${lang}_COMPILER ${CMAKE_${lang}_COMPILER} CACHE STRING "MPI ${lang} compiler" FORCE) - set(MPI_${lang}_COMPILE_FLAGS "" CACHE STRING "MPI ${lang} compilation flags" FORCE) - set(MPI_${lang}_INCLUDE_PATH "" CACHE STRING "MPI ${lang} include path" FORCE) - set(MPI_${lang}_LINK_FLAGS "" CACHE STRING "MPI ${lang} linking flags" FORCE) - set(MPI_${lang}_LIBRARIES "" CACHE STRING "MPI ${lang} libraries to link against" FORCE) - endif() - set(${success} ${compiler_has_mpi} PARENT_SCOPE) - unset(compiler_has_mpi CACHE) + try_compile(MPI_RESULT_${LANG}_${MPI_TEST_FILE_NAME}_${MODE} + "${CMAKE_BINARY_DIR}" SOURCES "${MPI_TEST_SOURCE_FILE}" + COMPILE_DEFINITIONS ${MPI_TEST_COMPILE_DEFINITIONS} + LINK_LIBRARIES MPI::MPI_${LANG} + COPY_FILE "${BIN_FILE}") + endif() endfunction() -# End definitions, commence real work here. +macro(_MPI_check_lang_works LANG) + # For Fortran we may have by the MPI-3 standard an implementation that provides: + # - the mpi_f08 module + # - *both*, the mpi module and 'mpif.h' + # Since older MPI standards (MPI-1) did not define anything but 'mpif.h', we need to check all three individually. + if( NOT MPI_${LANG}_WORKS ) + if("${LANG}" STREQUAL "Fortran") + set(MPI_Fortran_INTEGER_LINE "(kind=MPI_INTEGER_KIND)") + _MPI_try_staged_settings(${LANG} test_mpi F77_HEADER FALSE) + _MPI_try_staged_settings(${LANG} test_mpi F90_MODULE FALSE) + _MPI_try_staged_settings(${LANG} test_mpi F08_MODULE FALSE) + + set(MPI_${LANG}_WORKS FALSE) + + foreach(mpimethod IN ITEMS F77_HEADER F08_MODULE F90_MODULE) + if(MPI_RESULT_${LANG}_test_mpi_${mpimethod}) + set(MPI_${LANG}_WORKS TRUE) + set(MPI_${LANG}_HAVE_${mpimethod} TRUE) + else() + set(MPI_${LANG}_HAVE_${mpimethod} FALSE) + endif() + endforeach() + # MPI-1 versions had no MPI_INTGER_KIND defined, so we need to try without it. + # However, MPI-1 also did not define the Fortran 90 and 08 modules, so we only try the F77 header. + unset(MPI_Fortran_INTEGER_LINE) + if(NOT MPI_${LANG}_WORKS) + _MPI_try_staged_settings(${LANG} test_mpi F77_HEADER_NOKIND FALSE) + if(MPI_RESULT_${LANG}_test_mpi_F77_HEADER_NOKIND) + set(MPI_${LANG}_WORKS TRUE) + set(MPI_${LANG}_HAVE_F77_HEADER TRUE) + endif() + endif() + else() + _MPI_try_staged_settings(${LANG} test_mpi normal FALSE) + # If 'test_mpi' built correctly, we've found valid MPI settings. There might not be MPI-2 C++ support, but there can't + # be MPI-2 C++ support without the C bindings being present, so checking for them is sufficient. + set(MPI_${LANG}_WORKS "${MPI_RESULT_${LANG}_test_mpi_normal}") + endif() + endif() +endmacro() + +# Some systems install various MPI implementations in separate folders in some MPI prefix +# This macro enumerates all such subfolders and adds them to the list of hints that will be searched. +macro(MPI_search_mpi_prefix_folder PREFIX_FOLDER) + if(EXISTS "${PREFIX_FOLDER}") + file(GLOB _MPI_folder_children RELATIVE "${PREFIX_FOLDER}" "${PREFIX_FOLDER}/*") + foreach(_MPI_folder_child IN LISTS _MPI_folder_children) + if(IS_DIRECTORY "${PREFIX_FOLDER}/${_MPI_folder_child}") + list(APPEND MPI_HINT_DIRS "${PREFIX_FOLDER}/${_MPI_folder_child}") + endif() + endforeach() + endif() +endmacro() + +set(MPI_HINT_DIRS ${MPI_HOME} $ENV{MPI_HOME} $ENV{I_MPI_ROOT}) +if("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Linux") + # SUSE Linux Enterprise Server stores its MPI implementations under /usr/lib64/mpi/gcc/<name> + # We enumerate the subfolders and append each as a prefix + MPI_search_mpi_prefix_folder("/usr/lib64/mpi/gcc") +elseif("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Windows") + # MSMPI stores its runtime in a special folder, this adds the possible locations to the hints. + list(APPEND MPI_HINT_DIRS $ENV{MSMPI_BIN} "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MPI;InstallRoot]") +elseif("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "FreeBSD") + # FreeBSD ships mpich under the normal system paths - but available openmpi implementations + # will be found in /usr/local/mpi/<name> + MPI_search_mpi_prefix_folder("/usr/local/mpi/") +endif() -# Most mpi distros have some form of mpiexec which gives us something we can reliably look for. -find_program(MPIEXEC - NAMES ${_MPI_EXEC_NAMES} - HINTS ${MPI_HOME} $ENV{MPI_HOME} - PATHS ${_MPI_PREFIX_PATH} - PATH_SUFFIXES bin +# Most MPI distributions have some form of mpiexec or mpirun which gives us something we can look for. +# The MPI standard does not mandate the existence of either, but instead only makes requirements if a distribution +# ships an mpiexec program (mpirun executables are not regulated by the standard). +find_program(MPIEXEC_EXECUTABLE + NAMES ${_MPIEXEC_NAMES} + PATH_SUFFIXES bin sbin + HINTS ${MPI_HINT_DIRS} DOC "Executable for running MPI programs.") # call get_filename_component twice to remove mpiexec and the directory it exists in (typically bin). # This gives us a fairly reliable base directory to search for /bin /lib and /include from. -get_filename_component(_MPI_BASE_DIR "${MPIEXEC}" PATH) +get_filename_component(_MPI_BASE_DIR "${MPIEXEC_EXECUTABLE}" PATH) get_filename_component(_MPI_BASE_DIR "${_MPI_BASE_DIR}" PATH) # According to the MPI standard, section 8.8 -n is a guaranteed, and the only guaranteed way to # launch an MPI process using mpiexec if such a program exists. -set(MPIEXEC_NUMPROC_FLAG "-n" CACHE STRING "Flag used by MPI to specify the number of processes for MPIEXEC; the next option will be the number of processes.") -set(MPIEXEC_PREFLAGS "" CACHE STRING "These flags will be directly before the executable that is being run by MPIEXEC.") -set(MPIEXEC_POSTFLAGS "" CACHE STRING "These flags will come after all flags given to MPIEXEC.") +set(MPIEXEC_NUMPROC_FLAG "-n" CACHE STRING "Flag used by MPI to specify the number of processes for mpiexec; the next option will be the number of processes.") +set(MPIEXEC_PREFLAGS "" CACHE STRING "These flags will be directly before the executable that is being run by mpiexec.") +set(MPIEXEC_POSTFLAGS "" CACHE STRING "These flags will be placed after all flags passed to mpiexec.") # Set the number of processes to the processor count and the previous default # of 2 if that couldn't be determined. @@ -566,111 +1043,387 @@ ProcessorCount(_MPIEXEC_NUMPROCS) if("${_MPIEXEC_NUMPROCS}" EQUAL "0") set(_MPIEXEC_NUMPROCS 2) endif() -set(MPIEXEC_MAX_NUMPROCS "${_MPIEXEC_NUMPROCS}" CACHE STRING "Maximum number of processors available to run MPI applications.") +set(MPIEXEC_MAX_NUMPROCS "${_MPIEXEC_NUMPROCS}" CACHE STRING "Maximum number of processors available to run MPI applications.") unset(_MPIEXEC_NUMPROCS) -mark_as_advanced(MPIEXEC MPIEXEC_NUMPROC_FLAG MPIEXEC_PREFLAGS MPIEXEC_POSTFLAGS MPIEXEC_MAX_NUMPROCS) - +mark_as_advanced(MPIEXEC_EXECUTABLE MPIEXEC_NUMPROC_FLAG MPIEXEC_PREFLAGS MPIEXEC_POSTFLAGS MPIEXEC_MAX_NUMPROCS) #============================================================================= # Backward compatibility input hacks. Propagate the FindMPI hints to C and # CXX if the respective new versions are not defined. Translate the old -# MPI_LIBRARY and MPI_EXTRA_LIBRARY to respective MPI_${lang}_LIBRARIES. +# MPI_LIBRARY and MPI_EXTRA_LIBRARY to respective MPI_${LANG}_LIBRARIES. # # Once we find the new variables, we translate them back into their old # equivalents below. -foreach (lang C CXX) +foreach (LANG IN ITEMS C CXX) # Old input variables. set(_MPI_OLD_INPUT_VARS COMPILER COMPILE_FLAGS INCLUDE_PATH LINK_FLAGS) # Set new vars based on their old equivalents, if the new versions are not already set. foreach (var ${_MPI_OLD_INPUT_VARS}) - if (NOT MPI_${lang}_${var} AND MPI_${var}) - set(MPI_${lang}_${var} "${MPI_${var}}") + if (NOT MPI_${LANG}_${var} AND MPI_${var}) + set(MPI_${LANG}_${var} "${MPI_${var}}") endif() endforeach() - # Special handling for MPI_LIBRARY and MPI_EXTRA_LIBRARY, which we nixed in the - # new FindMPI. These need to be merged into MPI_<lang>_LIBRARIES - if (NOT MPI_${lang}_LIBRARIES AND (MPI_LIBRARY OR MPI_EXTRA_LIBRARY)) - set(MPI_${lang}_LIBRARIES ${MPI_LIBRARY} ${MPI_EXTRA_LIBRARY}) + # Chop the old compile flags into options and definitions + if(MPI_${LANG}_COMPILE_FLAGS) + unset(MPI_${LANG}_COMPILE_OPTIONS) + unset(MPI_${LANG}_COMPILE_DEFINITIONS) + separate_arguments(MPI_SEPARATE_FLAGS NATIVE_COMMAND "${MPI_${LANG}_COMPILE_FLAGS}") + foreach(_MPI_FLAG IN LISTS MPI_SEPARATE_FLAGS) + if("${_MPI_FLAG}" MATCHES "^ *[-/D]([^ ]+)") + list(APPEND MPI_${LANG}_COMPILE_DEFINITIONS "${CMAKE_MATCH_1}") + else() + list(APPEND MPI_${LANG}_COMPILE_FLAGS "${_MPI_FLAG}") + endif() + endforeach() + unset(MPI_SEPARATE_FLAGS) + endif() + + # If a list of libraries was given, we'll split it into new-style cache variables + if(NOT MPI_${LANG}_LIB_NAMES) + foreach(_MPI_LIB IN LISTS MPI_${LANG}_LIBRARIES MPI_LIBRARY MPI_EXTRA_LIBRARY) + get_filename_component(_MPI_PLAIN_LIB_NAME "${_MPI_LIB}" NAME_WE) + get_filename_component(_MPI_LIB_NAME "${_MPI_LIB}" NAME) + get_filename_component(_MPI_LIB_DIR "${_MPI_LIB}" DIRECTORY) + list(APPEND MPI_PLAIN_LIB_NAMES_WORK "${_MPI_PLAIN_LIB_NAME}") + find_library(MPI_${_MPI_PLAIN_LIB_NAME}_LIBRARY + NAMES "${_MPI_LIB_NAME}" "lib${_MPI_LIB_NAME}" + HINTS ${_MPI_LIB_DIR} $ENV{MPI_LIB} + DOC "Location of the ${_MPI_PLAIN_LIB_NAME} library for MPI" + ) + mark_as_advanced(MPI_${_MPI_PLAIN_LIB_NAME}_LIBRARY) + endforeach() endif() endforeach() #============================================================================= +unset(MPI_VERSION) +unset(MPI_VERSION_MAJOR) +unset(MPI_VERSION_MINOR) + +unset(_MPI_MIN_VERSION) # This loop finds the compilers and sends them off for interrogation. -foreach (lang C CXX Fortran) - if (CMAKE_${lang}_COMPILER_WORKS) - # If the user supplies a compiler *name* instead of an absolute path, assume that we need to find THAT compiler. - if (MPI_${lang}_COMPILER) - if (NOT IS_ABSOLUTE "${MPI_${lang}_COMPILER}") - # Get rid of our default list of names and just search for the name the user wants. - set(_MPI_${lang}_COMPILER_NAMES ${MPI_${lang}_COMPILER}) - set(MPI_${lang}_COMPILER "MPI_${lang}_COMPILER-NOTFOUND" CACHE FILEPATH "Cleared" FORCE) - endif() - # If the user specifies a compiler, we don't want to try to search libraries either. - set(try_libs FALSE) +foreach(LANG IN ITEMS C CXX Fortran) + if(CMAKE_${LANG}_COMPILER_LOADED) + if(NOT MPI_FIND_COMPONENTS) + set(_MPI_FIND_${LANG} TRUE) + elseif( ${LANG} IN_LIST MPI_FIND_COMPONENTS) + set(_MPI_FIND_${LANG} TRUE) + elseif( ${LANG} STREQUAL CXX AND NOT MPI_CXX_SKIP_MPICXX AND MPICXX IN_LIST MPI_FIND_COMPONENTS ) + set(_MPI_FIND_${LANG} TRUE) else() - set(try_libs TRUE) + set(_MPI_FIND_${LANG} FALSE) endif() + else() + set(_MPI_FIND_${LANG} FALSE) + endif() + if(_MPI_FIND_${LANG}) + if( ${LANG} STREQUAL CXX AND NOT MPICXX IN_LIST MPI_FIND_COMPONENTS ) + set(MPI_CXX_SKIP_MPICXX FALSE CACHE BOOL "If true, the MPI-2 C++ bindings are disabled using definitions.") + mark_as_advanced(MPI_CXX_SKIP_MPICXX) + endif() + if(NOT (MPI_${LANG}_LIB_NAMES AND (MPI_${LANG}_INCLUDE_PATH OR MPI_${LANG}_INCLUDE_DIRS OR MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS))) + if(NOT MPI_${LANG}_COMPILER AND NOT MPI_ASSUME_NO_BUILTIN_MPI) + # Should the imported targets be empty, we effectively try whether the compiler supports MPI on its own, which is the case on e.g. + # Cray PrgEnv. + _MPI_create_imported_target(${LANG}) + _MPI_check_lang_works(${LANG}) + + # If the compiler can build MPI code on its own, it functions as an MPI compiler and we'll set the variable to point to it. + if(MPI_${LANG}_WORKS) + set(MPI_${LANG}_COMPILER "${CMAKE_${LANG}_COMPILER}" CACHE FILEPATH "MPI compiler for ${LANG}" FORCE) + endif() + endif() - find_program(MPI_${lang}_COMPILER - NAMES ${_MPI_${lang}_COMPILER_NAMES} - HINTS ${_MPI_BASE_DIR}/bin - PATHS ${_MPI_PREFIX_PATH} - ) - interrogate_mpi_compiler(${lang} ${try_libs}) - mark_as_advanced(MPI_${lang}_COMPILER) + # If the user specified a library name we assume they prefer that library over a wrapper. If not, they can disable skipping manually. + if(NOT DEFINED MPI_SKIP_COMPILER_WRAPPER AND MPI_GUESS_LIBRARY_NAME) + set(MPI_SKIP_COMPILER_WRAPPER TRUE) + endif() + if(NOT MPI_SKIP_COMPILER_WRAPPER) + if(MPI_${LANG}_COMPILER) + # If the user supplies a compiler *name* instead of an absolute path, assume that we need to find THAT compiler. + if (NOT IS_ABSOLUTE "${MPI_${LANG}_COMPILER}") + # Get rid of our default list of names and just search for the name the user wants. + set(_MPI_${LANG}_COMPILER_NAMES "${MPI_${LANG}_COMPILER}") + unset(MPI_${LANG}_COMPILER CACHE) + endif() + # If the user specifies a compiler, we don't want to try to search libraries either. + set(MPI_PINNED_COMPILER TRUE) + else() + set(MPI_PINNED_COMPILER FALSE) + endif() + + # If we have an MPI base directory, we'll try all compiler names in that one first. + # This should prevent mixing different MPI environments + if(_MPI_BASE_DIR) + find_program(MPI_${LANG}_COMPILER + NAMES ${_MPI_${LANG}_COMPILER_NAMES} + PATH_SUFFIXES bin sbin + HINTS ${_MPI_BASE_DIR} + NO_DEFAULT_PATH + DOC "MPI compiler for ${LANG}" + ) + endif() + + # If the base directory did not help (for example because the mpiexec isn't in the same directory as the compilers), + # we shall try searching in the default paths. + find_program(MPI_${LANG}_COMPILER + NAMES ${_MPI_${LANG}_COMPILER_NAMES} + PATH_SUFFIXES bin sbin + DOC "MPI compiler for ${LANG}" + ) + + if(MPI_${LANG}_COMPILER STREQUAL CMAKE_${LANG}_COMPILER) + set(MPI_SKIP_GUESSING TRUE) + elseif(MPI_${LANG}_COMPILER) + _MPI_interrogate_compiler(${LANG}) + else() + set(MPI_${LANG}_WRAPPER_FOUND FALSE) + endif() + else() + set(MPI_${LANG}_WRAPPER_FOUND FALSE) + set(MPI_PINNED_COMPILER FALSE) + endif() - # last ditch try -- if nothing works so far, just try running the regular compiler and - # see if we can create an MPI executable. - set(regular_compiler_worked 0) - if (NOT MPI_${lang}_LIBRARIES OR NOT MPI_${lang}_INCLUDE_PATH) - try_regular_compiler(${lang} regular_compiler_worked) + if(NOT MPI_${LANG}_WRAPPER_FOUND AND NOT MPI_PINNED_COMPILER) + # For C++, we may use the settings for C. Should a given compiler wrapper for C++ not exist, but one for C does, we copy over the + # settings for C. An MPI distribution that is in this situation would be IBM Platform MPI. + if("${LANG}" STREQUAL "CXX" AND MPI_C_WRAPPER_FOUND) + set(MPI_${LANG}_COMPILE_OPTIONS ${MPI_C_COMPILE_OPTIONS} CACHE STRING "MPI ${LANG} compilation options" ) + set(MPI_${LANG}_COMPILE_DEFINITIONS ${MPI_C_COMPILE_DEFINITIONS} CACHE STRING "MPI ${LANG} compilation definitions" ) + set(MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS ${MPI_C_INCLUDE_DIRS} CACHE STRING "MPI ${LANG} additional include directories") + set(MPI_${LANG}_LINK_FLAGS ${MPI_C_LINK_FLAGS} CACHE STRING "MPI ${LANG} linker flags" ) + set(MPI_${LANG}_LIB_NAMES ${MPI_C_LIB_NAMES} CACHE STRING "MPI ${LANG} libraries to link against" ) + set(MPI_${LANG}_WRAPPER_FOUND TRUE) + elseif(NOT MPI_SKIP_GUESSING) + _MPI_guess_settings(${LANG}) + endif() + endif() endif() - set(MPI_${lang}_FIND_QUIETLY ${MPI_FIND_QUIETLY}) - set(MPI_${lang}_FIND_REQUIRED ${MPI_FIND_REQUIRED}) - set(MPI_${lang}_FIND_VERSION ${MPI_FIND_VERSION}) - set(MPI_${lang}_FIND_VERSION_EXACT ${MPI_FIND_VERSION_EXACT}) + _MPI_split_include_dirs(${LANG}) + if(NOT MPI_${LANG}_COMPILER STREQUAL CMAKE_${LANG}_COMPILER) + _MPI_assemble_include_dirs(${LANG}) + _MPI_assemble_libraries(${LANG}) + endif() + _MPI_adjust_compile_definitions(${LANG}) + # We always create imported targets even if they're empty + _MPI_create_imported_target(${LANG}) - if (regular_compiler_worked) - find_package_handle_standard_args(MPI_${lang} DEFAULT_MSG MPI_${lang}_COMPILER) - else() - find_package_handle_standard_args(MPI_${lang} DEFAULT_MSG MPI_${lang}_LIBRARIES MPI_${lang}_INCLUDE_PATH) + if(NOT MPI_${LANG}_WORKS) + _MPI_check_lang_works(${LANG}) endif() - if(MPI_${lang}_FOUND) - if(NOT TARGET MPI::MPI_${lang}) - add_library(MPI::MPI_${lang} INTERFACE IMPORTED) + # Next, we'll initialize the MPI variables that have not been previously set. + set(MPI_${LANG}_COMPILE_OPTIONS "" CACHE STRING "MPI ${LANG} compilation flags" ) + set(MPI_${LANG}_COMPILE_DEFINITIONS "" CACHE STRING "MPI ${LANG} compilation definitions" ) + set(MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS "" CACHE STRING "MPI ${LANG} additional include directories") + set(MPI_${LANG}_LINK_FLAGS "" CACHE STRING "MPI ${LANG} linker flags" ) + set(MPI_${LANG}_LIB_NAMES "" CACHE STRING "MPI ${LANG} libraries to link against" ) + mark_as_advanced(MPI_${LANG}_COMPILE_OPTIONS MPI_${LANG}_COMPILE_DEFINITIONS MPI_${LANG}_LINK_FLAGS + MPI_${LANG}_LIB_NAMES MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS MPI_${LANG}_COMPILER) + + # If we've found MPI, then we'll perform additional analysis: Determine the MPI version, MPI library version, supported + # MPI APIs (i.e. MPI-2 C++ bindings). For Fortran we also need to find specific parameters if we're under MPI-3. + if(MPI_${LANG}_WORKS) + if("${LANG}" STREQUAL "CXX" AND NOT DEFINED MPI_MPICXX_FOUND) + if(NOT MPI_CXX_SKIP_MPICXX AND NOT MPI_CXX_VALIDATE_SKIP_MPICXX) + _MPI_try_staged_settings(${LANG} test_mpi MPICXX FALSE) + if(MPI_RESULT_${LANG}_test_mpi_MPICXX) + set(MPI_MPICXX_FOUND TRUE) + else() + set(MPI_MPICXX_FOUND FALSE) + endif() + else() + set(MPI_MPICXX_FOUND FALSE) + endif() endif() - if(MPI_${lang}_COMPILE_FLAGS) - separate_arguments(_MPI_${lang}_COMPILE_OPTIONS NATIVE_COMMAND "${MPI_${lang}_COMPILE_FLAGS}") - set_property(TARGET MPI::MPI_${lang} PROPERTY - INTERFACE_COMPILE_OPTIONS "${_MPI_${lang}_COMPILE_OPTIONS}") + + # At this point, we know the bindings present but not the MPI version or anything else. + if(NOT DEFINED MPI_${LANG}_VERSION) + unset(MPI_${LANG}_VERSION_MAJOR) + unset(MPI_${LANG}_VERSION_MINOR) endif() + set(MPI_BIN_FOLDER ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/FindMPI) + + # For Fortran, we'll want to use the most modern MPI binding to test capabilities other than the + # Fortran parameters, since those depend on the method of consumption. + # For C++, we can always use the C bindings, and should do so, since the C++ bindings do not exist in MPI-3 + # whereas the C bindings do, and the C++ bindings never offered any feature advantage over their C counterparts. + if("${LANG}" STREQUAL "Fortran") + if(MPI_${LANG}_HAVE_F08_MODULE) + set(MPI_${LANG}_HIGHEST_METHOD F08_MODULE) + elseif(MPI_${LANG}_HAVE_F90_MODULE) + set(MPI_${LANG}_HIGHEST_METHOD F90_MODULE) + else() + set(MPI_${LANG}_HIGHEST_METHOD F77_HEADER) + endif() + + # Another difference between C and Fortran is that we can't use the preprocessor to determine whether MPI_VERSION + # and MPI_SUBVERSION are provided. These defines did not exist in MPI 1.0 and 1.1 and therefore might not + # exist. For C/C++, test_mpi.c will handle the MPI_VERSION extraction, but for Fortran, we need mpiver.f90. + if(NOT DEFINED MPI_${LANG}_VERSION) + _MPI_try_staged_settings(${LANG} mpiver ${MPI_${LANG}_HIGHEST_METHOD} FALSE) + if(MPI_RESULT_${LANG}_mpiver_${MPI_${LANG}_HIGHEST_METHOD}) + file(STRINGS ${MPI_BIN_FOLDER}/mpiver_${LANG}.bin _MPI_VERSION_STRING LIMIT_COUNT 1 REGEX "INFO:MPI-VER") + if("${_MPI_VERSION_STRING}" MATCHES ".*INFO:MPI-VER\\[([0-9]+)\\.([0-9]+)\\].*") + set(MPI_${LANG}_VERSION_MAJOR "${CMAKE_MATCH_1}") + set(MPI_${LANG}_VERSION_MINOR "${CMAKE_MATCH_2}") + set(MPI_${LANG}_VERSION "${MPI_${LANG}_VERSION_MAJOR}.${MPI_${LANG}_VERSION_MINOR}") + endif() + endif() + endif() - unset(_MPI_${lang}_LINK_LINE) - if(MPI_${lang}_LINK_FLAGS) - list(APPEND _MPI_${lang}_LINK_LINE "${MPI_${lang}_LINK_FLAGS}") + # Finally, we want to find out which capabilities a given interface supports, compare the MPI-3 standard. + # This is determined by interface specific parameters MPI_SUBARRAYS_SUPPORTED and MPI_ASYNC_PROTECTS_NONBLOCKING + # and might vary between the different methods of consumption. + if(MPI_DETERMINE_Fortran_CAPABILITIES AND NOT MPI_Fortran_CAPABILITIES_DETERMINED) + foreach(mpimethod IN ITEMS F08_MODULE F90_MODULE F77_HEADER) + if(MPI_${LANG}_HAVE_${mpimethod}) + set(MPI_${LANG}_${mpimethod}_SUBARRAYS FALSE) + set(MPI_${LANG}_${mpimethod}_ASYNCPROT FALSE) + _MPI_try_staged_settings(${LANG} fortranparam_mpi ${mpimethod} TRUE) + if(MPI_RESULT_${LANG}_fortranparam_mpi_${mpimethod} AND + NOT "${MPI_RUN_RESULT_${LANG}_fortranparam_mpi_${mpimethod}}" STREQUAL "FAILED_TO_RUN") + if("${MPI_RUN_OUTPUT_${LANG}_fortranparam_mpi_${mpimethod}}" MATCHES + ".*INFO:SUBARRAYS\\[ *([TF]) *\\]-ASYNCPROT\\[ *([TF]) *\\].*") + if("${CMAKE_MATCH_1}" STREQUAL "T") + set(MPI_${LANG}_${mpimethod}_SUBARRAYS TRUE) + endif() + if("${CMAKE_MATCH_2}" STREQUAL "T") + set(MPI_${LANG}_${mpimethod}_ASYNCPROT TRUE) + endif() + endif() + endif() + endif() + endforeach() + set(MPI_Fortran_CAPABILITIES_DETERMINED TRUE) + endif() + else() + set(MPI_${LANG}_HIGHEST_METHOD normal) + + # By the MPI-2 standard, MPI_VERSION and MPI_SUBVERSION are valid for both C and C++ bindings. + if(NOT DEFINED MPI_${LANG}_VERSION) + file(STRINGS ${MPI_BIN_FOLDER}/test_mpi_${LANG}.bin _MPI_VERSION_STRING LIMIT_COUNT 1 REGEX "INFO:MPI-VER") + if("${_MPI_VERSION_STRING}" MATCHES ".*INFO:MPI-VER\\[([0-9]+)\\.([0-9]+)\\].*") + set(MPI_${LANG}_VERSION_MAJOR "${CMAKE_MATCH_1}") + set(MPI_${LANG}_VERSION_MINOR "${CMAKE_MATCH_2}") + set(MPI_${LANG}_VERSION "${MPI_${LANG}_VERSION_MAJOR}.${MPI_${LANG}_VERSION_MINOR}") + endif() + endif() endif() - list(APPEND _MPI_${lang}_LINK_LINE "${MPI_${lang}_LIBRARIES}") - set_property(TARGET MPI::MPI_${lang} PROPERTY - INTERFACE_LINK_LIBRARIES "${_MPI_${lang}_LINK_LINE}") - set_property(TARGET MPI::MPI_${lang} PROPERTY - INTERFACE_INCLUDE_DIRECTORIES "${MPI_${lang}_INCLUDE_PATH}") + unset(MPI_BIN_FOLDER) + + # At this point, we have dealt with determining the MPI version and parameters for each Fortran method available. + # The one remaining issue is to determine which MPI library is installed. + # Determining the version and vendor of the MPI library is only possible via MPI_Get_library_version() at runtime, + # and therefore we cannot do this while cross-compiling (a user may still define MPI_<lang>_LIBRARY_VERSION_STRING + # themselves and we'll attempt splitting it, which is equivalent to provide the try_run output). + # It's also worth noting that the installed version string can depend on the language, or on the system the binary + # runs on if MPI is not statically linked. + if(MPI_DETERMINE_LIBRARY_VERSION AND NOT MPI_${LANG}_LIBRARY_VERSION_STRING) + _MPI_try_staged_settings(${LANG} libver_mpi ${MPI_${LANG}_HIGHEST_METHOD} TRUE) + if(MPI_RESULT_${LANG}_libver_mpi_${MPI_${LANG}_HIGHEST_METHOD} AND + "${MPI_RUN_RESULT_${LANG}_libver_mpi_${MPI_${LANG}_HIGHEST_METHOD}}" EQUAL "0") + string(STRIP "${MPI_RUN_OUTPUT_${LANG}_libver_mpi_${MPI_${LANG}_HIGHEST_METHOD}}" + MPI_${LANG}_LIBRARY_VERSION_STRING) + else() + set(MPI_${LANG}_LIBRARY_VERSION_STRING "NOTFOUND") + endif() + endif() endif() + + set(MPI_${LANG}_FIND_QUIETLY ${MPI_FIND_QUIETLY}) + set(MPI_${LANG}_FIND_VERSION ${MPI_FIND_VERSION}) + set(MPI_${LANG}_FIND_VERSION_EXACT ${MPI_FIND_VERSION_EXACT}) + + unset(MPI_${LANG}_REQUIRED_VARS) + if (MPI_${LANG}_WRAPPER_FOUND OR MPI_${LANG}_GUESS_FOUND) + foreach(mpilibname IN LISTS MPI_${LANG}_LIB_NAMES) + list(APPEND MPI_${LANG}_REQUIRED_VARS "MPI_${mpilibname}_LIBRARY") + endforeach() + list(APPEND MPI_${LANG}_REQUIRED_VARS "MPI_${LANG}_LIB_NAMES") + if("${LANG}" STREQUAL "Fortran") + # For Fortran we only need one of the module or header directories to have *some* support for MPI. + if(NOT MPI_${LANG}_MODULE_DIR) + list(APPEND MPI_${LANG}_REQUIRED_VARS "MPI_${LANG}_F77_HEADER_DIR") + endif() + if(NOT MPI_${LANG}_F77_HEADER_DIR) + list(APPEND MPI_${LANG}_REQUIRED_VARS "MPI_${LANG}_MODULE_DIR") + endif() + else() + list(APPEND MPI_${LANG}_REQUIRED_VARS "MPI_${LANG}_HEADER_DIR") + endif() + if(MPI_${LANG}_ADDITIONAL_INCLUDE_VARS) + foreach(mpiincvar IN LISTS MPI_${LANG}_ADDITIONAL_INCLUDE_VARS) + list(APPEND MPI_${LANG}_REQUIRED_VARS "MPI_${mpiincvar}_INCLUDE_DIR") + endforeach() + endif() + # Append the works variable now. If the settings did not work, this will show up properly. + list(APPEND MPI_${LANG}_REQUIRED_VARS "MPI_${LANG}_WORKS") + else() + # If the compiler worked implicitly, use its path as output. + # Should the compiler variable be set, we also require it to work. + list(APPEND MPI_${LANG}_REQUIRED_VARS "MPI_${LANG}_COMPILER") + if(MPI_${LANG}_COMPILER) + list(APPEND MPI_${LANG}_REQUIRED_VARS "MPI_${LANG}_WORKS") + endif() + endif() + find_package_handle_standard_args(MPI_${LANG} REQUIRED_VARS ${MPI_${LANG}_REQUIRED_VARS} + VERSION_VAR MPI_${LANG}_VERSION) + + if(DEFINED MPI_${LANG}_VERSION) + if(NOT _MPI_MIN_VERSION OR _MPI_MIN_VERSION VERSION_GREATER MPI_${LANG}_VERSION) + set(_MPI_MIN_VERSION MPI_${LANG}_VERSION) + endif() + endif() + endif() +endforeach() + +unset(_MPI_REQ_VARS) +foreach(LANG IN ITEMS C CXX Fortran) + if((NOT MPI_FIND_COMPONENTS AND CMAKE_${LANG}_COMPILER_LOADED) OR LANG IN_LIST MPI_FIND_COMPONENTS) + list(APPEND _MPI_REQ_VARS "MPI_${LANG}_FOUND") endif() endforeach() +if(MPICXX IN_LIST MPI_FIND_COMPONENTS) + list(APPEND _MPI_REQ_VARS "MPI_MPICXX_FOUND") +endif() + +find_package_handle_standard_args(MPI + REQUIRED_VARS ${_MPI_REQ_VARS} + VERSION_VAR ${_MPI_MIN_VERSION} + HANDLE_COMPONENTS) #============================================================================= # More backward compatibility stuff -# -# Bare MPI sans ${lang} vars are set to CXX then C, depending on what was found. + +# For compatibility reasons, we also define MPIEXEC +set(MPIEXEC "${MPIEXEC_EXECUTABLE}") + +# Copy over MPI_<LANG>_INCLUDE_PATH from the assembled INCLUDE_DIRS. +foreach(LANG IN ITEMS C CXX Fortran) + if(MPI_${LANG}_FOUND) + set(MPI_${LANG}_INCLUDE_PATH "${MPI_${LANG}_INCLUDE_DIRS}") + unset(MPI_${LANG}_COMPILE_FLAGS) + if(MPI_${LANG}_COMPILE_OPTIONS) + set(MPI_${LANG}_COMPILE_FLAGS "${MPI_${LANG}_COMPILE_OPTIONS}") + endif() + if(MPI_${LANG}_COMPILE_DEFINITIONS) + foreach(_MPI_DEF IN LISTS MPI_${LANG}_COMPILE_DEFINITIONS) + string(APPEND MPI_${LANG}_COMPILE_FLAGS " -D${_MPI_DEF}") + endforeach() + endif() + endif() +endforeach() + +# Bare MPI sans ${LANG} vars are set to CXX then C, depending on what was found. # This mimics the behavior of the old language-oblivious FindMPI. -set(_MPI_OLD_VARS FOUND COMPILER INCLUDE_PATH COMPILE_FLAGS LINK_FLAGS LIBRARIES) +set(_MPI_OLD_VARS COMPILER INCLUDE_PATH COMPILE_FLAGS LINK_FLAGS LIBRARIES) if (MPI_CXX_FOUND) foreach (var ${_MPI_OLD_VARS}) set(MPI_${var} ${MPI_CXX_${var}}) @@ -679,28 +1432,26 @@ elseif (MPI_C_FOUND) foreach (var ${_MPI_OLD_VARS}) set(MPI_${var} ${MPI_C_${var}}) endforeach() -else() - # Note that we might still have found Fortran, but you'll need to use MPI_Fortran_FOUND - set(MPI_FOUND FALSE) endif() # Chop MPI_LIBRARIES into the old-style MPI_LIBRARY and MPI_EXTRA_LIBRARY, and set them in cache. if (MPI_LIBRARIES) list(GET MPI_LIBRARIES 0 MPI_LIBRARY_WORK) - set(MPI_LIBRARY ${MPI_LIBRARY_WORK} CACHE FILEPATH "MPI library to link against" FORCE) + set(MPI_LIBRARY "${MPI_LIBRARY_WORK}") + unset(MPI_LIBRARY_WORK) else() - set(MPI_LIBRARY "MPI_LIBRARY-NOTFOUND" CACHE FILEPATH "MPI library to link against" FORCE) + set(MPI_LIBRARY "MPI_LIBRARY-NOTFOUND") endif() list(LENGTH MPI_LIBRARIES MPI_NUMLIBS) if (MPI_NUMLIBS GREATER 1) - set(MPI_EXTRA_LIBRARY_WORK ${MPI_LIBRARIES}) + set(MPI_EXTRA_LIBRARY_WORK "${MPI_LIBRARIES}") list(REMOVE_AT MPI_EXTRA_LIBRARY_WORK 0) - set(MPI_EXTRA_LIBRARY ${MPI_EXTRA_LIBRARY_WORK} CACHE STRING "Extra MPI libraries to link against" FORCE) + set(MPI_EXTRA_LIBRARY "${MPI_EXTRA_LIBRARY_WORK}") + unset(MPI_EXTRA_LIBRARY_WORK) else() - set(MPI_EXTRA_LIBRARY "MPI_EXTRA_LIBRARY-NOTFOUND" CACHE STRING "Extra MPI libraries to link against" FORCE) + set(MPI_EXTRA_LIBRARY "MPI_EXTRA_LIBRARY-NOTFOUND") endif() -mark_as_advanced(MPI_LIBRARY MPI_EXTRA_LIBRARY) #============================================================================= # unset these vars to cleanup namespace @@ -708,5 +1459,7 @@ unset(_MPI_OLD_VARS) unset(_MPI_PREFIX_PATH) unset(_MPI_BASE_DIR) foreach (lang C CXX Fortran) - unset(_MPI_${lang}_COMPILER_NAMES) + unset(_MPI_${LANG}_COMPILER_NAMES) endforeach() + +cmake_policy(POP) diff --git a/Modules/FindMPI/fortranparam_mpi.f90.in b/Modules/FindMPI/fortranparam_mpi.f90.in new file mode 100644 index 0000000..30f912c --- /dev/null +++ b/Modules/FindMPI/fortranparam_mpi.f90.in @@ -0,0 +1,4 @@ + program mpi_ver + @MPI_Fortran_INCLUDE_LINE@ + print *, 'INFO:SUBARRAYS[', MPI_SUBARRAYS_SUPPORTED, ']-ASYNCPROT[', MPI_ASYNC_PROTECTS_NONBLOCKING, ']' + end program mpi_ver diff --git a/Modules/FindMPI/libver_mpi.c b/Modules/FindMPI/libver_mpi.c new file mode 100644 index 0000000..be9d19d --- /dev/null +++ b/Modules/FindMPI/libver_mpi.c @@ -0,0 +1,19 @@ +#include <mpi.h> + +#ifdef __cplusplus +#include <cstdio> +#else +#include <stdio.h> +#endif + +int main(int argc, char* argv[]) +{ + char mpilibver_str[MPI_MAX_LIBRARY_VERSION_STRING]; + int mpilibver_len; + MPI_Get_library_version(mpilibver_str, &mpilibver_len); +#ifdef __cplusplus + std::puts(mpilibver_str); +#else + puts(mpilibver_str); +#endif +} diff --git a/Modules/FindMPI/libver_mpi.f90.in b/Modules/FindMPI/libver_mpi.f90.in new file mode 100644 index 0000000..7938587 --- /dev/null +++ b/Modules/FindMPI/libver_mpi.f90.in @@ -0,0 +1,7 @@ + program mpi_ver + @MPI_Fortran_INCLUDE_LINE@ + character(len=MPI_MAX_LIBRARY_VERSION_STRING) :: mpilibver_str + integer(kind=MPI_INTEGER_KIND) :: ierror, reslen + call MPI_GET_LIBRARY_VERSION(mpilibver_str, reslen, ierror) + print *, mpilibver_str + end program mpi_ver diff --git a/Modules/FindMPI/mpiver.f90.in b/Modules/FindMPI/mpiver.f90.in new file mode 100644 index 0000000..a254523 --- /dev/null +++ b/Modules/FindMPI/mpiver.f90.in @@ -0,0 +1,10 @@ + program mpi_ver + @MPI_Fortran_INCLUDE_LINE@ + integer(kind=kind(MPI_VERSION)), parameter :: zero = ichar('0') + character, dimension(17), parameter :: mpiver_str =& + (/ 'I', 'N', 'F', 'O', ':', 'M', 'P', 'I', '-', 'V', 'E', 'R', '[', & + char(zero + MPI_VERSION), & + '.', & + char(zero + MPI_SUBVERSION), ']' /) + print *, mpiver_str + end program mpi_ver diff --git a/Modules/FindMPI/test_mpi.c b/Modules/FindMPI/test_mpi.c new file mode 100644 index 0000000..b8a308a --- /dev/null +++ b/Modules/FindMPI/test_mpi.c @@ -0,0 +1,37 @@ +#include <mpi.h> + +#ifdef __cplusplus +#include <cstdio> +#else +#include <stdio.h> +#endif + +#if defined(MPI_VERSION) && defined(MPI_SUBVERSION) +const char mpiver_str[] = { 'I', 'N', + 'F', 'O', + ':', 'M', + 'P', 'I', + '-', 'V', + 'E', 'R', + '[', ('0' + MPI_VERSION), + '.', ('0' + MPI_SUBVERSION), + ']', '\0' }; +#endif + +int main(int argc, char* argv[]) +{ +#if defined(MPI_VERSION) && defined(MPI_SUBVERSION) +#ifdef __cplusplus + std::puts(mpiver_str); +#else + puts(mpiver_str); +#endif +#endif +#ifdef TEST_MPI_MPICXX + MPI::MPI_Init(&argc, &argv); + MPI::MPI_Finalize(); +#else + MPI_Init(&argc, &argv); + MPI_Finalize(); +#endif +} diff --git a/Modules/FindMPI/test_mpi.f90.in b/Modules/FindMPI/test_mpi.f90.in new file mode 100644 index 0000000..4d43a04 --- /dev/null +++ b/Modules/FindMPI/test_mpi.f90.in @@ -0,0 +1,6 @@ + program hello + @MPI_Fortran_INCLUDE_LINE@ + integer@MPI_Fortran_INTEGER_LINE@ ierror + call MPI_INIT(ierror) + call MPI_FINALIZE(ierror) + end program diff --git a/Modules/FindMatlab.cmake b/Modules/FindMatlab.cmake index cd8246d..7493281 100644 --- a/Modules/FindMatlab.cmake +++ b/Modules/FindMatlab.cmake @@ -1134,7 +1134,14 @@ else() # testing if we are able to extract the needed information from the registry set(_matlab_versions_from_registry) - matlab_extract_all_installed_versions_from_registry(CMAKE_CL_64 _matlab_versions_from_registry) + + if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(_matlab_win64 ON) + else() + set(_matlab_win64 OFF) + endif() + + matlab_extract_all_installed_versions_from_registry(_matlab_win64 _matlab_versions_from_registry) # the returned list is empty, doing the search on all known versions if(NOT _matlab_versions_from_registry) diff --git a/Modules/FindOpenACC.cmake b/Modules/FindOpenACC.cmake new file mode 100644 index 0000000..775cc18 --- /dev/null +++ b/Modules/FindOpenACC.cmake @@ -0,0 +1,252 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +#[=======================================================================[.rst: +FindOpenACC +----------- + +Detect OpenACC support by the compiler. + +This module can be used to detect OpenACC support in a compiler. +If the compiler supports OpenACC, the flags required to compile with +OpenACC support are returned in variables for the different languages. +Currently, only PGI, GNU and Cray compilers are supported. + +Variables +^^^^^^^^^ + +This module will set the following variables per language in your +project, where ``<lang>`` is one of C, CXX, or Fortran: + +``OpenACC_<lang>_FOUND`` + Variable indicating if OpenACC support for ``<lang>`` was detected. +``OpenACC_<lang>_FLAGS`` + OpenACC compiler flags for ``<lang>``, separated by spaces. + +The module will also try to provide the OpenACC version variables: + +``OpenACC_<lang>_SPEC_DATE`` + Date of the OpenACC specification implemented by the ``<lang>`` compiler. +``OpenACC_<lang>_VERSION_MAJOR`` + Major version of OpenACC implemented by the ``<lang>`` compiler. +``OpenACC_<lang>_VERSION_MINOR`` + Minor version of OpenACC implemented by the ``<lang>`` compiler. +``OpenACC_<lang>_VERSION`` + OpenACC version implemented by the ``<lang>`` compiler. + +The specification date is formatted as given in the OpenACC standard: +``yyyymm`` where ``yyyy`` and ``mm`` represents the year and month of +the OpenACC specification implemented by the ``<lang>`` compiler. + +Input Variables +^^^^^^^^^^^^^^^ + +``OpenACC_ACCEL_TARGET=<target>`` +If set, will the correct target accelerator flag set to the <target> will +be returned with OpenACC_<lang>_FLAGS. +#]=======================================================================] + +set(OpenACC_C_CXX_TEST_SOURCE +" +int main(){ +#ifndef _OPENACC + breaks_on_purpose +#endif +} +" +) +set(OpenACC_Fortran_TEST_SOURCE +" +program test +#ifndef _OPENACC + breaks_on_purpose +#endif +endprogram test +" +) +set(OpenACC_C_CXX_CHECK_VERSION_SOURCE +" +#include <stdio.h> +const char accver_str[] = { 'I', 'N', 'F', 'O', ':', 'O', 'p', 'e', 'n', 'A', + 'C', 'C', '-', 'd', 'a', 't', 'e', '[', + ('0' + ((_OPENACC/100000)%10)), + ('0' + ((_OPENACC/10000)%10)), + ('0' + ((_OPENACC/1000)%10)), + ('0' + ((_OPENACC/100)%10)), + ('0' + ((_OPENACC/10)%10)), + ('0' + ((_OPENACC/1)%10)), + ']', '\\0' }; +int main() +{ + puts(accver_str); +} +") +set(OpenACC_Fortran_CHECK_VERSION_SOURCE +" + program acc_ver + implicit none + integer, parameter :: zero = ichar('0') + character, dimension(25), parameter :: accver_str =& + (/ 'I', 'N', 'F', 'O', ':', 'O', 'p', 'e', 'n', 'A', 'C', 'C', '-',& + 'd', 'a', 't', 'e', '[',& + char(zero + mod(_OPENACC/100000, 10)),& + char(zero + mod(_OPENACC/10000, 10)),& + char(zero + mod(_OPENACC/1000, 10)),& + char(zero + mod(_OPENACC/100, 10)),& + char(zero + mod(_OPENACC/10, 10)),& + char(zero + mod(_OPENACC/1, 10)), ']' /) + print *, accver_str + end program acc_ver +" +) + + +function(_OPENACC_WRITE_SOURCE_FILE LANG SRC_FILE_CONTENT_VAR SRC_FILE_NAME SRC_FILE_FULLPATH) + set(WORK_DIR ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/FindOpenACC) + if("${LANG}" STREQUAL "C") + set(SRC_FILE "${WORK_DIR}/${SRC_FILE_NAME}.c") + file(WRITE "${SRC_FILE}" "${OpenACC_C_CXX_${SRC_FILE_CONTENT_VAR}}") + elseif("${LANG}" STREQUAL "CXX") + set(SRC_FILE "${WORK_DIR}/${SRC_FILE_NAME}.cpp") + file(WRITE "${SRC_FILE}" "${OpenACC_C_CXX_${SRC_FILE_CONTENT_VAR}}") + elseif("${LANG}" STREQUAL "Fortran") + set(SRC_FILE "${WORK_DIR}/${SRC_FILE_NAME}.F90") + file(WRITE "${SRC_FILE}_in" "${OpenACC_Fortran_${SRC_FILE_CONTENT_VAR}}") + configure_file("${SRC_FILE}_in" "${SRC_FILE}" @ONLY) + endif() + set(${SRC_FILE_FULLPATH} "${SRC_FILE}" PARENT_SCOPE) +endfunction() + + +function(_OPENACC_GET_FLAGS_CANDIDATE LANG FLAG_VAR) + set(ACC_FLAG_PGI "-acc") + set(ACC_FLAG_GNU "-fopenacc") + set(ACC_FLAG_Cray "-h acc") + + if(DEFINED ACC_FLAG_${CMAKE_${LANG}_COMPILER_ID}) + set("${FLAG_VAR}" "${ACC_FLAG_${CMAKE_${LANG}_COMPILER_ID}}" PARENT_SCOPE) + else() + # Fall back to a few common flags. + set("${FLAG_VAR}" ${ACC_FLAG_GNU} ${ACC_FLAG_PGI}) + endif() + +endfunction() + + +function(_OPENACC_GET_ACCEL_TARGET_FLAG LANG TARGET FLAG_VAR) + # Find target accelerator flags. + set(ACC_TARGET_FLAG_PGI "-ta") + if(DEFINED ACC_TARGET_FLAG_${CMAKE_${LANG}_COMPILER_ID}) + set("${FLAG_VAR}" "${ACC_TARGET_FLAG_${CMAKE_${LANG}_COMPILER_ID}}=${TARGET}" PARENT_SCOPE) + endif() +endfunction() + + +function(_OPENACC_GET_VERBOSE_FLAG LANG FLAG_VAR) + # Find compiler's verbose flag for OpenACC. + set(ACC_VERBOSE_FLAG_PGI "-Minfo=accel") + if(DEFINED ACC_VERBOSE_FLAG_${CMAKE_${LANG}_COMPILER_ID}) + set("${FLAG_VAR}" "${ACC_VERBOSE_FLAG_${CMAKE_${LANG}_COMPILER_ID}}" PARENT_SCOPE) + endif() +endfunction() + + +function(_OPENACC_GET_FLAGS LANG FLAG_VAR) + set(FLAG_CANDIDATES "") + _OPENACC_GET_FLAGS_CANDIDATE("${LANG}" FLAG_CANDIDATES) + _OPENACC_WRITE_SOURCE_FILE("${LANG}" "TEST_SOURCE" OpenACCTryFlag _OPENACC_TEST_SRC) + + foreach(FLAG IN LISTS FLAG_CANDIDATES) + try_compile(OpenACC_FLAG_TEST_RESULT ${CMAKE_BINARY_DIR} ${_OPENACC_TEST_SRC} + CMAKE_FLAGS "-DCOMPILE_DEFINITIONS:STRING=${FLAG}" + OUTPUT_VARIABLE OpenACC_TRY_COMPILE_OUTPUT + ) + if(OpenACC_FLAG_TEST_RESULT) + set("${FLAG_VAR}" "${FLAG}") + if(DEFINED OpenACC_ACCEL_TARGET) + _OPENACC_GET_ACCEL_TARGET_FLAG("${LANG}" "${OpenACC_ACCEL_TARGET}" TARGET_FLAG) + string(APPEND "${FLAG_VAR}" " ${TARGET_FLAG}") + endif() + + if(CMAKE_VERBOSE_MAKEFILE) + # -Minfo=accel prints out OpenACC's messages on optimizations. + _OPENACC_GET_VERBOSE_FLAG("${LANG}" OpenACC_VERBOSE_FLAG) + string(APPEND "${FLAG_VAR}" " ${OpenACC_VERBOSE_FLAG}") + endif() + set("${FLAG_VAR}" "${${FLAG_VAR}}" PARENT_SCOPE) + break() + endif() + endforeach() + +endfunction() + + +function(_OPENACC_GET_SPEC_DATE LANG SPEC_DATE) + _OPENACC_WRITE_SOURCE_FILE("${LANG}" "CHECK_VERSION_SOURCE" OpenACCCheckVersion _OPENACC_TEST_SRC) + + set(BIN_FILE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/FindOpenACC/accver_${LANG}.bin") + try_compile(OpenACC_SPECTEST_${LANG} "${CMAKE_BINARY_DIR}" "${_OPENACC_TEST_SRC}" + CMAKE_FLAGS "-DCOMPILE_DEFINITIONS:STRING=${OpenACC_${LANG}_FLAGS}" + COPY_FILE ${BIN_FILE} + OUTPUT_VARIABLE OUTPUT) + + if(${OpenACC_SPECTEST_${LANG}}) + file(STRINGS ${BIN_FILE} specstr LIMIT_COUNT 1 REGEX "INFO:OpenACC-date") + set(regex_spec_date ".*INFO:OpenACC-date\\[0*([^]]*)\\].*") + if("${specstr}" MATCHES "${regex_spec_date}") + set(${SPEC_DATE} "${CMAKE_MATCH_1}" PARENT_SCOPE) + endif() + endif() +endfunction() + + +macro(_OPENACC_SET_VERSION_BY_SPEC_DATE LANG) + set(OpenACC_SPEC_DATE_MAP + # Combined versions, 2.5 onwards + "201510=2.5" + # 2013 08 is the corrected version. + "201308=2.0" + "201306=2.0" + "201111=1.0" + ) + + string(REGEX MATCHALL "${OpenACC_${LANG}_SPEC_DATE}=([0-9]+)\\.([0-9]+)" _version_match "${OpenACC_SPEC_DATE_MAP}") + if(NOT _version_match STREQUAL "") + set(OpenACC_${LANG}_VERSION_MAJOR ${CMAKE_MATCH_1}) + set(OpenACC_${LANG}_VERSION_MINOR ${CMAKE_MATCH_2}) + set(OpenACC_${LANG}_VERSION "${OpenACC_${LANG}_VERSION_MAJOR}.${OpenACC_${LANG}_VERSION_MINOR}") + else() + unset(OpenACC_${LANG}_VERSION_MAJOR) + unset(OpenACC_${LANG}_VERSION_MINOR) + unset(OpenACC_${LANG}_VERSION) + endif() + unset(_version_match) + unset(OpenACC_SPEC_DATE_MAP) +endmacro() + + +include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) +foreach (LANG IN ITEMS C CXX Fortran) + if(CMAKE_${LANG}_COMPILER_LOADED) + set(OpenACC_${LANG}_FIND_QUIETLY ${OpenACC_FIND_QUIETLY}) + set(OpenACC_${LANG}_FIND_REQUIRED ${OpenACC_FIND_REQUIRED}) + set(OpenACC_${LANG}_FIND_VERSION ${OpenACC_FIND_VERSION}) + set(OpenACC_${LANG}_FIND_VERSION_EXACT ${OpenACC_FIND_VERSION_EXACT}) + + if(NOT DEFINED OpenACC_${LANG}_FLAGS) + _OPENACC_GET_FLAGS("${LANG}" OpenACC_${LANG}_FLAGS) + endif() + _OPENACC_GET_SPEC_DATE("${LANG}" OpenACC_${LANG}_SPEC_DATE) + _OPENACC_SET_VERSION_BY_SPEC_DATE("${LANG}") + + find_package_handle_standard_args(OpenACC_${LANG} + REQUIRED_VARS OpenACC_${LANG}_FLAGS + VERSION_VAR OpenACC_${LANG}_VERSION + ) + endif() +endforeach() + +unset(OpenACC_C_CXX_TEST_SOURCE) +unset(OpenACC_Fortran_TEST_SOURCE) +unset(OpenACC_C_CXX_CHECK_VERSION_SOURCE) +unset(OpenACC_Fortran_CHECK_VERSION_SOURCE) diff --git a/Modules/FindOpenGL.cmake b/Modules/FindOpenGL.cmake index af83fb7..59bee41 100644 --- a/Modules/FindOpenGL.cmake +++ b/Modules/FindOpenGL.cmake @@ -7,15 +7,28 @@ # # FindModule for OpenGL and GLU. # +# Optional COMPONENTS +# ^^^^^^^^^^^^^^^^^^^ +# +# This module respects several optional COMPONENTS: ``EGL``, ``GLX``, and +# ``OpenGL``. There are corresponding import targets for each of these flags. +# # IMPORTED Targets # ^^^^^^^^^^^^^^^^ # # This module defines the :prop_tgt:`IMPORTED` targets: # # ``OpenGL::GL`` -# Defined if the system has OpenGL. +# Defined to the platform-specific OpenGL libraries if the system has OpenGL. +# ``OpenGL::OpenGL`` +# Defined to libOpenGL if the system is GLVND-based. +# ``OpenGL::GL`` # ``OpenGL::GLU`` # Defined if the system has GLU. +# ``OpenGL::GLX`` +# Defined if the system has GLX. +# ``OpenGL::EGL`` +# Defined if the system has EGL. # # Result Variables # ^^^^^^^^^^^^^^^^ @@ -23,40 +36,87 @@ # This module sets the following variables: # # ``OPENGL_FOUND`` -# True, if the system has OpenGL. +# True, if the system has OpenGL and all components are found. # ``OPENGL_XMESA_FOUND`` # True, if the system has XMESA. # ``OPENGL_GLU_FOUND`` # True, if the system has GLU. +# ``OpenGL_OpenGL_FOUND`` +# True, if the system has an OpenGL library. +# ``OpenGL_GLX_FOUND`` +# True, if the system has GLX. +# ``OpenGL_EGL_FOUND`` +# True, if the system has EGL. # ``OPENGL_INCLUDE_DIR`` # Path to the OpenGL include directory. +# ``OPENGL_EGL_INCLUDE_DIRS`` +# Path to the EGL include directory. # ``OPENGL_LIBRARIES`` -# Paths to the OpenGL and GLU libraries. +# Paths to the OpenGL library, windowing system libraries, and GLU libraries. +# On Linux, this assumes glX and is never correct for EGL-based targets. +# Clients are encouraged to use the ``OpenGL::*`` import targets instead. # -# If you want to use just GL you can use these values: +# Cache variables +# ^^^^^^^^^^^^^^^ # -# ``OPENGL_gl_LIBRARY`` -# Path to the OpenGL library. +# The following cache variables may also be set: +# +# ``OPENGL_egl_LIBRARY`` +# Path to the EGL library. # ``OPENGL_glu_LIBRARY`` # Path to the GLU library. +# ``OPENGL_glx_LIBRARY`` +# Path to the GLVND 'GLX' library. +# ``OPENGL_opengl_LIBRARY`` +# Path to the GLVND 'OpenGL' library +# ``OPENGL_gl_LIBRARY`` +# Path to the OpenGL library. New code should prefer the ``OpenGL::*`` import +# targets. +# +# Linux-specific +# ^^^^^^^^^^^^^^ # -# OSX Specific -# ^^^^^^^^^^^^ +# Some Linux systems utilize GLVND as a new ABI for OpenGL. GLVND separates +# context libraries from OpenGL itself; OpenGL lives in "libOpenGL", and +# contexts are defined in "libGLX" or "libEGL". GLVND is currently the only way +# to get OpenGL 3+ functionality via EGL in a manner portable across vendors. # -# On OSX default to using the framework version of OpenGL. People will -# have to change the cache values of OPENGL_glu_LIBRARY and +# On Linux systems FindOpenGL defaults to using GLVND if available. Users can +# utilize GLVND explicitly with targets ``OpenGL::OpenGL``, ``OpenGL::GLX``, and +# ``OpenGL::EGL``. Additionally, when GLVND is available the ``OpenGL::GL`` +# target is equivalent to ``OpenGL::OpenGL OpenGL::GLX``. When the system is +# not GLVND-based, ``OpenGL::GL`` expands to libGL as it has historically done. +# Thus, for non-EGL-based Linux targets, the ``OpenGL::GL`` target is most +# portable. +# +# For EGL targets the client must rely on GLVND support on the user's system. +# Linking should use the ``OpenGL::OpenGL OpenGL::EGL`` targets. Using GLES* +# libraries is theoretically possible in place of ``OpenGL::OpenGL``, but this +# module does not currently support that; contributions welcome. +# +# ``OPENGL_egl_LIBRARY`` and ``OPENGL_EGL_INCLUDE_DIRS`` are defined in the case of +# GLVND. For non-GLVND Linux and other systems these are left undefined. +# +# macOS-Specific +# ^^^^^^^^^^^^^^ +# +# On OSX FindOpenGL defaults to using the framework version of OpenGL. People +# will have to change the cache values of OPENGL_glu_LIBRARY and # OPENGL_gl_LIBRARY to use OpenGL with X11 on OSX. - set(_OpenGL_REQUIRED_VARS OPENGL_gl_LIBRARY) -if (CYGWIN) +# Provide OPENGL_USE_<C> variables for each component. +foreach(component ${OpenGL_FIND_COMPONENTS}) + string(TOUPPER ${component} _COMPONENT) + set(OPENGL_USE_${_COMPONENT} 1) +endforeach() +if (CYGWIN) find_path(OPENGL_INCLUDE_DIR GL/gl.h ) list(APPEND _OpenGL_REQUIRED_VARS OPENGL_INCLUDE_DIR) find_library(OPENGL_gl_LIBRARY opengl32 ) - find_library(OPENGL_glu_LIBRARY glu32 ) elseif (WIN32) @@ -70,7 +130,6 @@ elseif (WIN32) endif() elseif (APPLE) - # The OpenGL.framework provides both gl and glu find_library(OPENGL_gl_LIBRARY OpenGL DOC "OpenGL library for OS X") find_library(OPENGL_glu_LIBRARY OpenGL DOC @@ -104,15 +163,14 @@ else() # fail since the compiler finds the Mesa headers but NVidia's library. # Make sure the NVIDIA directory comes BEFORE the others. # - Atanas Georgiev <atanas@cs.columbia.edu> - find_path(OPENGL_INCLUDE_DIR GL/gl.h /usr/share/doc/NVIDIA_GLX-1.0/include /usr/openwin/share/include /opt/graphics/OpenGL/include /usr/X11R6/include ${_OPENGL_INCLUDE_PATH} ) - list(APPEND _OpenGL_REQUIRED_VARS OPENGL_INCLUDE_DIR) - + find_path(OPENGL_GLX_INCLUDE_DIR GL/glx.h ${_OPENGL_INCLUDE_PATH}) + find_path(OPENGL_EGL_INCLUDE_DIR EGL/egl.h ${_OPENGL_INCLUDE_PATH}) find_path(OPENGL_xmesa_INCLUDE_DIR GL/xmesa.h /usr/share/doc/NVIDIA_GLX-1.0/include /usr/openwin/share/include @@ -126,6 +184,90 @@ else() /usr/shlib /usr/X11R6/lib ${_OPENGL_LIB_PATH} ) + # Search for the GLVND libraries. We do this regardless of COMPONENTS; we'll + # take into account the COMPONENTS logic later. + find_library(OPENGL_opengl_LIBRARY + NAMES OpenGL + PATHS /usr/X11R6/lib + ${_OPENGL_LIB_PATH} + ) + + find_library(OPENGL_glx_LIBRARY + NAMES GLX + PATHS /usr/X11R6/lib + ${_OPENGL_LIB_PATH} + ) + + find_library(OPENGL_egl_LIBRARY + NAMES EGL + PATHS ${_OPENGL_LIB_PATH} + ) + + find_library(OPENGL_glu_LIBRARY + NAMES GLU MesaGLU + PATHS ${OPENGL_gl_LIBRARY} + /opt/graphics/OpenGL/lib + /usr/openwin/lib + /usr/shlib /usr/X11R6/lib + ) + + # FPHSA cannot handle "this OR that is required", so we conditionally set what + # it must look for. First clear any previous config we might have done: + set(_OpenGL_REQUIRED_VARS) + + # now we append the libraries as appropriate. The complicated logic + # basically comes down to "use libOpenGL when we can, and add in specific + # context mechanisms when requested, or we need them to preserve the previous + # default where glx is always available." + if((NOT OPENGL_USE_EGL AND + NOT OPENGL_opengl_LIBRARY AND + OPENGL_glx_LIBRARY AND + NOT OPENGL_gl_LIBRARY) OR + (NOT OPENGL_USE_EGL AND + NOT OPENGL_glx_LIBRARY AND + NOT OPENGL_gl_LIBRARY) OR + (NOT OPENGL_USE_EGL AND + OPENGL_opengl_LIBRARY AND + OPENGL_glx_LIBRARY) OR + ( OPENGL_USE_EGL)) + list(APPEND _OpenGL_REQUIRED_VARS OPENGL_opengl_LIBRARY) + endif() + + # GLVND GLX library. Preferred when available. + if((NOT OPENGL_USE_OPENGL AND + NOT OPENGL_USE_GLX AND + NOT OPENGL_USE_EGL AND + NOT OPENGL_glx_LIBRARY AND + NOT OPENGL_gl_LIBRARY) OR + ( OPENGL_USE_GLX AND + NOT OPENGL_USE_EGL AND + NOT OPENGL_glx_LIBRARY AND + NOT OPENGL_gl_LIBRARY) OR + (NOT OPENGL_USE_EGL AND + OPENGL_opengl_LIBRARY AND + OPENGL_glx_LIBRARY) OR + (OPENGL_USE_GLX AND OPENGL_USE_EGL)) + list(APPEND _OpenGL_REQUIRED_VARS OPENGL_glx_LIBRARY) + endif() + + # GLVND EGL library. + if(OPENGL_USE_EGL) + list(APPEND _OpenGL_REQUIRED_VARS OPENGL_egl_LIBRARY) + endif() + + # Old-style "libGL" library: used as a fallback when GLVND isn't available. + if((NOT OPENGL_USE_EGL AND + NOT OPENGL_opengl_LIBRARY AND + OPENGL_glx_LIBRARY AND + OPENGL_gl_LIBRARY) OR + (NOT OPENGL_USE_EGL AND + NOT OPENGL_glx_LIBRARY AND + OPENGL_gl_LIBRARY)) + list(APPEND _OpenGL_REQUIRED_VARS OPENGL_gl_LIBRARY) + endif() + + # We always need the 'gl.h' include dir. + list(APPEND _OpenGL_REQUIRED_VARS OPENGL_INCLUDE_DIR) unset(_OPENGL_INCLUDE_PATH) unset(_OPENGL_LIB_PATH) @@ -137,42 +279,99 @@ else() /usr/openwin/lib /usr/shlib /usr/X11R6/lib ) - endif () -if(OPENGL_gl_LIBRARY) +if(OPENGL_xmesa_INCLUDE_DIR) + set( OPENGL_XMESA_FOUND "YES" ) +else() + set( OPENGL_XMESA_FOUND "NO" ) +endif() - if(OPENGL_xmesa_INCLUDE_DIR) - set( OPENGL_XMESA_FOUND "YES" ) - else() - set( OPENGL_XMESA_FOUND "NO" ) - endif() +if(OPENGL_glu_LIBRARY) + set( OPENGL_GLU_FOUND "YES" ) +else() + set( OPENGL_GLU_FOUND "NO" ) +endif() - set( OPENGL_LIBRARIES ${OPENGL_gl_LIBRARY} ${OPENGL_LIBRARIES}) - if(OPENGL_glu_LIBRARY) - set( OPENGL_GLU_FOUND "YES" ) - if(NOT "${OPENGL_glu_LIBRARY}" STREQUAL "${OPENGL_gl_LIBRARY}") - set( OPENGL_LIBRARIES ${OPENGL_glu_LIBRARY} ${OPENGL_LIBRARIES} ) - endif() - else() - set( OPENGL_GLU_FOUND "NO" ) - endif() +# OpenGL_OpenGL_FOUND is a bit unique in that it is okay if /either/ libOpenGL +# or libGL is found. +# Using libGL with libEGL is never okay, though; we handle that case later. +if(NOT OPENGL_opengl_LIBRARY AND NOT OPENGL_gl_LIBRARY) + set(OpenGL_OpenGL_FOUND FALSE) +else() + set(OpenGL_OpenGL_FOUND TRUE) +endif() - # This deprecated setting is for backward compatibility with CMake1.4 - set (OPENGL_LIBRARY ${OPENGL_LIBRARIES}) +if(OPENGL_glx_LIBRARY AND OPENGL_GLX_INCLUDE_DIR) + set(OpenGL_GLX_FOUND TRUE) +else() + set(OpenGL_GLX_FOUND FALSE) +endif() +if(OPENGL_egl_LIBRARY AND OPENGL_EGL_INCLUDE_DIR) + set(OpenGL_EGL_FOUND TRUE) +else() + set(OpenGL_EGL_FOUND FALSE) endif() -# This deprecated setting is for backward compatibility with CMake1.4 -set(OPENGL_INCLUDE_PATH ${OPENGL_INCLUDE_DIR}) +# User-visible names should be plural. +if(OPENGL_EGL_INCLUDE_DIR) + set(OPENGL_EGL_INCLUDE_DIRS ${OPENGL_EGL_INCLUDE_DIR}) +endif() include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) -FIND_PACKAGE_HANDLE_STANDARD_ARGS(OpenGL REQUIRED_VARS ${_OpenGL_REQUIRED_VARS}) +FIND_PACKAGE_HANDLE_STANDARD_ARGS(OpenGL REQUIRED_VARS ${_OpenGL_REQUIRED_VARS} + HANDLE_COMPONENTS) unset(_OpenGL_REQUIRED_VARS) # OpenGL:: targets if(OPENGL_FOUND) - if(NOT TARGET OpenGL::GL) + # ::OpenGL is a GLVND library, and thus Linux-only: we don't bother checking + # for a framework version of this library. + if(OPENGL_opengl_LIBRARY AND NOT TARGET OpenGL::OpenGL) + if(IS_ABSOLUTE "${OPENGL_opengl_LIBRARY}") + add_library(OpenGL::OpenGL UNKNOWN IMPORTED) + set_target_properties(OpenGL::OpenGL PROPERTIES IMPORTED_LOCATION + "${OPENGL_opengl_LIBRARY}") + else() + add_library(OpenGL::OpenGL INTERFACE IMPORTED) + set_target_properties(OpenGL::OpenGL PROPERTIES IMPORTED_LIBNAME + "${OPENGL_opengl_LIBRARY}") + endif() + set_target_properties(OpenGL::OpenGL PROPERTIES INTERFACE_INCLUDE_DIRECTORIES + "${OPENGL_INCLUDE_DIR}") + endif() + + # ::GLX is a GLVND library, and thus Linux-only: we don't bother checking + # for a framework version of this library. + if(OpenGL_GLX_FOUND AND NOT TARGET OpenGL::GLX) + if(IS_ABSOLUTE "${OPENGL_glx_LIBRARY}") + add_library(OpenGL::GLX UNKNOWN IMPORTED) + set_target_properties(OpenGL::GLX PROPERTIES IMPORTED_LOCATION + "${OPENGL_glx_LIBRARY}") + else() + add_library(OpenGL::GLX INTERFACE IMPORTED) + set_target_properties(OpenGL::GLX PROPERTIES IMPORTED_LIBNAME + "${OPENGL_glx_LIBRARY}") + endif() + set_target_properties(OpenGL::GLX PROPERTIES INTERFACE_LINK_LIBRARIES + OpenGL::OpenGL) + set_target_properties(OpenGL::GLX PROPERTIES INTERFACE_INCLUDE_DIRECTORIES + "${OPENGL_GLX_INCLUDE_DIR}") + endif() + + if(TARGET OpenGL::OpenGL AND TARGET OpenGL::GLX AND NOT TARGET OpenGL::GL) + # if GLVND with GLX is available, make ::GL a synonym for 'OpenGL::OpenGL + # OpenGL::GLX'. + add_library(OpenGL::GL INTERFACE IMPORTED) + set_target_properties(OpenGL::GL PROPERTIES INTERFACE_LINK_LIBRARIES + OpenGL::OpenGL) + set_property(TARGET OpenGL::GL APPEND PROPERTY INTERFACE_LINK_LIBRARIES + OpenGL::GLX) + set_target_properties(OpenGL::GL PROPERTIES INTERFACE_INCLUDE_DIRECTORIES + "${OPENGL_INCLUDE_DIR}") + + elseif(NOT TARGET OpenGL::GL) if(IS_ABSOLUTE "${OPENGL_gl_LIBRARY}") add_library(OpenGL::GL UNKNOWN IMPORTED) if(OPENGL_gl_LIBRARY MATCHES "/([^/]+)\\.framework$") @@ -195,6 +394,28 @@ if(OPENGL_FOUND) INTERFACE_INCLUDE_DIRECTORIES "${OPENGL_INCLUDE_DIR}") endif() + # ::EGL is a GLVND library, and thus Linux-only: we don't bother checking + # for a framework version of this library. + # Note we test for OpenGL::OpenGL as a target. When this module is updated to + # support GLES, we would additionally want to check for the hypothetical GLES + # target and enable EGL if either ::GLES or ::OpenGL is created. + if(TARGET OpenGL::OpenGL AND OpenGL_EGL_FOUND AND NOT TARGET OpenGL::EGL) + if(IS_ABSOLUTE "${OPENGL_egl_LIBRARY}") + add_library(OpenGL::EGL UNKNOWN IMPORTED) + set_target_properties(OpenGL::EGL PROPERTIES IMPORTED_LOCATION + "${OPENGL_egl_LIBRARY}") + else() + add_library(OpenGL::EGL INTERFACE IMPORTED) + set_target_properties(OpenGL::EGL PROPERTIES IMPORTED_LIBNAME + "${OPENGL_egl_LIBRARY}") + endif() + set_target_properties(OpenGL::EGL PROPERTIES INTERFACE_LINK_LIBRARIES + OpenGL::OpenGL) + # Note that EGL's include directory is different from OpenGL/GLX's! + set_target_properties(OpenGL::EGL PROPERTIES INTERFACE_INCLUDE_DIRECTORIES + "${OPENGL_EGL_INCLUDE_DIR}") + endif() + if(OPENGL_GLU_FOUND AND NOT TARGET OpenGL::GLU) if(IS_ABSOLUTE "${OPENGL_glu_LIBRARY}") add_library(OpenGL::GLU UNKNOWN IMPORTED) @@ -217,11 +438,31 @@ if(OPENGL_FOUND) set_target_properties(OpenGL::GLU PROPERTIES INTERFACE_LINK_LIBRARIES OpenGL::GL) endif() + + # OPENGL_LIBRARIES mirrors OpenGL::GL's logic ... + set(OPENGL_LIBRARIES ${OPENGL_gl_LIBRARY}) + if(TARGET OpenGL::GLX AND TARGET OpenGL::OpenGL) + set(OPENGL_LIBRARIES ${OPENGL_opengl_LIBRARY} ${OPENGL_glx_LIBRARY}) + endif() + # ... and also includes GLU, if available. + if(TARGET OpenGL::GLU) + list(APPEND OPENGL_LIBRARIES ${OPENGL_glu_LIBRARY}) + endif() endif() +# This deprecated setting is for backward compatibility with CMake1.4 +set(OPENGL_LIBRARY ${OPENGL_LIBRARIES}) +# This deprecated setting is for backward compatibility with CMake1.4 +set(OPENGL_INCLUDE_PATH ${OPENGL_INCLUDE_DIR}) + mark_as_advanced( OPENGL_INCLUDE_DIR OPENGL_xmesa_INCLUDE_DIR + OPENGL_egl_LIBRARY OPENGL_glu_LIBRARY + OPENGL_glx_LIBRARY OPENGL_gl_LIBRARY + OPENGL_opengl_LIBRARY + OPENGL_EGL_INCLUDE_DIR + OPENGL_GLX_INCLUDE_DIR ) diff --git a/Modules/FindOpenMP.cmake b/Modules/FindOpenMP.cmake index 1093be0..595b0b3 100644 --- a/Modules/FindOpenMP.cmake +++ b/Modules/FindOpenMP.cmake @@ -16,6 +16,19 @@ # Variables # ^^^^^^^^^ # +# The module exposes the components ``C``, ``CXX``, and ``Fortran``. +# Each of these controls the various languages to search OpenMP support for. +# +# Depending on the enabled components the following variables will be set: +# +# ``OpenMP_FOUND`` +# Variable indicating that OpenMP flags for all requested languages have been found. +# If no components are specified, this is true if OpenMP settings for all enabled languages +# were detected. +# ``OpenMP_VERSION`` +# Minimal version of the OpenMP standard detected among the requested languages, +# or all enabled languages if no components were specified. +# # This module will set the following variables per language in your # project, where ``<lang>`` is one of C, CXX, or Fortran: # @@ -60,18 +73,9 @@ # The specification date is formatted as given in the OpenMP standard: # ``yyyymm`` where ``yyyy`` and ``mm`` represents the year and month of # the OpenMP specification implemented by the ``<lang>`` compiler. -# -# Backward Compatibility -# ^^^^^^^^^^^^^^^^^^^^^^ -# -# For backward compatibility with older versions of FindOpenMP, these -# variables are set, but deprecated:: -# -# OpenMP_FOUND -# -# In new projects, please use the ``OpenMP_<lang>_XXX`` equivalents. cmake_policy(PUSH) +cmake_policy(SET CMP0054 NEW) # if() quoted variables not dereferenced cmake_policy(SET CMP0057 NEW) # if IN_LIST function(_OPENMP_FLAG_CANDIDATES LANG) @@ -95,10 +99,11 @@ function(_OPENMP_FLAG_CANDIDATES LANG) set(OMP_FLAG_NAG "-openmp") set(OMP_FLAG_Absoft "-openmp") set(OMP_FLAG_PGI "-mp") + set(OMP_FLAG_Flang "-fopenmp") set(OMP_FLAG_SunPro "-xopenmp") set(OMP_FLAG_XL "-qsmp=omp") - # Cray compiles with OpenMP automatically - set(OMP_FLAG_Cray " ") + # Cray compiler activate OpenMP with -h omp, which is enabled by default. + set(OMP_FLAG_Cray " " "-h omp") # If we know the correct flags, use those if(DEFINED OMP_FLAG_${CMAKE_${LANG}_COMPILER_ID}) @@ -285,6 +290,8 @@ endfunction() macro(_OPENMP_SET_VERSION_BY_SPEC_DATE LANG) set(OpenMP_SPEC_DATE_MAP + # Preview versions + "201611=5.0" # OpenMP 5.0 preview 1 # Combined versions, 2.5 onwards "201511=4.5" "201307=4.0" @@ -372,9 +379,15 @@ if(CMAKE_Fortran_COMPILER_LOADED) endif() endif() -set(OPENMP_FOUND TRUE) +if(NOT OpenMP_FIND_COMPONENTS) + set(OpenMP_FINDLIST C CXX Fortran) +else() + set(OpenMP_FINDLIST ${OpenMP_FIND_COMPONENTS}) +endif() -foreach(LANG IN ITEMS C CXX Fortran) +unset(_OpenMP_MIN_VERSION) + +foreach(LANG IN LISTS OpenMP_FINDLIST) if(CMAKE_${LANG}_COMPILER_LOADED) if (NOT OpenMP_${LANG}_SPEC_DATE) _OPENMP_GET_SPEC_DATE("${LANG}" OpenMP_${LANG}_SPEC_DATE_INTERNAL) @@ -405,6 +418,11 @@ foreach(LANG IN ITEMS C CXX Fortran) ) if(OpenMP_${LANG}_FOUND) + if(DEFINED OpenMP_${LANG}_VERSION) + if(NOT _OpenMP_MIN_VERSION OR _OpenMP_MIN_VERSION VERSION_GREATER OpenMP_${LANG}_VERSION) + set(_OpenMP_MIN_VERSION OpenMP_${LANG}_VERSION) + endif() + endif() set(OpenMP_${LANG}_LIBRARIES "") foreach(_OPENMP_IMPLICIT_LIB IN LISTS OpenMP_${LANG}_LIB_NAMES) list(APPEND OpenMP_${LANG}_LIBRARIES "${OpenMP_${_OPENMP_IMPLICIT_LIB}_LIBRARY}") @@ -423,12 +441,24 @@ foreach(LANG IN ITEMS C CXX Fortran) set_property(TARGET OpenMP::OpenMP_${LANG} PROPERTY INTERFACE_LINK_LIBRARIES "${OpenMP_${LANG}_LIBRARIES}") endif() - else() - set(OPENMP_FOUND FALSE) endif() endif() endforeach() +unset(_OpenMP_REQ_VARS) +foreach(LANG IN ITEMS C CXX Fortran) + if((NOT OpenMP_FIND_COMPONENTS AND CMAKE_${LANG}_COMPILER_LOADED) OR LANG IN_LIST OpenMP_FIND_COMPONENTS) + list(APPEND _OpenMP_REQ_VARS "OpenMP_${LANG}_FOUND") + endif() +endforeach() + +find_package_handle_standard_args(OpenMP + REQUIRED_VARS ${_OpenMP_REQ_VARS} + VERSION_VAR ${_OpenMP_MIN_VERSION} + HANDLE_COMPONENTS) + +set(OPENMP_FOUND ${OpenMP_FOUND}) + if(CMAKE_Fortran_COMPILER_LOADED AND OpenMP_Fortran_FOUND) if(NOT DEFINED OpenMP_Fortran_HAVE_OMPLIB_MODULE) set(OpenMP_Fortran_HAVE_OMPLIB_MODULE FALSE CACHE BOOL INTERNAL "") diff --git a/Modules/FindOpenSSL.cmake b/Modules/FindOpenSSL.cmake index f32eb50..0187e0d 100644 --- a/Modules/FindOpenSSL.cmake +++ b/Modules/FindOpenSSL.cmake @@ -149,6 +149,7 @@ if(WIN32 AND NOT CYGWIN) libcryptod libeay32${_OPENSSL_MSVC_RT_MODE}d libeay32d + cryptod NAMES_PER_DIR ${_OPENSSL_ROOT_HINTS_AND_PATHS} PATH_SUFFIXES @@ -176,6 +177,7 @@ if(WIN32 AND NOT CYGWIN) libssld ssleay32${_OPENSSL_MSVC_RT_MODE}d ssleay32d + ssld NAMES_PER_DIR ${_OPENSSL_ROOT_HINTS_AND_PATHS} PATH_SUFFIXES diff --git a/Modules/FindPackageHandleStandardArgs.cmake b/Modules/FindPackageHandleStandardArgs.cmake index b851a90..67f6bd6 100644 --- a/Modules/FindPackageHandleStandardArgs.cmake +++ b/Modules/FindPackageHandleStandardArgs.cmake @@ -175,11 +175,12 @@ endmacro() function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG) -# set up the arguments for CMAKE_PARSE_ARGUMENTS and check whether we are in -# new extended or in the "old" mode: +# Set up the arguments for `cmake_parse_arguments`. set(options CONFIG_MODE HANDLE_COMPONENTS) set(oneValueArgs FAIL_MESSAGE VERSION_VAR FOUND_VAR) set(multiValueArgs REQUIRED_VARS) + +# Check whether we are in 'simple' or 'extended' mode: set(_KEYWORDS_FOR_EXTENDED_MODE ${options} ${oneValueArgs} ${multiValueArgs} ) list(FIND _KEYWORDS_FOR_EXTENDED_MODE "${_FIRST_ARG}" INDEX) @@ -188,8 +189,7 @@ function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG) set(FPHSA_REQUIRED_VARS ${ARGN}) set(FPHSA_VERSION_VAR) else() - - CMAKE_PARSE_ARGUMENTS(FPHSA "${options}" "${oneValueArgs}" "${multiValueArgs}" ${_FIRST_ARG} ${ARGN}) + cmake_parse_arguments(FPHSA "${options}" "${oneValueArgs}" "${multiValueArgs}" ${_FIRST_ARG} ${ARGN}) if(FPHSA_UNPARSED_ARGUMENTS) message(FATAL_ERROR "Unknown keywords given to FIND_PACKAGE_HANDLE_STANDARD_ARGS(): \"${FPHSA_UNPARSED_ARGUMENTS}\"") @@ -198,6 +198,18 @@ function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG) if(NOT FPHSA_FAIL_MESSAGE) set(FPHSA_FAIL_MESSAGE "DEFAULT_MSG") endif() + + # In config-mode, we rely on the variable <package>_CONFIG, which is set by find_package() + # when it successfully found the config-file, including version checking: + if(FPHSA_CONFIG_MODE) + list(INSERT FPHSA_REQUIRED_VARS 0 ${_NAME}_CONFIG) + list(REMOVE_DUPLICATES FPHSA_REQUIRED_VARS) + set(FPHSA_VERSION_VAR ${_NAME}_VERSION) + endif() + + if(NOT FPHSA_REQUIRED_VARS) + message(FATAL_ERROR "No REQUIRED_VARS specified for FIND_PACKAGE_HANDLE_STANDARD_ARGS()") + endif() endif() # now that we collected all arguments, process them @@ -206,18 +218,6 @@ function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG) set(FPHSA_FAIL_MESSAGE "Could NOT find ${_NAME}") endif() - # In config-mode, we rely on the variable <package>_CONFIG, which is set by find_package() - # when it successfully found the config-file, including version checking: - if(FPHSA_CONFIG_MODE) - list(INSERT FPHSA_REQUIRED_VARS 0 ${_NAME}_CONFIG) - list(REMOVE_DUPLICATES FPHSA_REQUIRED_VARS) - set(FPHSA_VERSION_VAR ${_NAME}_VERSION) - endif() - - if(NOT FPHSA_REQUIRED_VARS) - message(FATAL_ERROR "No REQUIRED_VARS specified for FIND_PACKAGE_HANDLE_STANDARD_ARGS()") - endif() - list(GET FPHSA_REQUIRED_VARS 0 _FIRST_REQUIRED_VAR) string(TOUPPER ${_NAME} _NAME_UPPER) @@ -289,15 +289,15 @@ function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG) # version handling: set(VERSION_MSG "") set(VERSION_OK TRUE) - set(VERSION ${${FPHSA_VERSION_VAR}}) # check with DEFINED here as the requested or found version may be "0" if (DEFINED ${_NAME}_FIND_VERSION) if(DEFINED ${FPHSA_VERSION_VAR}) + set(_FOUND_VERSION ${${FPHSA_VERSION_VAR}}) if(${_NAME}_FIND_VERSION_EXACT) # exact version required # count the dots in the version string - string(REGEX REPLACE "[^.]" "" _VERSION_DOTS "${VERSION}") + string(REGEX REPLACE "[^.]" "" _VERSION_DOTS "${_FOUND_VERSION}") # add one dot because there is one dot more than there are components string(LENGTH "${_VERSION_DOTS}." _VERSION_DOTS) if (_VERSION_DOTS GREATER ${_NAME}_FIND_VERSION_COUNT) @@ -312,31 +312,31 @@ function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG) else () set(_VERSION_REGEX "[^.]*\\.[^.]*\\.[^.]*\\.[^.]*") endif () - string(REGEX REPLACE "^(${_VERSION_REGEX})\\..*" "\\1" _VERSION_HEAD "${VERSION}") + string(REGEX REPLACE "^(${_VERSION_REGEX})\\..*" "\\1" _VERSION_HEAD "${_FOUND_VERSION}") unset(_VERSION_REGEX) if (NOT ${_NAME}_FIND_VERSION VERSION_EQUAL _VERSION_HEAD) - set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"") + set(VERSION_MSG "Found unsuitable version \"${_FOUND_VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"") set(VERSION_OK FALSE) else () - set(VERSION_MSG "(found suitable exact version \"${VERSION}\")") + set(VERSION_MSG "(found suitable exact version \"${_FOUND_VERSION}\")") endif () unset(_VERSION_HEAD) else () - if (NOT ${_NAME}_FIND_VERSION VERSION_EQUAL VERSION) - set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"") + if (NOT ${_NAME}_FIND_VERSION VERSION_EQUAL _FOUND_VERSION) + set(VERSION_MSG "Found unsuitable version \"${_FOUND_VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"") set(VERSION_OK FALSE) else () - set(VERSION_MSG "(found suitable exact version \"${VERSION}\")") + set(VERSION_MSG "(found suitable exact version \"${_FOUND_VERSION}\")") endif () endif () unset(_VERSION_DOTS) else() # minimum version specified: - if (${_NAME}_FIND_VERSION VERSION_GREATER VERSION) - set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is at least \"${${_NAME}_FIND_VERSION}\"") + if (${_NAME}_FIND_VERSION VERSION_GREATER _FOUND_VERSION) + set(VERSION_MSG "Found unsuitable version \"${_FOUND_VERSION}\", but required is at least \"${${_NAME}_FIND_VERSION}\"") set(VERSION_OK FALSE) else () - set(VERSION_MSG "(found suitable version \"${VERSION}\", minimum required is \"${${_NAME}_FIND_VERSION}\")") + set(VERSION_MSG "(found suitable version \"${_FOUND_VERSION}\", minimum required is \"${${_NAME}_FIND_VERSION}\")") endif () endif() @@ -351,13 +351,14 @@ function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG) endif() else () - if(VERSION) - set(VERSION_MSG "(found version \"${VERSION}\")") + # Check with DEFINED as the found version may be 0. + if(DEFINED ${FPHSA_VERSION_VAR}) + set(VERSION_MSG "(found version \"${${FPHSA_VERSION_VAR}}\")") endif() endif () if(VERSION_OK) - string(APPEND DETAILS "[v${VERSION}(${${_NAME}_FIND_VERSION})]") + string(APPEND DETAILS "[v${${FPHSA_VERSION_VAR}}(${${_NAME}_FIND_VERSION})]") else() set(${_NAME}_FOUND FALSE) endif() diff --git a/Modules/FindPatch.cmake b/Modules/FindPatch.cmake new file mode 100644 index 0000000..3ebcae9 --- /dev/null +++ b/Modules/FindPatch.cmake @@ -0,0 +1,68 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +#.rst: +# FindPatch +# --------- +# +# The module defines the following variables: +# +# ``Patch_EXECUTABLE`` +# Path to patch command-line executable. +# ``Patch_FOUND`` +# True if the patch command-line executable was found. +# +# The following :prop_tgt:`IMPORTED` targets are also defined: +# +# ``Patch::patch`` +# The command-line executable. +# +# Example usage: +# +# .. code-block:: cmake +# +# find_package(Patch) +# if(Patch_FOUND) +# message("Patch found: ${Patch_EXECUTABLE}") +# endif() + +set(_doc "Patch command line executable") +set(_patch_path ) + +if(CMAKE_HOST_WIN32) + set(_patch_path + "$ENV{LOCALAPPDATA}/Programs/Git/bin" + "$ENV{LOCALAPPDATA}/Programs/Git/usr/bin" + "$ENV{APPDATA}/Programs/Git/bin" + "$ENV{APPDATA}/Programs/Git/usr/bin" + ) +endif() + +# First search the PATH +find_program(Patch_EXECUTABLE + NAME patch + PATHS ${_patch_path} + DOC ${_doc} + ) + +if(CMAKE_HOST_WIN32) + # Now look for installations in Git/ directories under typical installation + # prefixes on Windows. + find_program(Patch_EXECUTABLE + NAMES patch + PATH_SUFFIXES Git/usr/bin Git/bin GnuWin32/bin + DOC ${_doc} + ) +endif() + +if(Patch_EXECUTABLE AND NOT TARGET Patch::patch) + add_executable(Patch::patch IMPORTED) + set_property(TARGET Patch::patch PROPERTY IMPORTED_LOCATION ${Patch_EXECUTABLE}) +endif() + +unset(_patch_path) +unset(_doc) + +include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) +find_package_handle_standard_args(Patch + REQUIRED_VARS Patch_EXECUTABLE) diff --git a/Modules/FindThreads.cmake b/Modules/FindThreads.cmake index 2c6a58b..a0148dd 100644 --- a/Modules/FindThreads.cmake +++ b/Modules/FindThreads.cmake @@ -86,23 +86,16 @@ macro(_check_pthreads_flag) set(_threads_src ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/FindThreads/CheckForPthreads.cxx) configure_file(${CMAKE_CURRENT_LIST_DIR}/CheckForPthreads.c "${_threads_src}" COPYONLY) endif() - try_run(THREADS_PTHREAD_ARG THREADS_HAVE_PTHREAD_ARG + try_compile(THREADS_HAVE_PTHREAD_ARG ${CMAKE_BINARY_DIR} ${_threads_src} CMAKE_FLAGS -DLINK_LIBRARIES:STRING=-pthread - COMPILE_OUTPUT_VARIABLE OUTPUT) + OUTPUT_VARIABLE OUTPUT) unset(_threads_src) if(THREADS_HAVE_PTHREAD_ARG) - if(THREADS_PTHREAD_ARG STREQUAL "2") - set(Threads_FOUND TRUE) - message(STATUS "Check if compiler accepts -pthread - yes") - else() - message(STATUS "Check if compiler accepts -pthread - no") - file(APPEND - ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log - "Determining if compiler accepts -pthread returned ${THREADS_PTHREAD_ARG} instead of 2. The compiler had the following output:\n${OUTPUT}\n\n") - endif() + set(Threads_FOUND TRUE) + message(STATUS "Check if compiler accepts -pthread - yes") else() message(STATUS "Check if compiler accepts -pthread - no") file(APPEND diff --git a/Modules/GetPrerequisites.cmake b/Modules/GetPrerequisites.cmake index 4e52cb3..b81dd76 100644 --- a/Modules/GetPrerequisites.cmake +++ b/Modules/GetPrerequisites.cmake @@ -659,7 +659,6 @@ function(get_prerequisites target prerequisites_var exclude_system recurse exepa if(NOT EXISTS "${target}") message("warning: target '${target}' does not exist...") - set(${prerequisites_var} "" PARENT_SCOPE) return() endif() diff --git a/Modules/InstallRequiredSystemLibraries.cmake b/Modules/InstallRequiredSystemLibraries.cmake index 1a4e268..ac8c20b 100644 --- a/Modules/InstallRequiredSystemLibraries.cmake +++ b/Modules/InstallRequiredSystemLibraries.cmake @@ -56,6 +56,36 @@ # Specify the :command:`install(PROGRAMS)` command ``COMPONENT`` # option. If not specified, no such option will be used. +set(_IRSL_HAVE_Intel FALSE) +set(_IRSL_HAVE_MSVC FALSE) +foreach(LANG IN ITEMS C CXX Fortran) + if(CMAKE_${LANG}_COMPILER_ID STREQUAL Intel) + if(NOT _IRSL_HAVE_Intel) + get_filename_component(_Intel_basedir "${CMAKE_${LANG}_COMPILER}" PATH) + if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(_Intel_archdir intel64) + else() + set(_Intel_archdir x86) + endif() + set(_Intel_compiler_ver ${CMAKE_${LANG}_COMPILER_VERSION}) + if(WIN32) + get_filename_component(_Intel_redistdir "${_Intel_basedir}/../../redist/${_Intel_archdir}/compiler" ABSOLUTE) + elseif(APPLE) + get_filename_component(_Intel_redistdir "${_Intel_basedir}/../../compiler/lib" ABSOLUTE) + else() + if(EXISTS "${_Intel_basedir}/../lib/${_Intel_archdir}_lin") + get_filename_component(_Intel_redistdir "${_Intel_basedir}/../lib/${_Intel_archdir}" ABSOLUTE) + else() + get_filename_component(_Intel_redistdir "${_Intel_basedir}/../../compiler/lib/${_Intel_archdir}_lin" ABSOLUTE) + endif() + endif() + set(_IRSL_HAVE_Intel TRUE) + endif() + elseif(CMAKE_${LANG}_COMPILER_ID STREQUAL MSVC) + set(_IRSL_HAVE_MSVC TRUE) + endif() +endforeach() + if(MSVC) file(TO_CMAKE_PATH "$ENV{SYSTEMROOT}" SYSTEMROOT) @@ -175,7 +205,12 @@ if(MSVC) endif() endif() - if(MSVC_VERSION EQUAL 1911) + set(MSVC_REDIST_NAME "") + set(_MSVCRT_DLL_VERSION "") + set(_MSVCRT_IDE_VERSION "") + if(MSVC_VERSION GREATER_EQUAL 2000) + message(WARNING "MSVC ${MSVC_VERSION} not yet supported.") + elseif(MSVC_VERSION GREATER_EQUAL 1911) set(MSVC_REDIST_NAME VC141) set(_MSVCRT_DLL_VERSION 140) set(_MSVCRT_IDE_VERSION 15) @@ -199,10 +234,6 @@ if(MSVC) set(MSVC_REDIST_NAME VC100) set(_MSVCRT_DLL_VERSION 100) set(_MSVCRT_IDE_VERSION 10) - else() - set(MSVC_REDIST_NAME "") - set(_MSVCRT_DLL_VERSION "") - set(_MSVCRT_IDE_VERSION "") endif() if(_MSVCRT_DLL_VERSION) @@ -397,10 +428,11 @@ if(MSVC) ) endif() - if(MSVC_VERSION EQUAL 1911) - set(_MFC_DLL_VERSION 140) - set(_MFC_IDE_VERSION 15) - elseif(MSVC_VERSION EQUAL 1910) + set(_MFC_DLL_VERSION "") + set(_MFC_IDE_VERSION "") + if(MSVC_VERSION GREATER_EQUAL 2000) + # Version not yet supported. + elseif(MSVC_VERSION GREATER_EQUAL 1910) set(_MFC_DLL_VERSION 140) set(_MFC_IDE_VERSION 15) elseif(MSVC_VERSION EQUAL 1900) @@ -415,9 +447,6 @@ if(MSVC) elseif(MSVC_VERSION EQUAL 1600) set(_MFC_DLL_VERSION 100) set(_MFC_IDE_VERSION 10) - else() - set(_MFC_DLL_VERSION "") - set(_MFC_IDE_VERSION "") endif() if(_MFC_DLL_VERSION) @@ -487,11 +516,12 @@ if(MSVC) # MSVC 8 was the first version with OpenMP # Furthermore, there is no debug version of this - if(CMAKE_INSTALL_OPENMP_LIBRARIES) - if(MSVC_VERSION EQUAL 1911) - set(_MSOMP_DLL_VERSION 140) - set(_MSOMP_IDE_VERSION 15) - elseif(MSVC_VERSION EQUAL 1910) + if(CMAKE_INSTALL_OPENMP_LIBRARIES AND _IRSL_HAVE_MSVC) + set(_MSOMP_DLL_VERSION "") + set(_MSOMP_IDE_VERSION "") + if(MSVC_VERSION GREATER_EQUAL 2000) + # Version not yet supported. + elseif(MSVC_VERSION GREATER_EQUAL 1910) set(_MSOMP_DLL_VERSION 140) set(_MSOMP_IDE_VERSION 15) elseif(MSVC_VERSION EQUAL 1900) @@ -512,9 +542,6 @@ if(MSVC) elseif(MSVC_VERSION EQUAL 1400) set(_MSOMP_DLL_VERSION 80) set(_MSOMP_IDE_VERSION 8) - else() - set(_MSOMP_DLL_VERSION "") - set(_MSOMP_IDE_VERSION "") endif() if(_MSOMP_DLL_VERSION) @@ -548,6 +575,109 @@ if(MSVC) endforeach() endif() +if(_IRSL_HAVE_Intel) + unset(__install_libs) + if(CMAKE_INSTALL_OPENMP_LIBRARIES) + if(WIN32) + list(APPEND __install_libs "${_Intel_redistdir}/libiomp5md.dll" "${_Intel_redistdir}/libiompstubs5md.dll") + elseif(APPLE) + list(APPEND __install_libs "${_Intel_redistdir}/libiomp5.dylib" "${_Intel_redistdir}/libiompstubs5.dylib") + else() + list(APPEND __install_libs "${_Intel_redistdir}/libiomp5.so" "${_Intel_redistdir}/libiompstubs5.so") + if(_Intel_compiler_ver VERSION_LESS 17) + list(APPEND __install_libs "${_Intel_redistdir}/libomp_db.so") + endif() + if(_Intel_compiler_ver VERSION_LESS 13) + list(APPEND __install_libs "${_Intel_redistdir}/libiompprof5.so") + endif() + endif() + endif() + if(WIN32) + set(__install_dirs "${_Intel_redistdir}/irml" "${_Intel_redistdir}/irml_c" + "${_Intel_redistdir}/1033" "${_Intel_redistdir}/1041") + foreach(__Intel_lib IN ITEMS cilkrts20.dll libchkp.dll libgfxoffload.dll libioffload_host.dll libirngmd.dll + libmmd.dll libmmdd.dll libmpx.dll liboffload.dll svml_dispmd.dll) + + list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}") + endforeach() + if(CMAKE_Fortran_COMPILER_ID STREQUAL Intel) + foreach(__Intel_lib IN ITEMS libicaf.dll libifcoremd.dll libifcoremdd.dll libifcorert.dll libifcorertd.dll libifportmd.dll) + + list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}") + endforeach() + endif() + elseif(APPLE) + foreach(__Intel_lib IN ITEMS libchkp.dylib libcilkrts.5.dylib libcilkrts.dylib libimf.dylib libintlc.dylib libirc.dylib libirng.dylib libsvml.dylib) + list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}") + endforeach() + if(_Intel_compiler_ver VERSION_LESS 17) + list(APPEND __install_libs "${_Intel_redistdir}/libistrconv.dylib") + endif() + if(CMAKE_Fortran_COMPILER_ID STREQUAL Intel) + foreach(__Intel_lib IN ITEMS libifcore.dylib libifcoremt.dylib libifport.dylib libifportmt.dylib) + + list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}") + endforeach() + endif() + else() + set(__install_dirs "${_Intel_redistdir}/irml") + foreach(__Intel_lib IN ITEMS cilk_db.so libchkp.so libcilkrts.so libcilkrts.so.5 libimf.so libintlc.so libintlc.so.5 libirc.so libpdbx.so libpdbx.so.5 libsvml.so) + + list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}") + endforeach() + if(_Intel_compiler_ver VERSION_GREATER_EQUAL 13) + foreach(__Intel_lib IN ITEMS libirng.so liboffload.so liboffload.so.5) + + list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}") + endforeach() + endif() + if(_Intel_compiler_ver VERSION_GREATER_EQUAL 15) + foreach(__Intel_lib IN ITEMS libgfxoffload.so libistrconv.so) + + list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}") + endforeach() + endif() + if(_Intel_compiler_ver VERSION_GREATER_EQUAL 16) + foreach(__Intel_lib IN ITEMS libioffload_host.so libioffload_host.so.5 libioffload_target.so libioffload_target.so.5 libmpx.so offload_main) + + list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}") + endforeach() + endif() + if(_Intel_compiler_ver VERSION_LESS 15) + foreach(__Intel_lib IN ITEMS libcxaguard.so libcxaguard.so.5) + + list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}") + endforeach() + endif() + if(CMAKE_Fortran_COMPILER_ID STREQUAL Intel) + foreach(__Intel_lib IN ITEMS libicaf.so libifcore.so libifcore.so.5 libifcoremt.so libifcoremt.so.5 libifport.so libifport.so.5) + + list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}") + endforeach() + endif() + endif() + + foreach(lib IN LISTS __install_libs) + if(EXISTS ${lib}) + list(APPEND CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS ${lib}) + else() + if(NOT CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS) + message(WARNING "system runtime library file does not exist: '${lib}'") + endif() + endif() + endforeach() + + foreach(dir IN LISTS __install_dirs) + if(EXISTS ${dir}) + list(APPEND CMAKE_INSTALL_SYSTEM_RUNTIME_DIRECTORIES ${dir}) + else() + if(NOT CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS) + message(WARNING "system runtime library file does not exist: '${dir}'") + endif() + endif() + endforeach() +endif() + if(WATCOM) get_filename_component( CompilerPath ${CMAKE_C_COMPILER} PATH ) if(CMAKE_C_COMPILER_VERSION) @@ -601,5 +731,10 @@ if(CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS) DESTINATION ${CMAKE_INSTALL_SYSTEM_RUNTIME_DESTINATION} ${_CMAKE_INSTALL_SYSTEM_RUNTIME_COMPONENT} ) + + install(DIRECTORY ${CMAKE_INSTALL_SYSTEM_RUNTIME_DIRECTORIES} + DESTINATION ${CMAKE_INSTALL_SYSTEM_RUNTIME_DESTINATION} + ${_CMAKE_INSTALL_SYSTEM_RUNTIME_COMPONENT} + ) endif() endif() diff --git a/Modules/Platform/Android/Determine-Compiler-NDK.cmake b/Modules/Platform/Android/Determine-Compiler-NDK.cmake index d983dd6..0649925 100644 --- a/Modules/Platform/Android/Determine-Compiler-NDK.cmake +++ b/Modules/Platform/Android/Determine-Compiler-NDK.cmake @@ -124,7 +124,7 @@ file(STRINGS "${_ANDROID_TOOL_SETUP_MK}" _ANDROID_TOOL_SETUP REGEX "^(LLVM|TOOLC unset(_ANDROID_TOOL_SETUP_MK) set(_ANDROID_TOOL_PREFIX "") set(_ANDROID_TOOL_NAME_ONLY "") -set(_ANDROID_TOOL_LLVM_NAME "") +set(_ANDROID_TOOL_LLVM_NAME "llvm") set(_ANDROID_TOOL_LLVM_VERS "") foreach(line IN LISTS _ANDROID_TOOL_SETUP) if(CMAKE_ANDROID_NDK_TOOLCHAIN_DEBUG) diff --git a/Modules/Platform/FreeBSD-Determine-CXX.cmake b/Modules/Platform/FreeBSD-Determine-CXX.cmake new file mode 100644 index 0000000..b594dae --- /dev/null +++ b/Modules/Platform/FreeBSD-Determine-CXX.cmake @@ -0,0 +1,3 @@ +if(NOT CMAKE_CXX_COMPILER_NAMES) + set(CMAKE_CXX_COMPILER_NAMES c++) +endif() diff --git a/Modules/Platform/Midipix.cmake b/Modules/Platform/Midipix.cmake new file mode 100644 index 0000000..54a156b --- /dev/null +++ b/Modules/Platform/Midipix.cmake @@ -0,0 +1 @@ +include(Platform/UnixPaths) diff --git a/Modules/Platform/Windows-MSVC.cmake b/Modules/Platform/Windows-MSVC.cmake index cfe6e1c..4719563 100644 --- a/Modules/Platform/Windows-MSVC.cmake +++ b/Modules/Platform/Windows-MSVC.cmake @@ -122,7 +122,9 @@ set(CMAKE_BUILD_TYPE_INIT Debug) # Compute an architecture family from the architecture id. foreach(lang C CXX) set(_MSVC_${lang}_ARCHITECTURE_FAMILY "${MSVC_${lang}_ARCHITECTURE_ID}") - if(_MSVC_${lang}_ARCHITECTURE_FAMILY MATCHES "^ARM") + if(_MSVC_${lang}_ARCHITECTURE_FAMILY MATCHES "^ARM64") + set(_MSVC_${lang}_ARCHITECTURE_FAMILY "ARM64") + elseif(_MSVC_${lang}_ARCHITECTURE_FAMILY MATCHES "^ARM") set(_MSVC_${lang}_ARCHITECTURE_FAMILY "ARM") elseif(_MSVC_${lang}_ARCHITECTURE_FAMILY MATCHES "^SH") set(_MSVC_${lang}_ARCHITECTURE_FAMILY "SHx") @@ -175,7 +177,7 @@ elseif(WINDOWS_PHONE OR WINDOWS_STORE) set(CMAKE_C_STANDARD_LIBRARIES_INIT "WindowsApp.lib") elseif(WINDOWS_PHONE) set(CMAKE_C_STANDARD_LIBRARIES_INIT "WindowsPhoneCore.lib RuntimeObject.lib PhoneAppModelHost.lib") - elseif(_MSVC_C_ARCHITECTURE_FAMILY STREQUAL "ARM" OR _MSVC_CXX_ARCHITECTURE_FAMILY STREQUAL "ARM") + elseif(_MSVC_C_ARCHITECTURE_FAMILY STREQUAL "ARM" OR _MSVC_CXX_ARCHITECTURE_FAMILY STREQUAL "ARM" OR _MSVC_C_ARCHITECTURE_FAMILY STREQUAL "ARM64" OR _MSVC_CXX_ARCHITECTURE_FAMILY STREQUAL "ARM64") set(CMAKE_C_STANDARD_LIBRARIES_INIT "kernel32.lib user32.lib") else() set(CMAKE_C_STANDARD_LIBRARIES_INIT "kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib") @@ -183,10 +185,10 @@ elseif(WINDOWS_PHONE OR WINDOWS_STORE) else() set(_PLATFORM_DEFINES "/DWIN32") - if(_MSVC_C_ARCHITECTURE_FAMILY STREQUAL "ARM" OR _MSVC_CXX_ARCHITECTURE_FAMILY STREQUAL "ARM") + if(_MSVC_C_ARCHITECTURE_FAMILY STREQUAL "ARM" OR _MSVC_CXX_ARCHITECTURE_FAMILY STREQUAL "ARM" OR _MSVC_C_ARCHITECTURE_FAMILY STREQUAL "ARM64" OR _MSVC_CXX_ARCHITECTURE_FAMILY STREQUAL "ARM64") set(CMAKE_C_STANDARD_LIBRARIES_INIT "kernel32.lib user32.lib") elseif(MSVC_VERSION GREATER 1310) - if(CMAKE_VS_PLATFORM_TOOLSET MATCHES "(v[0-9]+_clang_.*|LLVM-vs[0-9]+.*)") + if(CMAKE_VS_PLATFORM_TOOLSET MATCHES "v[0-9]+_clang_.*") # Clang/C2 in MSVC14 Update 1 seems to not support -fsantinize (yet?) # set(_RTC1 "-fsantinize=memory,safe-stack") set(_FLAGS_CXX " -frtti -fexceptions") @@ -215,6 +217,8 @@ set (CMAKE_LINK_DEF_FILE_FLAG "/DEF:") if(MSVC_C_ARCHITECTURE_ID) if(MSVC_C_ARCHITECTURE_ID MATCHES "^ARMV.I") set(_MACHINE_ARCH_FLAG "/machine:THUMB") + elseif(_MSVC_C_ARCHITECTURE_FAMILY STREQUAL "ARM64") + set(_MACHINE_ARCH_FLAG "/machine:ARM64") elseif(_MSVC_C_ARCHITECTURE_FAMILY STREQUAL "ARM") set(_MACHINE_ARCH_FLAG "/machine:ARM") else() @@ -223,6 +227,8 @@ if(MSVC_C_ARCHITECTURE_ID) elseif(MSVC_CXX_ARCHITECTURE_ID) if(MSVC_CXX_ARCHITECTURE_ID MATCHES "^ARMV.I") set(_MACHINE_ARCH_FLAG "/machine:THUMB") + elseif(_MSVC_CXX_ARCHITECTURE_FAMILY STREQUAL "ARM64") + set(_MACHINE_ARCH_FLAG "/machine:ARM64") elseif(_MSVC_CXX_ARCHITECTURE_FAMILY STREQUAL "ARM") set(_MACHINE_ARCH_FLAG "/machine:ARM") else() @@ -285,7 +291,7 @@ macro(__windows_compiler_msvc lang) if("x${lang}" STREQUAL "xC" OR "x${lang}" STREQUAL "xCXX") - if(CMAKE_VS_PLATFORM_TOOLSET MATCHES "(v[0-9]+_clang_.*|LLVM-vs[0-9]+.*)") + if(CMAKE_VS_PLATFORM_TOOLSET MATCHES "v[0-9]+_clang_.*") # note: MSVC 14 2015 Update 1 sets -fno-ms-compatibility by default, but this does not allow one to compile many projects # that include MS's own headers. CMake itself is affected project too. string(APPEND CMAKE_${lang}_FLAGS_INIT " ${_PLATFORM_DEFINES}${_PLATFORM_DEFINES_${lang}} -fms-extensions -fms-compatibility -D_WINDOWS -Wall${_FLAGS_${lang}}") diff --git a/Modules/Platform/Windows-NMcl.cmake b/Modules/Platform/Windows-NMcl.cmake deleted file mode 100644 index 7add0b0..0000000 --- a/Modules/Platform/Windows-NMcl.cmake +++ /dev/null @@ -1,4 +0,0 @@ -# this is for the numega compiler which is really a front -# end for visual studio, but adds memory checking code. - -include(Platform/Windows-cl) diff --git a/Source/CMakeLists.txt b/Source/CMakeLists.txt index bcc3437..fdc6476 100644 --- a/Source/CMakeLists.txt +++ b/Source/CMakeLists.txt @@ -307,8 +307,9 @@ set(SRCS cmPropertyDefinitionMap.h cmPropertyMap.cxx cmPropertyMap.h - cmQtAutoGeneratorCommon.cxx - cmQtAutoGeneratorCommon.h + cmQtAutoGen.cxx + cmQtAutoGen.h + cmQtAutoGenDigest.h cmQtAutoGeneratorInitializer.cxx cmQtAutoGeneratorInitializer.h cmQtAutoGenerators.cxx @@ -586,7 +587,6 @@ set(SRCS cmWriteFileCommand.cxx cmWriteFileCommand.h - cm_auto_ptr.hxx cm_get_date.h cm_get_date.c cm_utf8.h diff --git a/Source/CMakeVersion.cmake b/Source/CMakeVersion.cmake index 0e0c748..d5dc2ba 100644 --- a/Source/CMakeVersion.cmake +++ b/Source/CMakeVersion.cmake @@ -1,5 +1,5 @@ # CMake version number components. set(CMake_VERSION_MAJOR 3) set(CMake_VERSION_MINOR 9) -set(CMake_VERSION_PATCH 20170830) +set(CMake_VERSION_PATCH 20170927) #set(CMake_VERSION_RC 1) diff --git a/Source/CPack/IFW/cmCPackIFWGenerator.cxx b/Source/CPack/IFW/cmCPackIFWGenerator.cxx index 97e792a..825a888 100644 --- a/Source/CPack/IFW/cmCPackIFWGenerator.cxx +++ b/Source/CPack/IFW/cmCPackIFWGenerator.cxx @@ -49,19 +49,15 @@ int cmCPackIFWGenerator::PackageFiles() ifwCmd += " -p " + this->toplevel + "/packages"; if (!this->PkgsDirsVector.empty()) { - for (std::vector<std::string>::iterator it = - this->PkgsDirsVector.begin(); - it != this->PkgsDirsVector.end(); ++it) { - ifwCmd += " -p " + *it; + for (std::string const& it : this->PkgsDirsVector) { + ifwCmd += " -p " + it; } } if (!this->RepoDirsVector.empty()) { if (!this->IsVersionLess("3.1")) { - for (std::vector<std::string>::iterator it = - this->RepoDirsVector.begin(); - it != this->RepoDirsVector.end(); ++it) { - ifwCmd += " --repository " + *it; + for (std::string const& rd : this->RepoDirsVector) { + ifwCmd += " --repository " + rd; } } else { cmCPackIFWLogger(WARNING, "The \"CPACK_IFW_REPOSITORIES_DIRECTORIES\" " @@ -137,19 +133,15 @@ int cmCPackIFWGenerator::PackageFiles() ifwCmd += " -p " + this->toplevel + "/packages"; if (!this->PkgsDirsVector.empty()) { - for (std::vector<std::string>::iterator it = - this->PkgsDirsVector.begin(); - it != this->PkgsDirsVector.end(); ++it) { - ifwCmd += " -p " + *it; + for (std::string const& it : this->PkgsDirsVector) { + ifwCmd += " -p " + it; } } if (!this->RepoDirsVector.empty()) { if (!this->IsVersionLess("3.1")) { - for (std::vector<std::string>::iterator it = - this->RepoDirsVector.begin(); - it != this->RepoDirsVector.end(); ++it) { - ifwCmd += " --repository " + *it; + for (std::string const& rd : this->RepoDirsVector) { + ifwCmd += " --repository " + rd; } } else { cmCPackIFWLogger(WARNING, "The \"CPACK_IFW_REPOSITORIES_DIRECTORIES\" " @@ -258,7 +250,7 @@ int cmCPackIFWGenerator::InitializeInternal() const char* BinCreatorStr = this->GetOption(BinCreatorOpt); if (!BinCreatorStr || cmSystemTools::IsNOTFOUND(BinCreatorStr)) { - this->BinCreator = ""; + this->BinCreator.clear(); } else { this->BinCreator = BinCreatorStr; } @@ -274,7 +266,7 @@ int cmCPackIFWGenerator::InitializeInternal() const char* RepoGenStr = this->GetOption(RepoGenOpt); if (!RepoGenStr || cmSystemTools::IsNOTFOUND(RepoGenStr)) { - this->RepoGen = ""; + this->RepoGen.clear(); } else { this->RepoGen = RepoGenStr; } @@ -321,9 +313,8 @@ int cmCPackIFWGenerator::InitializeInternal() if (const char* RepoAllStr = this->GetOption("CPACK_IFW_REPOSITORIES_ALL")) { std::vector<std::string> RepoAllVector; cmSystemTools::ExpandListArgument(RepoAllStr, RepoAllVector); - for (std::vector<std::string>::iterator rit = RepoAllVector.begin(); - rit != RepoAllVector.end(); ++rit) { - this->GetRepository(*rit); + for (std::string const& r : RepoAllVector) { + this->GetRepository(r); } } diff --git a/Source/CPack/IFW/cmCPackIFWGenerator.h b/Source/CPack/IFW/cmCPackIFWGenerator.h index 9fd14bd..919dd46 100644 --- a/Source/CPack/IFW/cmCPackIFWGenerator.h +++ b/Source/CPack/IFW/cmCPackIFWGenerator.h @@ -47,7 +47,7 @@ public: /** * Destruct IFW generator */ - ~cmCPackIFWGenerator() CM_OVERRIDE; + ~cmCPackIFWGenerator() override; protected: // cmCPackGenerator reimplementation @@ -56,18 +56,18 @@ protected: * @brief Initialize generator * @return 0 on failure */ - int InitializeInternal() CM_OVERRIDE; - int PackageFiles() CM_OVERRIDE; - const char* GetPackagingInstallPrefix() CM_OVERRIDE; + int InitializeInternal() override; + int PackageFiles() override; + const char* GetPackagingInstallPrefix() override; /** * @brief Target binary extension * @return Executable suffix or disk image format */ - const char* GetOutputExtension() CM_OVERRIDE; + const char* GetOutputExtension() override; std::string GetComponentInstallDirNameSuffix( - const std::string& componentName) CM_OVERRIDE; + const std::string& componentName) override; /** * @brief Get Component @@ -79,7 +79,7 @@ protected: * @return Pointer to component */ cmCPackComponent* GetComponent(const std::string& projectName, - const std::string& componentName) CM_OVERRIDE; + const std::string& componentName) override; /** * @brief Get group of component @@ -91,12 +91,12 @@ protected: * @return Pointer to component group */ cmCPackComponentGroup* GetComponentGroup( - const std::string& projectName, const std::string& groupName) CM_OVERRIDE; + const std::string& projectName, const std::string& groupName) override; - enum cmCPackGenerator::CPackSetDestdirSupport SupportsSetDestdir() const - CM_OVERRIDE; - bool SupportsAbsoluteDestination() const CM_OVERRIDE; - bool SupportsComponentInstallation() const CM_OVERRIDE; + enum cmCPackGenerator::CPackSetDestdirSupport SupportsSetDestdir() + const override; + bool SupportsAbsoluteDestination() const override; + bool SupportsComponentInstallation() const override; protected: // Methods diff --git a/Source/CPack/IFW/cmCPackIFWInstaller.cxx b/Source/CPack/IFW/cmCPackIFWInstaller.cxx index 288e924..422f5d5 100644 --- a/Source/CPack/IFW/cmCPackIFWInstaller.cxx +++ b/Source/CPack/IFW/cmCPackIFWInstaller.cxx @@ -262,7 +262,7 @@ public: std::string path, basePath; protected: - void StartElement(const std::string& name, const char** /*atts*/) CM_OVERRIDE + void StartElement(const std::string& name, const char** /*atts*/) override { this->file = name == "file"; if (file) { @@ -270,7 +270,7 @@ protected: } } - void CharacterDataHandler(const char* data, int length) CM_OVERRIDE + void CharacterDataHandler(const char* data, int length) override { if (this->file) { std::string content(data, data + length); @@ -284,7 +284,7 @@ protected: } } - void EndElement(const std::string& /*name*/) CM_OVERRIDE {} + void EndElement(const std::string& /*name*/) override {} }; void cmCPackIFWInstaller::GenerateInstallerFile() @@ -406,9 +406,8 @@ void cmCPackIFWInstaller::GenerateInstallerFile() // Remote repositories if (!this->RemoteRepositories.empty()) { xout.StartElement("RemoteRepositories"); - for (RepositoriesVector::iterator rit = this->RemoteRepositories.begin(); - rit != this->RemoteRepositories.end(); ++rit) { - (*rit)->WriteRepositoryConfig(xout); + for (cmCPackIFWRepository* r : this->RemoteRepositories) { + r->WriteRepositoryConfig(xout); } xout.EndElement(); } @@ -492,9 +491,8 @@ void cmCPackIFWInstaller::GeneratePackageFiles() } // Generate packages meta information - for (PackagesMap::iterator pit = this->Packages.begin(); - pit != this->Packages.end(); ++pit) { - cmCPackIFWPackage* package = pit->second; + for (auto& p : this->Packages) { + cmCPackIFWPackage* package = p.second; package->GeneratePackageFile(); } } diff --git a/Source/CPack/IFW/cmCPackIFWPackage.cxx b/Source/CPack/IFW/cmCPackIFWPackage.cxx index 8461309..d3ce15c 100644 --- a/Source/CPack/IFW/cmCPackIFWPackage.cxx +++ b/Source/CPack/IFW/cmCPackIFWPackage.cxx @@ -111,19 +111,19 @@ void cmCPackIFWPackage::DefaultConfiguration() { this->DisplayName.clear(); this->Description.clear(); - this->Version = ""; - this->ReleaseDate = ""; - this->Script = ""; + this->Version.clear(); + this->ReleaseDate.clear(); + this->Script.clear(); this->Licenses.clear(); this->UserInterfaces.clear(); this->Translations.clear(); - this->SortingPriority = ""; - this->UpdateText = ""; - this->Default = ""; - this->Essential = ""; - this->Virtual = ""; - this->ForcedInstallation = ""; - this->RequiresAdminRights = ""; + this->SortingPriority.clear(); + this->UpdateText.clear(); + this->Default.clear(); + this->Essential.clear(); + this->Virtual.clear(); + this->ForcedInstallation.clear(); + this->RequiresAdminRights.clear(); } // Defaul configuration (all in one package) @@ -203,10 +203,8 @@ int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent* component) // CMake dependencies if (!component->Dependencies.empty()) { - std::vector<cmCPackComponent*>::iterator dit; - for (dit = component->Dependencies.begin(); - dit != component->Dependencies.end(); ++dit) { - this->Dependencies.insert(this->Generator->ComponentPackages[*dit]); + for (cmCPackComponent* dep : component->Dependencies) { + this->Dependencies.insert(this->Generator->ComponentPackages[dep]); } } @@ -413,9 +411,8 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix) if (const char* value = this->GetOption(option)) { cmSystemTools::ExpandListArgument(value, deps); } - for (std::vector<std::string>::iterator dit = deps.begin(); - dit != deps.end(); ++dit) { - DependenceStruct dep(*dit); + for (std::string const& d : deps) { + DependenceStruct dep(d); if (this->Generator->Packages.count(dep.Name)) { cmCPackIFWPackage& depPkg = this->Generator->Packages[dep.Name]; dep.Name = depPkg.Name; @@ -435,9 +432,8 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix) } else if (const char* value = this->GetOption(option)) { std::vector<std::string> depsOn; cmSystemTools::ExpandListArgument(value, depsOn); - for (std::vector<std::string>::iterator dit = depsOn.begin(); - dit != depsOn.end(); ++dit) { - DependenceStruct dep(*dit); + for (std::string const& d : depsOn) { + DependenceStruct dep(d); if (this->Generator->Packages.count(dep.Name)) { cmCPackIFWPackage& depPkg = this->Generator->Packages[dep.Name]; dep.Name = depPkg.Name; @@ -486,6 +482,15 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix) this->ForcedInstallation = "false"; } + // Replaces + option = prefix + "REPLACES"; + if (this->IsSetToEmpty(option)) { + this->Replaces.clear(); + } else if (const char* value = this->GetOption(option)) { + this->Replaces.clear(); + cmSystemTools::ExpandListArgument(value, this->Replaces); + } + // Requires admin rights option = prefix + "REQUIRES_ADMIN_RIGHTS"; if (this->IsSetToEmpty(option)) { @@ -496,6 +501,16 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix) this->RequiresAdminRights = "false"; } + // Checkable + option = prefix + "CHECKABLE"; + if (this->IsSetToEmpty(option)) { + this->Checkable.clear(); + } else if (this->IsOn(option)) { + this->Checkable = "true"; + } else if (this->IsSetToOff(option)) { + this->Checkable = "false"; + } + return 1; } @@ -521,26 +536,22 @@ void cmCPackIFWPackage::GeneratePackageFile() xout.StartElement("Package"); // DisplayName (with translations) - for (std::map<std::string, std::string>::iterator it = - this->DisplayName.begin(); - it != this->DisplayName.end(); ++it) { + for (auto const& dn : this->DisplayName) { xout.StartElement("DisplayName"); - if (!it->first.empty()) { - xout.Attribute("xml:lang", it->first); + if (!dn.first.empty()) { + xout.Attribute("xml:lang", dn.first); } - xout.Content(it->second); + xout.Content(dn.second); xout.EndElement(); } // Description (with translations) - for (std::map<std::string, std::string>::iterator it = - this->Description.begin(); - it != this->Description.end(); ++it) { + for (auto const& d : this->Description) { xout.StartElement("Description"); - if (!it->first.empty()) { - xout.Attribute("xml:lang", it->first); + if (!d.first.empty()) { + xout.Attribute("xml:lang", d.first); } - xout.Content(it->second); + xout.Content(d.second); xout.EndElement(); } @@ -568,46 +579,43 @@ void cmCPackIFWPackage::GeneratePackageFile() // User Interfaces (copy to meta dir) std::vector<std::string> userInterfaces = UserInterfaces; - for (size_t i = 0; i < userInterfaces.size(); i++) { - std::string name = cmSystemTools::GetFilenameName(userInterfaces[i]); + for (std::string& userInterface : userInterfaces) { + std::string name = cmSystemTools::GetFilenameName(userInterface); std::string path = this->Directory + "/meta/" + name; - cmsys::SystemTools::CopyFileIfDifferent(userInterfaces[i], path); - userInterfaces[i] = name; + cmsys::SystemTools::CopyFileIfDifferent(userInterface, path); + userInterface = name; } if (!userInterfaces.empty()) { xout.StartElement("UserInterfaces"); - for (size_t i = 0; i < userInterfaces.size(); i++) { - xout.Element("UserInterface", userInterfaces[i]); + for (std::string const& userInterface : userInterfaces) { + xout.Element("UserInterface", userInterface); } xout.EndElement(); } // Translations (copy to meta dir) std::vector<std::string> translations = Translations; - for (size_t i = 0; i < translations.size(); i++) { - std::string name = cmSystemTools::GetFilenameName(translations[i]); + for (std::string& translation : translations) { + std::string name = cmSystemTools::GetFilenameName(translation); std::string path = this->Directory + "/meta/" + name; - cmsys::SystemTools::CopyFileIfDifferent(translations[i], path); - translations[i] = name; + cmsys::SystemTools::CopyFileIfDifferent(translation, path); + translation = name; } if (!translations.empty()) { xout.StartElement("Translations"); - for (size_t i = 0; i < translations.size(); i++) { - xout.Element("Translation", translations[i]); + for (std::string const& translation : translations) { + xout.Element("Translation", translation); } xout.EndElement(); } // Dependencies std::set<DependenceStruct> compDepSet; - for (std::set<DependenceStruct*>::iterator ait = - this->AlienDependencies.begin(); - ait != this->AlienDependencies.end(); ++ait) { - compDepSet.insert(*(*ait)); + for (DependenceStruct* ad : this->AlienDependencies) { + compDepSet.insert(*ad); } - for (std::set<cmCPackIFWPackage*>::iterator it = this->Dependencies.begin(); - it != this->Dependencies.end(); ++it) { - compDepSet.insert(DependenceStruct((*it)->Name)); + for (cmCPackIFWPackage* d : this->Dependencies) { + compDepSet.insert(DependenceStruct(d->Name)); } // Write dependencies if (!compDepSet.empty()) { @@ -624,10 +632,8 @@ void cmCPackIFWPackage::GeneratePackageFile() // Automatic dependency on std::set<DependenceStruct> compAutoDepSet; - for (std::set<DependenceStruct*>::iterator ait = - this->AlienAutoDependOn.begin(); - ait != this->AlienAutoDependOn.end(); ++ait) { - compAutoDepSet.insert(*(*ait)); + for (DependenceStruct* aad : this->AlienAutoDependOn) { + compAutoDepSet.insert(*aad); } // Write automatic dependency on if (!compAutoDepSet.empty()) { @@ -665,6 +671,19 @@ void cmCPackIFWPackage::GeneratePackageFile() xout.Element("ForcedInstallation", this->ForcedInstallation); } + // Replaces + if (!this->Replaces.empty()) { + std::ostringstream replaces; + std::vector<std::string>::iterator it = this->Replaces.begin(); + replaces << *it; + ++it; + while (it != this->Replaces.end()) { + replaces << "," << *it; + ++it; + } + xout.Element("Replaces", replaces.str()); + } + if (!this->RequiresAdminRights.empty()) { xout.Element("RequiresAdminRights", this->RequiresAdminRights); } @@ -685,6 +704,11 @@ void cmCPackIFWPackage::GeneratePackageFile() xout.Element("SortingPriority", this->SortingPriority); } + // Checkable + if (!this->Checkable.empty()) { + xout.Element("Checkable", this->Checkable); + } + xout.EndElement(); xout.EndDocument(); } diff --git a/Source/CPack/IFW/cmCPackIFWPackage.h b/Source/CPack/IFW/cmCPackIFWPackage.h index cec59b0..ae41146 100644 --- a/Source/CPack/IFW/cmCPackIFWPackage.h +++ b/Source/CPack/IFW/cmCPackIFWPackage.h @@ -114,9 +114,15 @@ public: /// Determines that the package must always be installed std::string ForcedInstallation; + /// List of components to replace + std::vector<std::string> Replaces; + /// Package needs to be installed with elevated permissions std::string RequiresAdminRights; + /// Set to false if you want to hide the checkbox for an item + std::string Checkable; + public: // Internal implementation diff --git a/Source/CPack/IFW/cmCPackIFWRepository.cxx b/Source/CPack/IFW/cmCPackIFWRepository.cxx index b115db0..a01fc4e 100644 --- a/Source/CPack/IFW/cmCPackIFWRepository.cxx +++ b/Source/CPack/IFW/cmCPackIFWRepository.cxx @@ -62,49 +62,49 @@ bool cmCPackIFWRepository::ConfigureFromOptions() if (const char* url = this->GetOption(prefix + "URL")) { this->Url = url; } else { - this->Url = ""; + this->Url.clear(); } // Old url if (const char* oldUrl = this->GetOption(prefix + "OLD_URL")) { this->OldUrl = oldUrl; } else { - this->OldUrl = ""; + this->OldUrl.clear(); } // New url if (const char* newUrl = this->GetOption(prefix + "NEW_URL")) { this->NewUrl = newUrl; } else { - this->NewUrl = ""; + this->NewUrl.clear(); } // Enabled if (this->IsOn(prefix + "DISABLED")) { this->Enabled = "0"; } else { - this->Enabled = ""; + this->Enabled.clear(); } // Username if (const char* username = this->GetOption(prefix + "USERNAME")) { this->Username = username; } else { - this->Username = ""; + this->Username.clear(); } // Password if (const char* password = this->GetOption(prefix + "PASSWORD")) { this->Password = password; } else { - this->Password = ""; + this->Password.clear(); } // DisplayName if (const char* displayName = this->GetOption(prefix + "DISPLAY_NAME")) { this->DisplayName = displayName; } else { - this->DisplayName = ""; + this->DisplayName.clear(); } return this->IsValid(); @@ -128,7 +128,7 @@ public: bool patched; protected: - void StartElement(const std::string& name, const char** atts) CM_OVERRIDE + void StartElement(const std::string& name, const char** atts) override { this->xout.StartElement(name); this->StartFragment(atts); @@ -143,7 +143,7 @@ protected: } } - void EndElement(const std::string& name) CM_OVERRIDE + void EndElement(const std::string& name) override { if (name == "Updates" && !this->patched) { this->repository->WriteRepositoryUpdates(this->xout); @@ -159,10 +159,10 @@ protected: } } - void CharacterDataHandler(const char* data, int length) CM_OVERRIDE + void CharacterDataHandler(const char* data, int length) override { std::string content(data, data + length); - if (content == "" || content == " " || content == " " || + if (content.empty() || content == " " || content == " " || content == "\n") { return; } @@ -279,9 +279,8 @@ void cmCPackIFWRepository::WriteRepositoryUpdates(cmXMLWriter& xout) { if (!this->RepositoryUpdate.empty()) { xout.StartElement("RepositoryUpdate"); - for (RepositoriesVector::iterator rit = this->RepositoryUpdate.begin(); - rit != this->RepositoryUpdate.end(); ++rit) { - (*rit)->WriteRepositoryUpdate(xout); + for (cmCPackIFWRepository* r : this->RepositoryUpdate) { + r->WriteRepositoryUpdate(xout); } xout.EndElement(); } diff --git a/Source/CPack/OSXScriptLauncher.cxx b/Source/CPack/OSXScriptLauncher.cxx index b48bf12..d3de02b 100644 --- a/Source/CPack/OSXScriptLauncher.cxx +++ b/Source/CPack/OSXScriptLauncher.cxx @@ -34,7 +34,7 @@ int main(int argc, char* argv[]) } fileName = CFSTR("RuntimeScript"); if (!(scriptFileURL = - CFBundleCopyResourceURL(appBundle, fileName, NULL, NULL))) { + CFBundleCopyResourceURL(appBundle, fileName, nullptr, nullptr))) { DebugError("CFBundleCopyResourceURL failed"); return 1; } @@ -71,7 +71,7 @@ int main(int argc, char* argv[]) for (cc = 1; cc < argc; ++cc) { args.push_back(argv[cc]); } - args.push_back(0); + args.push_back(nullptr); cmsysProcess* cp = cmsysProcess_New(); cmsysProcess_SetCommand(cp, &*args.begin()); @@ -83,7 +83,7 @@ int main(int argc, char* argv[]) std::vector<char> tempOutput; char* data; int length; - while (cmsysProcess_WaitForData(cp, &data, &length, 0)) { + while (cmsysProcess_WaitForData(cp, &data, &length, nullptr)) { // Translate NULL characters in the output into valid text. for (int i = 0; i < length; ++i) { if (data[i] == '\0') { @@ -93,7 +93,7 @@ int main(int argc, char* argv[]) std::cout.write(data, length); } - cmsysProcess_WaitForExit(cp, 0); + cmsysProcess_WaitForExit(cp, nullptr); bool result = true; if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exited) { diff --git a/Source/CPack/WiX/cmCPackWIXGenerator.cxx b/Source/CPack/WiX/cmCPackWIXGenerator.cxx index 274dfd0..ba07d08 100644 --- a/Source/CPack/WiX/cmCPackWIXGenerator.cxx +++ b/Source/CPack/WiX/cmCPackWIXGenerator.cxx @@ -89,9 +89,8 @@ bool cmCPackWIXGenerator::RunCandleCommand(std::string const& sourceFile, command << " -arch " << GetArchitecture(); command << " -out " << QuotePath(objectFile); - for (extension_set_t::const_iterator i = CandleExtensions.begin(); - i != CandleExtensions.end(); ++i) { - command << " -ext " << QuotePath(*i); + for (std::string const& ext : CandleExtensions) { + command << " -ext " << QuotePath(ext); } AddCustomFlags("CPACK_WIX_CANDLE_EXTRA_FLAGS", command); @@ -113,9 +112,8 @@ bool cmCPackWIXGenerator::RunLightCommand(std::string const& objectFiles) command << " -nologo"; command << " -out " << QuotePath(packageFileNames.at(0)); - for (extension_set_t::const_iterator i = this->LightExtensions.begin(); - i != this->LightExtensions.end(); ++i) { - command << " -ext " << QuotePath(*i); + for (std::string const& ext : this->LightExtensions) { + command << " -ext " << QuotePath(ext); } const char* const cultures = GetOption("CPACK_WIX_CULTURES"); @@ -219,8 +217,8 @@ bool cmCPackWIXGenerator::InitializeWiXConfiguration() std::vector<std::string> patchFilePaths; cmSystemTools::ExpandListArgument(patchFilePath, patchFilePaths); - for (size_t i = 0; i < patchFilePaths.size(); ++i) { - if (!this->Patch->LoadFragments(patchFilePaths[i])) { + for (std::string const& p : patchFilePaths) { + if (!this->Patch->LoadFragments(p)) { return false; } } @@ -254,9 +252,7 @@ bool cmCPackWIXGenerator::PackageFilesImpl() std::set<std::string> usedBaseNames; std::ostringstream objectFiles; - for (size_t i = 0; i < this->WixSources.size(); ++i) { - std::string const& sourceFilename = this->WixSources[i]; - + for (std::string const& sourceFilename : this->WixSources) { std::string baseName = cmSystemTools::GetFilenameWithoutLastExtension(sourceFilename); @@ -306,8 +302,8 @@ void cmCPackWIXGenerator::AppendUserSuppliedExtraObjects(std::ostream& stream) cmSystemTools::ExpandListArgument(cpackWixExtraObjects, expandedExtraObjects); - for (size_t i = 0; i < expandedExtraObjects.size(); ++i) { - stream << " " << QuotePath(expandedExtraObjects[i]); + for (std::string const& obj : expandedExtraObjects) { + stream << " " << QuotePath(obj); } } @@ -345,9 +341,7 @@ void cmCPackWIXGenerator::CreateWiXPropertiesIncludeFile() std::string prefix = "CPACK_WIX_PROPERTY_"; std::vector<std::string> options = GetOptions(); - for (size_t i = 0; i < options.size(); ++i) { - std::string const& name = options[i]; - + for (std::string const& name : options) { if (name.length() > prefix.length() && name.substr(0, prefix.length()) == prefix) { std::string id = name.substr(prefix.length()); @@ -503,16 +497,14 @@ bool cmCPackWIXGenerator::CreateWiXSourceFiles() globalShortcuts.AddShortcutTypes(emittedShortcutTypes); } else { - for (std::map<std::string, cmCPackComponent>::const_iterator i = - this->Components.begin(); - i != this->Components.end(); ++i) { - cmCPackComponent const& component = i->second; + for (auto const& i : this->Components) { + cmCPackComponent const& component = i.second; std::string componentPath = toplevel; componentPath += "/"; componentPath += component.Name; - std::string componentFeatureId = "CM_C_" + component.Name; + std::string const componentFeatureId = "CM_C_" + component.Name; cmWIXShortcuts featureShortcuts; AddComponentsToFeature(componentPath, componentFeatureId, @@ -623,19 +615,15 @@ bool cmCPackWIXGenerator::GenerateMainSourceFileFromTemplate() bool cmCPackWIXGenerator::CreateFeatureHierarchy( cmWIXFeaturesSourceWriter& featureDefinitions) { - for (std::map<std::string, cmCPackComponentGroup>::const_iterator i = - ComponentGroups.begin(); - i != ComponentGroups.end(); ++i) { - cmCPackComponentGroup const& group = i->second; + for (auto const& i : ComponentGroups) { + cmCPackComponentGroup const& group = i.second; if (group.ParentGroup == 0) { featureDefinitions.EmitFeatureForComponentGroup(group, *this->Patch); } } - for (std::map<std::string, cmCPackComponent>::const_iterator i = - this->Components.begin(); - i != this->Components.end(); ++i) { - cmCPackComponent const& component = i->second; + for (auto const& i : this->Components) { + cmCPackComponent const& component = i.second; if (!component.Group) { featureDefinitions.EmitFeatureForComponent(component, *this->Patch); @@ -1135,9 +1123,8 @@ void cmCPackWIXGenerator::AddCustomFlags(std::string const& variableName, std::vector<std::string> list; cmSystemTools::ExpandListArgument(variableContent, list); - for (std::vector<std::string>::const_iterator i = list.begin(); - i != list.end(); ++i) { - stream << " " << QuotePath(*i); + for (std::string const& i : list) { + stream << " " << QuotePath(i); } } diff --git a/Source/CPack/WiX/cmWIXAccessControlList.cxx b/Source/CPack/WiX/cmWIXAccessControlList.cxx index 744a932..1603bf8 100644 --- a/Source/CPack/WiX/cmWIXAccessControlList.cxx +++ b/Source/CPack/WiX/cmWIXAccessControlList.cxx @@ -20,8 +20,8 @@ bool cmWIXAccessControlList::Apply() std::vector<std::string> entries; this->InstalledFile.GetPropertyAsList("CPACK_WIX_ACL", entries); - for (size_t i = 0; i < entries.size(); ++i) { - this->CreatePermissionElement(entries[i]); + for (std::string const& entry : entries) { + this->CreatePermissionElement(entry); } return true; @@ -56,9 +56,9 @@ void cmWIXAccessControlList::CreatePermissionElement(std::string const& entry) if (!domain.empty()) { this->SourceWriter.AddAttribute("Domain", domain); } - for (size_t i = 0; i < permissions.size(); ++i) { + for (std::string const& permission : permissions) { this->EmitBooleanAttribute(entry, - cmSystemTools::TrimWhitespace(permissions[i])); + cmSystemTools::TrimWhitespace(permission)); } this->SourceWriter.EndElement("Permission"); } diff --git a/Source/CPack/WiX/cmWIXFeaturesSourceWriter.cxx b/Source/CPack/WiX/cmWIXFeaturesSourceWriter.cxx index 0be4377..a7a0648 100644 --- a/Source/CPack/WiX/cmWIXFeaturesSourceWriter.cxx +++ b/Source/CPack/WiX/cmWIXFeaturesSourceWriter.cxx @@ -46,16 +46,12 @@ void cmWIXFeaturesSourceWriter::EmitFeatureForComponentGroup( patch.ApplyFragment("CM_G_" + group.Name, *this); - for (std::vector<cmCPackComponentGroup*>::const_iterator i = - group.Subgroups.begin(); - i != group.Subgroups.end(); ++i) { - EmitFeatureForComponentGroup(**i, patch); + for (cmCPackComponentGroup* subgroup : group.Subgroups) { + EmitFeatureForComponentGroup(*subgroup, patch); } - for (std::vector<cmCPackComponent*>::const_iterator i = - group.Components.begin(); - i != group.Components.end(); ++i) { - EmitFeatureForComponent(**i, patch); + for (cmCPackComponent* component : group.Components) { + EmitFeatureForComponent(*component, patch); } EndElement("Feature"); diff --git a/Source/CPack/WiX/cmWIXPatch.cxx b/Source/CPack/WiX/cmWIXPatch.cxx index 287a644..dec95fb 100644 --- a/Source/CPack/WiX/cmWIXPatch.cxx +++ b/Source/CPack/WiX/cmWIXPatch.cxx @@ -29,10 +29,8 @@ void cmWIXPatch::ApplyFragment(std::string const& id, return; const cmWIXPatchElement& fragment = i->second; - for (cmWIXPatchElement::attributes_t::const_iterator attr_i = - fragment.attributes.begin(); - attr_i != fragment.attributes.end(); ++attr_i) { - writer.AddAttribute(attr_i->first, attr_i->second); + for (auto const& attr : fragment.attributes) { + writer.AddAttribute(attr.first, attr.second); } this->ApplyElementChildren(fragment, writer); @@ -42,11 +40,7 @@ void cmWIXPatch::ApplyFragment(std::string const& id, void cmWIXPatch::ApplyElementChildren(const cmWIXPatchElement& element, cmWIXSourceWriter& writer) { - for (cmWIXPatchElement::child_list_t::const_iterator j = - element.children.begin(); - j != element.children.end(); ++j) { - cmWIXPatchNode* node = *j; - + for (cmWIXPatchNode* node : element.children) { switch (node->type()) { case cmWIXPatchNode::ELEMENT: ApplyElement(dynamic_cast<const cmWIXPatchElement&>(*node), writer); @@ -63,10 +57,8 @@ void cmWIXPatch::ApplyElement(const cmWIXPatchElement& element, { writer.BeginElement(element.name); - for (cmWIXPatchElement::attributes_t::const_iterator i = - element.attributes.begin(); - i != element.attributes.end(); ++i) { - writer.AddAttribute(i->first, i->second); + for (auto const& attr : element.attributes) { + writer.AddAttribute(attr.first, attr.second); } this->ApplyElementChildren(element, writer); @@ -77,14 +69,13 @@ void cmWIXPatch::ApplyElement(const cmWIXPatchElement& element, bool cmWIXPatch::CheckForUnappliedFragments() { std::string fragmentList; - for (cmWIXPatchParser::fragment_map_t::const_iterator i = Fragments.begin(); - i != Fragments.end(); ++i) { + for (auto const& fragment : Fragments) { if (!fragmentList.empty()) { fragmentList += ", "; } fragmentList += "'"; - fragmentList += i->first; + fragmentList += fragment.first; fragmentList += "'"; } diff --git a/Source/CPack/WiX/cmWIXPatchParser.cxx b/Source/CPack/WiX/cmWIXPatchParser.cxx index b050b85..e6aeed3 100644 --- a/Source/CPack/WiX/cmWIXPatchParser.cxx +++ b/Source/CPack/WiX/cmWIXPatchParser.cxx @@ -22,8 +22,8 @@ cmWIXPatchNode::~cmWIXPatchNode() cmWIXPatchElement::~cmWIXPatchElement() { - for (child_list_t::iterator i = children.begin(); i != children.end(); ++i) { - delete *i; + for (cmWIXPatchNode* child : children) { + delete child; } } diff --git a/Source/CPack/WiX/cmWIXShortcut.cxx b/Source/CPack/WiX/cmWIXShortcut.cxx index e5dea94..cd1988a 100644 --- a/Source/CPack/WiX/cmWIXShortcut.cxx +++ b/Source/CPack/WiX/cmWIXShortcut.cxx @@ -47,10 +47,9 @@ bool cmWIXShortcuts::EmitShortcuts( return false; } - for (shortcut_id_map_t::const_iterator j = id_map.begin(); j != id_map.end(); - ++j) { - std::string const& id = j->first; - shortcut_list_t const& shortcutList = j->second; + for (auto const& j : id_map) { + std::string const& id = j.first; + shortcut_list_t const& shortcutList = j.second; for (size_t shortcutListIndex = 0; shortcutListIndex < shortcutList.size(); ++shortcutListIndex) { @@ -68,9 +67,8 @@ bool cmWIXShortcuts::EmitShortcuts( void cmWIXShortcuts::AddShortcutTypes(std::set<Type>& types) { - for (shortcut_type_map_t::const_iterator i = this->Shortcuts.begin(); - i != this->Shortcuts.end(); ++i) { - types.insert(i->first); + for (auto const& shortcut : this->Shortcuts) { + types.insert(shortcut.first); } } @@ -96,9 +94,9 @@ void cmWIXShortcuts::CreateFromProperty(std::string const& propertyName, std::vector<std::string> list; installedFile.GetPropertyAsList(propertyName, list); - for (size_t i = 0; i < list.size(); ++i) { + for (std::string const& label : list) { cmWIXShortcut shortcut; - shortcut.label = list[i]; + shortcut.label = label; shortcut.workingDirectoryId = directoryId; insert(type, id, shortcut); } diff --git a/Source/CPack/WiX/cmWIXSourceWriter.cxx b/Source/CPack/WiX/cmWIXSourceWriter.cxx index a86e28d..dc730e0 100644 --- a/Source/CPack/WiX/cmWIXSourceWriter.cxx +++ b/Source/CPack/WiX/cmWIXSourceWriter.cxx @@ -158,9 +158,7 @@ std::string cmWIXSourceWriter::EscapeAttributeValue(std::string const& value) std::string result; result.reserve(value.size()); - char c = 0; - for (size_t i = 0; i < value.size(); ++i) { - c = value[i]; + for (char c : value) { switch (c) { case '<': result += "<"; diff --git a/Source/CPack/cmCPack7zGenerator.h b/Source/CPack/cmCPack7zGenerator.h index 31c02a4..8af4c4a 100644 --- a/Source/CPack/cmCPack7zGenerator.h +++ b/Source/CPack/cmCPack7zGenerator.h @@ -20,10 +20,10 @@ public: * Construct generator */ cmCPack7zGenerator(); - ~cmCPack7zGenerator() CM_OVERRIDE; + ~cmCPack7zGenerator() override; protected: - const char* GetOutputExtension() CM_OVERRIDE { return ".7z"; } + const char* GetOutputExtension() override { return ".7z"; } }; #endif diff --git a/Source/CPack/cmCPackArchiveGenerator.cxx b/Source/CPack/cmCPackArchiveGenerator.cxx index 1e45b48..641be38 100644 --- a/Source/CPack/cmCPackArchiveGenerator.cxx +++ b/Source/CPack/cmCPackArchiveGenerator.cxx @@ -9,7 +9,6 @@ #include "cmSystemTools.h" #include "cmWorkingDirectory.h" -#include <map> #include <ostream> #include <utility> #include <vector> @@ -74,10 +73,8 @@ int cmCPackArchiveGenerator::addOneComponentToArchive( filePrefix += installPrefix + 1; filePrefix += "/"; } - std::vector<std::string>::const_iterator fileIt; - for (fileIt = component->Files.begin(); fileIt != component->Files.end(); - ++fileIt) { - std::string rp = filePrefix + *fileIt; + for (std::string const& file : component->Files) { + std::string rp = filePrefix + file; cmCPackLogger(cmCPackLog::LOG_DEBUG, "Adding file: " << rp << std::endl); archive.Add(rp, 0, nullptr, false); if (!archive) { @@ -117,53 +114,47 @@ int cmCPackArchiveGenerator::PackageComponents(bool ignoreGroup) // The default behavior is to have one package by component group // unless CPACK_COMPONENTS_IGNORE_GROUP is specified. if (!ignoreGroup) { - std::map<std::string, cmCPackComponentGroup>::iterator compGIt; - for (compGIt = this->ComponentGroups.begin(); - compGIt != this->ComponentGroups.end(); ++compGIt) { - cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Packaging component group: " - << compGIt->first << std::endl); + for (auto const& compG : this->ComponentGroups) { + cmCPackLogger(cmCPackLog::LOG_VERBOSE, + "Packaging component group: " << compG.first << std::endl); // Begin the archive for this group std::string packageFileName = std::string(toplevel) + "/" + - this->GetArchiveComponentFileName(compGIt->first, true); + this->GetArchiveComponentFileName(compG.first, true); // open a block in order to automatically close archive // at the end of the block { DECLARE_AND_OPEN_ARCHIVE(packageFileName, archive); // now iterate over the component of this group - std::vector<cmCPackComponent*>::iterator compIt; - for (compIt = (compGIt->second).Components.begin(); - compIt != (compGIt->second).Components.end(); ++compIt) { + for (cmCPackComponent* comp : (compG.second).Components) { // Add the files of this component to the archive - addOneComponentToArchive(archive, *compIt); + addOneComponentToArchive(archive, comp); } } // add the generated package to package file names list packageFileNames.push_back(packageFileName); } // Handle Orphan components (components not belonging to any groups) - std::map<std::string, cmCPackComponent>::iterator compIt; - for (compIt = this->Components.begin(); compIt != this->Components.end(); - ++compIt) { + for (auto& comp : this->Components) { // Does the component belong to a group? - if (compIt->second.Group == nullptr) { + if (comp.second.Group == nullptr) { cmCPackLogger( cmCPackLog::LOG_VERBOSE, "Component <" - << compIt->second.Name + << comp.second.Name << "> does not belong to any group, package it separately." << std::endl); std::string localToplevel( this->GetOption("CPACK_TEMPORARY_DIRECTORY")); std::string packageFileName = std::string(toplevel); - localToplevel += "/" + compIt->first; + localToplevel += "/" + comp.first; packageFileName += - "/" + this->GetArchiveComponentFileName(compIt->first, false); + "/" + this->GetArchiveComponentFileName(comp.first, false); { DECLARE_AND_OPEN_ARCHIVE(packageFileName, archive); // Add the files of this component to the archive - addOneComponentToArchive(archive, &(compIt->second)); + addOneComponentToArchive(archive, &(comp.second)); } // add the generated package to package file names list packageFileNames.push_back(packageFileName); @@ -173,20 +164,18 @@ int cmCPackArchiveGenerator::PackageComponents(bool ignoreGroup) // CPACK_COMPONENTS_IGNORE_GROUPS is set // We build 1 package per component else { - std::map<std::string, cmCPackComponent>::iterator compIt; - for (compIt = this->Components.begin(); compIt != this->Components.end(); - ++compIt) { + for (auto& comp : this->Components) { std::string localToplevel(this->GetOption("CPACK_TEMPORARY_DIRECTORY")); std::string packageFileName = std::string(toplevel); - localToplevel += "/" + compIt->first; + localToplevel += "/" + comp.first; packageFileName += - "/" + this->GetArchiveComponentFileName(compIt->first, false); + "/" + this->GetArchiveComponentFileName(comp.first, false); { DECLARE_AND_OPEN_ARCHIVE(packageFileName, archive); // Add the files of this component to the archive - addOneComponentToArchive(archive, &(compIt->second)); + addOneComponentToArchive(archive, &(comp.second)); } // add the generated package to package file names list packageFileNames.push_back(packageFileName); @@ -217,11 +206,9 @@ int cmCPackArchiveGenerator::PackageComponentsAllInOne() DECLARE_AND_OPEN_ARCHIVE(packageFileNames[0], archive); // The ALL COMPONENTS in ONE package case - std::map<std::string, cmCPackComponent>::iterator compIt; - for (compIt = this->Components.begin(); compIt != this->Components.end(); - ++compIt) { + for (auto& comp : this->Components) { // Add the files of this component to the archive - addOneComponentToArchive(archive, &(compIt->second)); + addOneComponentToArchive(archive, &(comp.second)); } // archive goes out of scope so it will finalized and closed. @@ -249,16 +236,15 @@ int cmCPackArchiveGenerator::PackageFiles() // CASE 3 : NON COMPONENT package. DECLARE_AND_OPEN_ARCHIVE(packageFileNames[0], archive); - std::vector<std::string>::const_iterator fileIt; cmWorkingDirectory workdir(toplevel); - for (fileIt = files.begin(); fileIt != files.end(); ++fileIt) { + for (std::string const& file : files) { // Get the relative path to the file std::string rp = - cmSystemTools::RelativePath(toplevel.c_str(), fileIt->c_str()); + cmSystemTools::RelativePath(toplevel.c_str(), file.c_str()); archive.Add(rp, 0, nullptr, false); if (!archive) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem while adding file< " - << *fileIt << "> to archive <" << packageFileNames[0] + << file << "> to archive <" << packageFileNames[0] << "> .ERROR =" << archive.GetError() << std::endl); return 0; } diff --git a/Source/CPack/cmCPackArchiveGenerator.h b/Source/CPack/cmCPackArchiveGenerator.h index 72ba1b2..9983854 100644 --- a/Source/CPack/cmCPackArchiveGenerator.h +++ b/Source/CPack/cmCPackArchiveGenerator.h @@ -28,11 +28,11 @@ public: * Construct generator */ cmCPackArchiveGenerator(cmArchiveWrite::Compress, std::string const& format); - ~cmCPackArchiveGenerator() CM_OVERRIDE; + ~cmCPackArchiveGenerator() override; // Used to add a header to the archive virtual int GenerateHeader(std::ostream* os); // component support - bool SupportsComponentInstallation() const CM_OVERRIDE; + bool SupportsComponentInstallation() const override; private: // get archive component filename @@ -40,7 +40,7 @@ private: bool isGroupName); protected: - int InitializeInternal() CM_OVERRIDE; + int InitializeInternal() override; /** * Add the files belonging to the specified component * to the provided (already opened) archive. @@ -56,7 +56,7 @@ protected: * method will call either PackageComponents or * PackageComponentsAllInOne. */ - int PackageFiles() CM_OVERRIDE; + int PackageFiles() override; /** * The method used to package files when component * install is used. This will create one @@ -68,7 +68,7 @@ protected: * components will be put in a single installer. */ int PackageComponentsAllInOne(); - const char* GetOutputExtension() CM_OVERRIDE = 0; + const char* GetOutputExtension() override = 0; cmArchiveWrite::Compress Compress; std::string ArchiveFormat; }; diff --git a/Source/CPack/cmCPackBundleGenerator.cxx b/Source/CPack/cmCPackBundleGenerator.cxx index d538901..bbf2a50 100644 --- a/Source/CPack/cmCPackBundleGenerator.cxx +++ b/Source/CPack/cmCPackBundleGenerator.cxx @@ -19,7 +19,7 @@ cmCPackBundleGenerator::~cmCPackBundleGenerator() int cmCPackBundleGenerator::InitializeInternal() { const char* name = this->GetOption("CPACK_BUNDLE_NAME"); - if (0 == name) { + if (nullptr == name) { cmCPackLogger(cmCPackLog::LOG_ERROR, "CPACK_BUNDLE_NAME must be set to use the Bundle generator." << std::endl); diff --git a/Source/CPack/cmCPackBundleGenerator.h b/Source/CPack/cmCPackBundleGenerator.h index e99bf43..27bac3a 100644 --- a/Source/CPack/cmCPackBundleGenerator.h +++ b/Source/CPack/cmCPackBundleGenerator.h @@ -21,15 +21,15 @@ public: cmCPackTypeMacro(cmCPackBundleGenerator, cmCPackDragNDropGenerator); cmCPackBundleGenerator(); - ~cmCPackBundleGenerator() CM_OVERRIDE; + ~cmCPackBundleGenerator() override; protected: - int InitializeInternal() CM_OVERRIDE; - const char* GetPackagingInstallPrefix() CM_OVERRIDE; + int InitializeInternal() override; + const char* GetPackagingInstallPrefix() override; int ConstructBundle(); int SignBundle(const std::string& src_dir); - int PackageFiles() CM_OVERRIDE; - bool SupportsComponentInstallation() const CM_OVERRIDE; + int PackageFiles() override; + bool SupportsComponentInstallation() const override; std::string InstallPrefix; }; diff --git a/Source/CPack/cmCPackComponentGroup.cxx b/Source/CPack/cmCPackComponentGroup.cxx index e39398a..f888a5f 100644 --- a/Source/CPack/cmCPackComponentGroup.cxx +++ b/Source/CPack/cmCPackComponentGroup.cxx @@ -5,7 +5,6 @@ #include "cmSystemTools.h" #include <string> -#include <vector> unsigned long cmCPackComponent::GetInstalledSize( const std::string& installDir) const @@ -14,11 +13,10 @@ unsigned long cmCPackComponent::GetInstalledSize( return this->TotalSize; } - std::vector<std::string>::const_iterator fileIt; - for (fileIt = this->Files.begin(); fileIt != this->Files.end(); ++fileIt) { + for (std::string const& file : this->Files) { std::string path = installDir; path += '/'; - path += *fileIt; + path += file; this->TotalSize += cmSystemTools::FileLength(path); } diff --git a/Source/CPack/cmCPackCygwinBinaryGenerator.h b/Source/CPack/cmCPackCygwinBinaryGenerator.h index b5a0531..f87a134 100644 --- a/Source/CPack/cmCPackCygwinBinaryGenerator.h +++ b/Source/CPack/cmCPackCygwinBinaryGenerator.h @@ -17,7 +17,7 @@ public: * Construct generator */ cmCPackCygwinBinaryGenerator(); - ~cmCPackCygwinBinaryGenerator() CM_OVERRIDE; + ~cmCPackCygwinBinaryGenerator() override; protected: virtual int InitializeInternal(); diff --git a/Source/CPack/cmCPackCygwinSourceGenerator.h b/Source/CPack/cmCPackCygwinSourceGenerator.h index d19f87c..a909b15 100644 --- a/Source/CPack/cmCPackCygwinSourceGenerator.h +++ b/Source/CPack/cmCPackCygwinSourceGenerator.h @@ -17,7 +17,7 @@ public: * Construct generator */ cmCPackCygwinSourceGenerator(); - ~cmCPackCygwinSourceGenerator() CM_OVERRIDE; + ~cmCPackCygwinSourceGenerator() override; protected: const char* GetPackagingInstallPrefix(); diff --git a/Source/CPack/cmCPackDebGenerator.cxx b/Source/CPack/cmCPackDebGenerator.cxx index 18d559e..7fc3c26 100644 --- a/Source/CPack/cmCPackDebGenerator.cxx +++ b/Source/CPack/cmCPackDebGenerator.cxx @@ -12,7 +12,6 @@ #include "cm_sys_stat.h" #include "cmsys/Glob.hxx" -#include <map> #include <ostream> #include <set> #include <string.h> @@ -105,37 +104,31 @@ int cmCPackDebGenerator::PackageComponents(bool ignoreGroup) // The default behavior is to have one package by component group // unless CPACK_COMPONENTS_IGNORE_GROUP is specified. if (!ignoreGroup) { - std::map<std::string, cmCPackComponentGroup>::iterator compGIt; - for (compGIt = this->ComponentGroups.begin(); - compGIt != this->ComponentGroups.end(); ++compGIt) { - cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Packaging component group: " - << compGIt->first << std::endl); + for (auto const& compG : this->ComponentGroups) { + cmCPackLogger(cmCPackLog::LOG_VERBOSE, + "Packaging component group: " << compG.first << std::endl); // Begin the archive for this group - retval &= PackageOnePack(initialTopLevel, compGIt->first); + retval &= PackageOnePack(initialTopLevel, compG.first); } // Handle Orphan components (components not belonging to any groups) - std::map<std::string, cmCPackComponent>::iterator compIt; - for (compIt = this->Components.begin(); compIt != this->Components.end(); - ++compIt) { + for (auto const& comp : this->Components) { // Does the component belong to a group? - if (compIt->second.Group == nullptr) { + if (comp.second.Group == nullptr) { cmCPackLogger( cmCPackLog::LOG_VERBOSE, "Component <" - << compIt->second.Name + << comp.second.Name << "> does not belong to any group, package it separately." << std::endl); // Begin the archive for this orphan component - retval &= PackageOnePack(initialTopLevel, compIt->first); + retval &= PackageOnePack(initialTopLevel, comp.first); } } } // CPACK_COMPONENTS_IGNORE_GROUPS is set // We build 1 package per component else { - std::map<std::string, cmCPackComponent>::iterator compIt; - for (compIt = this->Components.begin(); compIt != this->Components.end(); - ++compIt) { - retval &= PackageOnePack(initialTopLevel, compIt->first); + for (auto const& comp : this->Components) { + retval &= PackageOnePack(initialTopLevel, comp.first); } } return retval; @@ -336,10 +329,8 @@ int cmCPackDebGenerator::createDeb() { std::string dirName = this->GetOption("CPACK_TEMPORARY_DIRECTORY"); dirName += '/'; - for (std::vector<std::string>::const_iterator fileIt = - packageFiles.begin(); - fileIt != packageFiles.end(); ++fileIt) { - totalSize += cmSystemTools::FileLength(*fileIt); + for (std::string const& file : packageFiles) { + totalSize += cmSystemTools::FileLength(file); } } out << "Installed-Size: " << (totalSize + 1023) / 1024 << "\n"; @@ -400,7 +391,7 @@ int cmCPackDebGenerator::createDeb() compression_suffix = ".gz"; tar_compression_type = cmArchiveWrite::CompressGZip; } else if (!strcmp(debian_compression_type, "none")) { - compression_suffix = ""; + compression_suffix.clear(); tar_compression_type = cmArchiveWrite::CompressNone; } else { cmCPackLogger(cmCPackLog::LOG_ERROR, @@ -446,10 +437,7 @@ int cmCPackDebGenerator::createDeb() // we have to reconstruct the parent folders as well - for (std::vector<std::string>::const_iterator fileIt = - packageFiles.begin(); - fileIt != packageFiles.end(); ++fileIt) { - std::string currentPath = *fileIt; + for (std::string currentPath : packageFiles) { while (currentPath != strGenWDIR) { // the last one IS strGenWDIR, but we do not want this one: // XXX/application/usr/bin/myprogram with GEN_WDIR=XXX/application @@ -459,18 +447,17 @@ int cmCPackDebGenerator::createDeb() } } - for (std::set<std::string>::const_iterator fileIt = orderedFiles.begin(); - fileIt != orderedFiles.end(); ++fileIt) { - cmCPackLogger(cmCPackLog::LOG_DEBUG, "FILEIT: \"" << *fileIt << "\"" + for (std::string const& file : orderedFiles) { + cmCPackLogger(cmCPackLog::LOG_DEBUG, "FILEIT: \"" << file << "\"" << std::endl); - std::string::size_type slashPos = fileIt->find('/', topLevelLength + 1); + std::string::size_type slashPos = file.find('/', topLevelLength + 1); std::string relativeDir = - fileIt->substr(topLevelLength, slashPos - topLevelLength); + file.substr(topLevelLength, slashPos - topLevelLength); cmCPackLogger(cmCPackLog::LOG_DEBUG, "RELATIVEDIR: \"" << relativeDir << "\"" << std::endl); #ifdef WIN32 - std::string mode_t_adt_filename = *fileIt + ":cmake_mode_t"; + std::string mode_t_adt_filename = file + ":cmake_mode_t"; cmsys::ifstream permissionStream(mode_t_adt_filename.c_str()); mode_t permissions = 0; @@ -481,7 +468,7 @@ int cmCPackDebGenerator::createDeb() if (permissions != 0) { data_tar.SetPermissions(permissions); - } else if (cmSystemTools::FileIsDirectory(*fileIt)) { + } else if (cmSystemTools::FileIsDirectory(file)) { data_tar.SetPermissions(0755); } else { data_tar.ClearPermissions(); @@ -489,11 +476,11 @@ int cmCPackDebGenerator::createDeb() #endif // do not recurse because the loop will do it - if (!data_tar.Add(*fileIt, topLevelLength, ".", false)) { + if (!data_tar.Add(file, topLevelLength, ".", false)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem adding file to tar:" << std::endl << "#top level directory: " << strGenWDIR << std::endl - << "#file: " << *fileIt << std::endl + << "#file: " << file << std::endl << "#error:" << data_tar.GetError() << std::endl); return 0; } @@ -508,23 +495,21 @@ int cmCPackDebGenerator::createDeb() std::string topLevelWithTrailingSlash = this->GetOption("CPACK_TEMPORARY_DIRECTORY"); topLevelWithTrailingSlash += '/'; - for (std::vector<std::string>::const_iterator fileIt = - packageFiles.begin(); - fileIt != packageFiles.end(); ++fileIt) { + for (std::string const& file : packageFiles) { // hash only regular files - if (cmSystemTools::FileIsDirectory(*fileIt) || - cmSystemTools::FileIsSymlink(*fileIt)) { + if (cmSystemTools::FileIsDirectory(file) || + cmSystemTools::FileIsSymlink(file)) { continue; } std::string output = - cmSystemTools::ComputeFileHash(*fileIt, cmCryptoHash::AlgoMD5); + cmSystemTools::ComputeFileHash(file, cmCryptoHash::AlgoMD5); if (output.empty()) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem computing the md5 of " - << *fileIt << std::endl); + << file << std::endl); } - output += " " + *fileIt + "\n"; + output += " " + file + "\n"; // debian md5sums entries are like this: // 014f3604694729f3bf19263bac599765 usr/bin/ccmake // thus strip the full path (with the trailing slash) @@ -641,9 +626,8 @@ int cmCPackDebGenerator::createDeb() std::vector<std::string> controlExtraList; cmSystemTools::ExpandListArgument(controlExtra, controlExtraList); - for (std::vector<std::string>::iterator i = controlExtraList.begin(); - i != controlExtraList.end(); ++i) { - std::string filenamename = cmsys::SystemTools::GetFilenameName(*i); + for (std::string const& i : controlExtraList) { + std::string filenamename = cmsys::SystemTools::GetFilenameName(i); std::string localcopy = strGenWDIR + "/" + filenamename; if (permissionStrictPolicy) { @@ -653,7 +637,7 @@ int cmCPackDebGenerator::createDeb() } // if we can copy the file, it means it does exist, let's add it: - if (cmsys::SystemTools::CopyFileIfDifferent(*i, localcopy)) { + if (cmsys::SystemTools::CopyFileIfDifferent(i, localcopy)) { control_tar.Add(localcopy, strGenWDIR.length(), "."); } } diff --git a/Source/CPack/cmCPackDebGenerator.h b/Source/CPack/cmCPackDebGenerator.h index 21fc3be..b4f0c79 100644 --- a/Source/CPack/cmCPackDebGenerator.h +++ b/Source/CPack/cmCPackDebGenerator.h @@ -23,7 +23,7 @@ public: * Construct generator */ cmCPackDebGenerator(); - ~cmCPackDebGenerator() CM_OVERRIDE; + ~cmCPackDebGenerator() override; static bool CanGenerate() { @@ -40,7 +40,7 @@ public: } protected: - int InitializeInternal() CM_OVERRIDE; + int InitializeInternal() override; /** * This method factors out the work done in component packaging case. */ @@ -57,11 +57,11 @@ protected: * components will be put in a single installer. */ int PackageComponentsAllInOne(const std::string& compInstDirName); - int PackageFiles() CM_OVERRIDE; - const char* GetOutputExtension() CM_OVERRIDE { return ".deb"; } - bool SupportsComponentInstallation() const CM_OVERRIDE; + int PackageFiles() override; + const char* GetOutputExtension() override { return ".deb"; } + bool SupportsComponentInstallation() const override; std::string GetComponentInstallDirNameSuffix( - const std::string& componentName) CM_OVERRIDE; + const std::string& componentName) override; private: int createDeb(); diff --git a/Source/CPack/cmCPackDragNDropGenerator.cxx b/Source/CPack/cmCPackDragNDropGenerator.cxx index 8758d32..88204c8 100644 --- a/Source/CPack/cmCPackDragNDropGenerator.cxx +++ b/Source/CPack/cmCPackDragNDropGenerator.cxx @@ -242,9 +242,9 @@ bool cmCPackDragNDropGenerator::RunCommand(std::ostringstream& command, { int exit_code = 1; - bool result = - cmSystemTools::RunSingleCommand(command.str().c_str(), output, output, - &exit_code, 0, this->GeneratorVerbose, 0); + bool result = cmSystemTools::RunSingleCommand(command.str().c_str(), output, + output, &exit_code, nullptr, + this->GeneratorVerbose, 0); if (!result || exit_code) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error executing: " << command.str() @@ -553,10 +553,10 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir, header_data.push_back(languages.size()); for (size_t i = 0; i < languages.size(); ++i) { CFStringRef language_cfstring = CFStringCreateWithCString( - NULL, languages[i].c_str(), kCFStringEncodingUTF8); + nullptr, languages[i].c_str(), kCFStringEncodingUTF8); CFStringRef iso_language = CFLocaleCreateCanonicalLanguageIdentifierFromString( - NULL, language_cfstring); + nullptr, language_cfstring); if (!iso_language) { cmCPackLogger(cmCPackLog::LOG_ERROR, languages[i] << " is not a recognized language" << std::endl); diff --git a/Source/CPack/cmCPackDragNDropGenerator.h b/Source/CPack/cmCPackDragNDropGenerator.h index 4606c3c..8565c68 100644 --- a/Source/CPack/cmCPackDragNDropGenerator.h +++ b/Source/CPack/cmCPackDragNDropGenerator.h @@ -23,20 +23,20 @@ public: cmCPackTypeMacro(cmCPackDragNDropGenerator, cmCPackGenerator); cmCPackDragNDropGenerator(); - ~cmCPackDragNDropGenerator() CM_OVERRIDE; + ~cmCPackDragNDropGenerator() override; protected: - int InitializeInternal() CM_OVERRIDE; - const char* GetOutputExtension() CM_OVERRIDE; - int PackageFiles() CM_OVERRIDE; - bool SupportsComponentInstallation() const CM_OVERRIDE; + int InitializeInternal() override; + const char* GetOutputExtension() override; + int PackageFiles() override; + bool SupportsComponentInstallation() const override; bool CopyFile(std::ostringstream& source, std::ostringstream& target); bool CreateEmptyFile(std::ostringstream& target, size_t size); bool RunCommand(std::ostringstream& command, std::string* output = 0); std::string GetComponentInstallDirNameSuffix( - const std::string& componentName) CM_OVERRIDE; + const std::string& componentName) override; int CreateDMG(const std::string& src_dir, const std::string& output_file); diff --git a/Source/CPack/cmCPackFreeBSDGenerator.cxx b/Source/CPack/cmCPackFreeBSDGenerator.cxx index ae17b79..91ae1a2 100644 --- a/Source/CPack/cmCPackFreeBSDGenerator.cxx +++ b/Source/CPack/cmCPackFreeBSDGenerator.cxx @@ -122,7 +122,7 @@ public: { } - void write_value(cmGeneratedFileStream& s) const CM_OVERRIDE + void write_value(cmGeneratedFileStream& s) const override { s << EscapeQuotes(value); } @@ -154,7 +154,7 @@ public: return *this; } - void write_value(cmGeneratedFileStream& s) const CM_OVERRIDE + void write_value(cmGeneratedFileStream& s) const override { bool with_comma = false; @@ -179,7 +179,7 @@ public: { } - void write_value(cmGeneratedFileStream& s) const CM_OVERRIDE + void write_value(cmGeneratedFileStream& s) const override { s << "{\n"; for (VList::const_iterator it = value.begin(); it != value.end(); ++it) { diff --git a/Source/CPack/cmCPackFreeBSDGenerator.h b/Source/CPack/cmCPackFreeBSDGenerator.h index 230f728..99d2e24 100644 --- a/Source/CPack/cmCPackFreeBSDGenerator.h +++ b/Source/CPack/cmCPackFreeBSDGenerator.h @@ -22,13 +22,13 @@ public: * Construct generator */ cmCPackFreeBSDGenerator(); - ~cmCPackFreeBSDGenerator() CM_OVERRIDE; + ~cmCPackFreeBSDGenerator() override; - int InitializeInternal() CM_OVERRIDE; - int PackageFiles() CM_OVERRIDE; + int InitializeInternal() override; + int PackageFiles() override; protected: - const char* GetOutputExtension() CM_OVERRIDE { return ".txz"; } + const char* GetOutputExtension() override { return ".txz"; } std::string var_lookup(const char* var_name); void write_manifest_fields(cmGeneratedFileStream&); diff --git a/Source/CPack/cmCPackGenerator.cxx b/Source/CPack/cmCPackGenerator.cxx index b65eb64..ecb5adb 100644 --- a/Source/CPack/cmCPackGenerator.cxx +++ b/Source/CPack/cmCPackGenerator.cxx @@ -6,6 +6,7 @@ #include "cmsys/Glob.hxx" #include "cmsys/RegularExpression.hxx" #include <algorithm> +#include <memory> // IWYU pragma: keep #include <utility> #include "cmCPackComponentGroup.h" @@ -17,7 +18,6 @@ #include "cmStateSnapshot.h" #include "cmWorkingDirectory.h" #include "cmXMLSafe.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" #if defined(__HAIKU__) @@ -156,7 +156,7 @@ int cmCPackGenerator::PrepareNames() } const char* algoSignature = this->GetOption("CPACK_PACKAGE_CHECKSUM"); if (algoSignature) { - if (cmCryptoHash::New(algoSignature).get() == nullptr) { + if (!cmCryptoHash::New(algoSignature)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot recognize algorithm: " << algoSignature << std::endl); return 0; @@ -248,25 +248,23 @@ int cmCPackGenerator::InstallProjectViaInstallCommands( cmSystemTools::PutEnv(tempInstallDirectoryEnv); std::vector<std::string> installCommandsVector; cmSystemTools::ExpandListArgument(installCommands, installCommandsVector); - std::vector<std::string>::iterator it; - for (it = installCommandsVector.begin(); it != installCommandsVector.end(); - ++it) { - cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << *it << std::endl); + for (std::string const& ic : installCommandsVector) { + cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << ic << std::endl); std::string output; int retVal = 1; bool resB = - cmSystemTools::RunSingleCommand(it->c_str(), &output, &output, &retVal, + cmSystemTools::RunSingleCommand(ic.c_str(), &output, &output, &retVal, nullptr, this->GeneratorVerbose, 0); if (!resB || retVal) { std::string tmpFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); tmpFile += "/InstallOutput.log"; cmGeneratedFileStream ofs(tmpFile.c_str()); - ofs << "# Run command: " << *it << std::endl + ofs << "# Run command: " << ic << std::endl << "# Output:" << std::endl << output << std::endl; cmCPackLogger( cmCPackLog::LOG_ERROR, "Problem running install command: " - << *it << std::endl + << ic << std::endl << "Please check " << tmpFile << " for errors" << std::endl); return 0; } @@ -286,12 +284,10 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories( std::vector<std::string> ignoreFilesRegexString; cmSystemTools::ExpandListArgument(cpackIgnoreFiles, ignoreFilesRegexString); - std::vector<std::string>::iterator it; - for (it = ignoreFilesRegexString.begin(); - it != ignoreFilesRegexString.end(); ++it) { + for (std::string const& ifr : ignoreFilesRegexString) { cmCPackLogger(cmCPackLog::LOG_VERBOSE, - "Create ignore files regex for: " << *it << std::endl); - ignoreFilesRegex.push_back(it->c_str()); + "Create ignore files regex for: " << ifr << std::endl); + ignoreFilesRegex.push_back(ifr.c_str()); } } const char* installDirectories = @@ -313,7 +309,7 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories( const std::string& tempDir = tempInstallDirectory; for (it = installDirectoriesVector.begin(); it != installDirectoriesVector.end(); ++it) { - std::vector<std::pair<std::string, std::string> > symlinkedFiles; + std::vector<std::pair<std::string, std::string>> symlinkedFiles; cmCPackLogger(cmCPackLog::LOG_DEBUG, "Find files" << std::endl); cmsys::Glob gl; std::string top = *it; @@ -334,15 +330,14 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories( files = gl.GetFiles(); std::vector<std::string>::iterator gfit; std::vector<cmsys::RegularExpression>::iterator regIt; - for (gfit = files.begin(); gfit != files.end(); ++gfit) { + for (std::string const& gf : files) { bool skip = false; - std::string inFile = *gfit; - if (cmSystemTools::FileIsDirectory(*gfit)) { + std::string inFile = gf; + if (cmSystemTools::FileIsDirectory(gf)) { inFile += '/'; } - for (regIt = ignoreFilesRegex.begin(); regIt != ignoreFilesRegex.end(); - ++regIt) { - if (regIt->find(inFile.c_str())) { + for (cmsys::RegularExpression& reg : ignoreFilesRegex) { + if (reg.find(inFile.c_str())) { cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Ignore file: " << inFile << std::endl); skip = true; @@ -353,7 +348,7 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories( } std::string filePath = tempDir; filePath += "/" + subdir + "/" + - cmSystemTools::RelativePath(top.c_str(), gfit->c_str()); + cmSystemTools::RelativePath(top.c_str(), gf.c_str()); cmCPackLogger(cmCPackLog::LOG_DEBUG, "Copy file: " << inFile << " -> " << filePath << std::endl); /* If the file is a symlink we will have to re-create it */ @@ -377,33 +372,30 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories( } /* rebuild symlinks in the installed tree */ if (!symlinkedFiles.empty()) { - std::vector<std::pair<std::string, std::string> >::iterator - symlinkedIt; std::string curDir = cmSystemTools::GetCurrentWorkingDirectory(); std::string goToDir = tempDir; goToDir += "/" + subdir; cmCPackLogger(cmCPackLog::LOG_DEBUG, "Change dir to: " << goToDir << std::endl); cmWorkingDirectory workdir(goToDir); - for (symlinkedIt = symlinkedFiles.begin(); - symlinkedIt != symlinkedFiles.end(); ++symlinkedIt) { + for (auto const& symlinked : symlinkedFiles) { cmCPackLogger(cmCPackLog::LOG_DEBUG, "Will create a symlink: " - << symlinkedIt->second << "--> " - << symlinkedIt->first << std::endl); + << symlinked.second << "--> " << symlinked.first + << std::endl); // make sure directory exists for symlink std::string destDir = - cmSystemTools::GetFilenamePath(symlinkedIt->second); + cmSystemTools::GetFilenamePath(symlinked.second); if (!destDir.empty() && !cmSystemTools::MakeDirectory(destDir)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot create dir: " << destDir << "\nTrying to create symlink: " - << symlinkedIt->second << "--> " - << symlinkedIt->first << std::endl); + << symlinked.second << "--> " << symlinked.first + << std::endl); } - if (!cmSystemTools::CreateSymlink(symlinkedIt->first, - symlinkedIt->second)) { + if (!cmSystemTools::CreateSymlink(symlinked.first, + symlinked.second)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot create symlink: " - << symlinkedIt->second << "--> " - << symlinkedIt->first << std::endl); + << symlinked.second << "--> " << symlinked.first + << std::endl); return 0; } } @@ -424,10 +416,7 @@ int cmCPackGenerator::InstallProjectViaInstallScript( << std::endl); std::vector<std::string> cmakeScriptsVector; cmSystemTools::ExpandListArgument(cmakeScripts, cmakeScriptsVector); - std::vector<std::string>::iterator it; - for (it = cmakeScriptsVector.begin(); it != cmakeScriptsVector.end(); - ++it) { - std::string installScript = *it; + for (std::string const& installScript : cmakeScriptsVector) { cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Install script: " << installScript << std::endl); @@ -533,10 +522,8 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( if (installTypes && *installTypes) { std::vector<std::string> installTypesVector; cmSystemTools::ExpandListArgument(installTypes, installTypesVector); - std::vector<std::string>::iterator installTypeIt; - for (installTypeIt = installTypesVector.begin(); - installTypeIt != installTypesVector.end(); ++installTypeIt) { - this->GetInstallationType(installProjectName, *installTypeIt); + for (std::string const& installType : installTypesVector) { + this->GetInstallationType(installProjectName, installType); } } @@ -546,10 +533,8 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( const char* components = this->GetOption(componentsVar); if (components && *components) { cmSystemTools::ExpandListArgument(components, componentsVector); - std::vector<std::string>::iterator compIt; - for (compIt = componentsVector.begin(); - compIt != componentsVector.end(); ++compIt) { - GetComponent(installProjectName, *compIt); + for (std::string const& comp : componentsVector) { + GetComponent(installProjectName, comp); } componentInstall = true; } @@ -610,11 +595,9 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( "- Install project: " << installProjectName << std::endl); // Run the installation for each component - std::vector<std::string>::iterator componentIt; - for (componentIt = componentsVector.begin(); - componentIt != componentsVector.end(); ++componentIt) { + for (std::string const& component : componentsVector) { std::string tempInstallDirectory = baseTempInstallDirectory; - installComponent = *componentIt; + installComponent = component; if (componentInstall) { cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Install component: " << installComponent << std::endl); @@ -627,8 +610,7 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( cm.AddCMakePaths(); cm.SetProgressCallback(cmCPackGeneratorProgress, this); cmGlobalGenerator gg(&cm); - CM_AUTO_PTR<cmMakefile> mf( - new cmMakefile(&gg, cm.GetCurrentSnapshot())); + cmMakefile mf(&gg, cm.GetCurrentSnapshot()); if (!installSubDirectory.empty() && installSubDirectory != "/" && installSubDirectory != ".") { tempInstallDirectory += installSubDirectory; @@ -674,11 +656,11 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( if (this->GetOption("CPACK_INSTALL_PREFIX")) { dir += this->GetOption("CPACK_INSTALL_PREFIX"); } - mf->AddDefinition("CMAKE_INSTALL_PREFIX", dir.c_str()); + mf.AddDefinition("CMAKE_INSTALL_PREFIX", dir.c_str()); cmCPackLogger( cmCPackLog::LOG_DEBUG, - "- Using DESTDIR + CPACK_INSTALL_PREFIX... (mf->AddDefinition)" + "- Using DESTDIR + CPACK_INSTALL_PREFIX... (mf.AddDefinition)" << std::endl); cmCPackLogger(cmCPackLog::LOG_DEBUG, "- Setting CMAKE_INSTALL_PREFIX to '" << dir << "'" @@ -715,8 +697,8 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( return 0; } } else { - mf->AddDefinition("CMAKE_INSTALL_PREFIX", - tempInstallDirectory.c_str()); + mf.AddDefinition("CMAKE_INSTALL_PREFIX", + tempInstallDirectory.c_str()); if (!cmsys::SystemTools::MakeDirectory( tempInstallDirectory.c_str())) { @@ -727,7 +709,7 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( } cmCPackLogger(cmCPackLog::LOG_DEBUG, - "- Using non-DESTDIR install... (mf->AddDefinition)" + "- Using non-DESTDIR install... (mf.AddDefinition)" << std::endl); cmCPackLogger(cmCPackLog::LOG_DEBUG, "- Setting CMAKE_INSTALL_PREFIX to '" @@ -735,19 +717,19 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( } if (!buildConfig.empty()) { - mf->AddDefinition("BUILD_TYPE", buildConfig.c_str()); + mf.AddDefinition("BUILD_TYPE", buildConfig.c_str()); } std::string installComponentLowerCase = cmSystemTools::LowerCase(installComponent); if (installComponentLowerCase != "all") { - mf->AddDefinition("CMAKE_INSTALL_COMPONENT", - installComponent.c_str()); + mf.AddDefinition("CMAKE_INSTALL_COMPONENT", + installComponent.c_str()); } // strip on TRUE, ON, 1, one or several file names, but not on // FALSE, OFF, 0 and an empty string if (!cmSystemTools::IsOff(this->GetOption("CPACK_STRIP_FILES"))) { - mf->AddDefinition("CMAKE_INSTALL_DO_STRIP", "1"); + mf.AddDefinition("CMAKE_INSTALL_DO_STRIP", "1"); } // Remember the list of files before installation // of the current component (if we are in component install) @@ -767,7 +749,7 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( // If CPack was asked to warn on ABSOLUTE INSTALL DESTINATION // then forward request to cmake_install.cmake script if (this->IsOn("CPACK_WARN_ON_ABSOLUTE_INSTALL_DESTINATION")) { - mf->AddDefinition("CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION", "1"); + mf.AddDefinition("CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION", "1"); } // If current CPack generator does support // ABSOLUTE INSTALL DESTINATION or CPack has been asked for @@ -775,18 +757,17 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( // as soon as it occurs (before installing file) if (!SupportsAbsoluteDestination() || this->IsOn("CPACK_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION")) { - mf->AddDefinition("CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION", - "1"); + mf.AddDefinition("CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION", "1"); } // do installation - int res = mf->ReadListFile(installFile.c_str()); + int res = mf.ReadListFile(installFile.c_str()); // forward definition of CMAKE_ABSOLUTE_DESTINATION_FILES // to CPack (may be used by generators like CPack RPM or DEB) // in order to transparently handle ABSOLUTE PATH - if (mf->GetDefinition("CMAKE_ABSOLUTE_DESTINATION_FILES")) { - mf->AddDefinition( + if (mf.GetDefinition("CMAKE_ABSOLUTE_DESTINATION_FILES")) { + mf.AddDefinition( "CPACK_ABSOLUTE_DESTINATION_FILES", - mf->GetDefinition("CMAKE_ABSOLUTE_DESTINATION_FILES")); + mf.GetDefinition("CMAKE_ABSOLUTE_DESTINATION_FILES")); } // Now rebuild the list of files after installation @@ -820,12 +801,12 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( } } - if (nullptr != mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES")) { + if (nullptr != mf.GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES")) { if (!absoluteDestFiles.empty()) { absoluteDestFiles += ";"; } absoluteDestFiles += - mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES"); + mf.GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES"); cmCPackLogger(cmCPackLog::LOG_DEBUG, "Got some ABSOLUTE DESTINATION FILES: " << absoluteDestFiles << std::endl); @@ -839,13 +820,13 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( this->GetOption(absoluteDestFileComponent); absoluteDestFilesListComponent += ";"; absoluteDestFilesListComponent += - mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES"); + mf.GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES"); this->SetOption(absoluteDestFileComponent, absoluteDestFilesListComponent.c_str()); } else { this->SetOption( absoluteDestFileComponent, - mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES")); + mf.GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES")); } } } @@ -981,7 +962,7 @@ int cmCPackGenerator::DoPackage() /* Prepare checksum algorithm*/ const char* algo = this->GetOption("CPACK_PACKAGE_CHECKSUM"); - CM_AUTO_PTR<cmCryptoHash> crypto = cmCryptoHash::New(algo ? algo : ""); + std::unique_ptr<cmCryptoHash> crypto = cmCryptoHash::New(algo ? algo : ""); /* * Copy the generated packages to final destination @@ -991,12 +972,11 @@ int cmCPackGenerator::DoPackage() */ cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Copying final package(s) [" << packageFileNames.size() << "]:" << std::endl); - std::vector<std::string>::iterator it; /* now copy package one by one */ - for (it = packageFileNames.begin(); it != packageFileNames.end(); ++it) { + for (std::string const& pkgFileName : packageFileNames) { std::string tmpPF(this->GetOption("CPACK_OUTPUT_FILE_PREFIX")); - std::string filename(cmSystemTools::GetFilenameName(*it)); - tempPackageFileName = it->c_str(); + std::string filename(cmSystemTools::GetFilenameName(pkgFileName)); + tempPackageFileName = pkgFileName.c_str(); tmpPF += "/" + filename; const char* packageFileName = tmpPF.c_str(); cmCPackLogger(cmCPackLog::LOG_DEBUG, "Copy final package(s): " @@ -1015,10 +995,9 @@ int cmCPackGenerator::DoPackage() << packageFileName << " generated." << std::endl); /* Generate checksum file */ - if (crypto.get() != nullptr) { + if (crypto) { std::string hashFile(this->GetOption("CPACK_OUTPUT_FILE_PREFIX")); - hashFile += - "/" + filename.substr(0, filename.rfind(this->GetOutputExtension())); + hashFile += "/" + filename; hashFile += "." + cmSystemTools::LowerCase(algo); cmsys::ofstream outF(hashFile.c_str()); if (!outF) { @@ -1420,10 +1399,9 @@ cmCPackComponent* cmCPackGenerator::GetComponent( std::vector<std::string> installTypesVector; cmSystemTools::ExpandListArgument(installTypes, installTypesVector); std::vector<std::string>::iterator installTypesIt; - for (installTypesIt = installTypesVector.begin(); - installTypesIt != installTypesVector.end(); ++installTypesIt) { + for (std::string const& installType : installTypesVector) { component->InstallationTypes.push_back( - this->GetInstallationType(projectName, *installTypesIt)); + this->GetInstallationType(projectName, installType)); } } @@ -1433,9 +1411,8 @@ cmCPackComponent* cmCPackGenerator::GetComponent( std::vector<std::string> dependsVector; cmSystemTools::ExpandListArgument(depends, dependsVector); std::vector<std::string>::iterator dependIt; - for (dependIt = dependsVector.begin(); dependIt != dependsVector.end(); - ++dependIt) { - cmCPackComponent* child = GetComponent(projectName, *dependIt); + for (std::string const& depend : dependsVector) { + cmCPackComponent* child = GetComponent(projectName, depend); component->Dependencies.push_back(child); child->ReverseDependencies.push_back(component); } diff --git a/Source/CPack/cmCPackGenerator.h b/Source/CPack/cmCPackGenerator.h index 194d4e5..4e3a6e0 100644 --- a/Source/CPack/cmCPackGenerator.h +++ b/Source/CPack/cmCPackGenerator.h @@ -299,7 +299,7 @@ private: #define cmCPackTypeMacro(klass, superclass) \ typedef superclass Superclass; \ - const char* GetNameOfClass() CM_OVERRIDE { return #klass; } \ + const char* GetNameOfClass() override { return #klass; } \ static cmCPackGenerator* CreateGenerator() { return new klass; } \ class cmCPackTypeMacro_UseTrailingSemicolon diff --git a/Source/CPack/cmCPackNSISGenerator.cxx b/Source/CPack/cmCPackNSISGenerator.cxx index d04ea13..ddf104c 100644 --- a/Source/CPack/cmCPackNSISGenerator.cxx +++ b/Source/CPack/cmCPackNSISGenerator.cxx @@ -59,11 +59,10 @@ int cmCPackNSISGenerator::PackageFiles() std::string nsisInstallOptions = nsisFileName + "/NSIS.InstallOptions.ini"; nsisFileName += "/project.nsi"; std::ostringstream str; - std::vector<std::string>::const_iterator it; - for (it = files.begin(); it != files.end(); ++it) { + for (std::string const& file : files) { std::string outputDir = "$INSTDIR"; std::string fileN = - cmSystemTools::RelativePath(toplevel.c_str(), it->c_str()); + cmSystemTools::RelativePath(toplevel.c_str(), file.c_str()); if (!this->Components.empty()) { const std::string::size_type pos = fileN.find('/'); @@ -87,12 +86,11 @@ int cmCPackNSISGenerator::PackageFiles() this->SetOptionIfNotSet("CPACK_NSIS_DELETE_FILES", str.str().c_str()); std::vector<std::string> dirs; this->GetListOfSubdirectories(toplevel.c_str(), dirs); - std::vector<std::string>::const_iterator sit; std::ostringstream dstr; - for (sit = dirs.begin(); sit != dirs.end(); ++sit) { + for (std::string const& dir : dirs) { std::string componentName; std::string fileN = - cmSystemTools::RelativePath(toplevel.c_str(), sit->c_str()); + cmSystemTools::RelativePath(toplevel.c_str(), dir.c_str()); if (fileN.empty()) { continue; } @@ -205,65 +203,57 @@ int cmCPackNSISGenerator::PackageFiles() // in a vector based on the indices, and print them in that order. std::vector<cmCPackInstallationType*> installTypes( this->InstallationTypes.size()); - std::map<std::string, cmCPackInstallationType>::iterator installTypeIt; - for (installTypeIt = this->InstallationTypes.begin(); - installTypeIt != this->InstallationTypes.end(); ++installTypeIt) { - installTypes[installTypeIt->second.Index - 1] = &installTypeIt->second; - } - std::vector<cmCPackInstallationType*>::iterator installTypeIt2; - for (installTypeIt2 = installTypes.begin(); - installTypeIt2 != installTypes.end(); ++installTypeIt2) { + for (auto& installType : this->InstallationTypes) { + installTypes[installType.second.Index - 1] = &installType.second; + } + for (cmCPackInstallationType* installType : installTypes) { installTypesCode += "InstType \""; - installTypesCode += (*installTypeIt2)->DisplayName; + installTypesCode += installType->DisplayName; installTypesCode += "\"\n"; } // Create installation groups first - std::map<std::string, cmCPackComponentGroup>::iterator groupIt; - for (groupIt = this->ComponentGroups.begin(); - groupIt != this->ComponentGroups.end(); ++groupIt) { - if (groupIt->second.ParentGroup == nullptr) { + for (auto& group : this->ComponentGroups) { + if (group.second.ParentGroup == nullptr) { componentCode += - this->CreateComponentGroupDescription(&groupIt->second, macrosOut); + this->CreateComponentGroupDescription(&group.second, macrosOut); } // Add the group description, if any. - if (!groupIt->second.Description.empty()) { + if (!group.second.Description.empty()) { groupDescriptions += " !insertmacro MUI_DESCRIPTION_TEXT ${" + - groupIt->first + "} \"" + - this->TranslateNewlines(groupIt->second.Description) + "\"\n"; + group.first + "} \"" + + this->TranslateNewlines(group.second.Description) + "\"\n"; } } // Create the remaining components, which aren't associated with groups. - std::map<std::string, cmCPackComponent>::iterator compIt; - for (compIt = this->Components.begin(); compIt != this->Components.end(); - ++compIt) { - if (compIt->second.Files.empty()) { + for (auto& comp : this->Components) { + if (comp.second.Files.empty()) { // NSIS cannot cope with components that have no files. continue; } anyDownloadedComponents = - anyDownloadedComponents || compIt->second.IsDownloaded; + anyDownloadedComponents || comp.second.IsDownloaded; - if (!compIt->second.Group) { + if (!comp.second.Group) { componentCode += - this->CreateComponentDescription(&compIt->second, macrosOut); + this->CreateComponentDescription(&comp.second, macrosOut); } // Add this component to the various section lists. sectionList += " !insertmacro \"${MacroName}\" \""; - sectionList += compIt->first; + sectionList += comp.first; sectionList += "\"\n"; - selectedVarsList += "Var " + compIt->first + "_selected\n"; - selectedVarsList += "Var " + compIt->first + "_was_installed\n"; + selectedVarsList += "Var " + comp.first + "_selected\n"; + selectedVarsList += "Var " + comp.first + "_was_installed\n"; // Add the component description, if any. - if (!compIt->second.Description.empty()) { + if (!comp.second.Description.empty()) { componentDescriptions += " !insertmacro MUI_DESCRIPTION_TEXT ${" + - compIt->first + "} \"" + - this->TranslateNewlines(compIt->second.Description) + "\"\n"; + comp.first + "} \"" + + this->TranslateNewlines(comp.second.Description) + "\"\n"; } } @@ -463,11 +453,9 @@ int cmCPackNSISGenerator::InitializeInternal() cmSystemTools::ExpandListArgument(cpackPackageDeskTopLinks, cpackPackageDesktopLinksVector); - for (std::vector<std::string>::iterator i = - cpackPackageDesktopLinksVector.begin(); - i != cpackPackageDesktopLinksVector.end(); ++i) { + for (std::string const& cpdl : cpackPackageDesktopLinksVector) { cmCPackLogger(cmCPackLog::LOG_DEBUG, - "CPACK_CREATE_DESKTOP_LINKS: " << *i << std::endl); + "CPACK_CREATE_DESKTOP_LINKS: " << cpdl << std::endl); } } else { cmCPackLogger(cmCPackLog::LOG_DEBUG, "CPACK_CREATE_DESKTOP_LINKS: " @@ -647,11 +635,9 @@ std::string cmCPackNSISGenerator::CreateComponentDescription( componentCode += " SectionIn RO\n"; } else if (!component->InstallationTypes.empty()) { std::ostringstream out; - std::vector<cmCPackInstallationType*>::iterator installTypeIter; - for (installTypeIter = component->InstallationTypes.begin(); - installTypeIter != component->InstallationTypes.end(); - ++installTypeIter) { - out << " " << (*installTypeIter)->Index; + for (cmCPackInstallationType const* installType : + component->InstallationTypes) { + out << " " << installType->Index; } componentCode += " SectionIn" + out.str() + "\n"; } @@ -730,19 +716,17 @@ std::string cmCPackNSISGenerator::CreateComponentDescription( unsigned long totalSize = 0; { // the scope is needed for cmGeneratedFileStream cmGeneratedFileStream out(zipListFileName.c_str()); - std::vector<std::string>::iterator fileIt; - for (fileIt = component->Files.begin(); fileIt != component->Files.end(); - ++fileIt) { + for (std::string const& file : component->Files) { if (needQuotesInFile) { out << "\""; } - out << *fileIt; + out << file; if (needQuotesInFile) { out << "\""; } out << std::endl; - totalSize += cmSystemTools::FileLength(dirName + *fileIt); + totalSize += cmSystemTools::FileLength(dirName + file); } } @@ -798,17 +782,14 @@ std::string cmCPackNSISGenerator::CreateComponentDescription( macrosOut << "!macro Remove_${" << component->Name << "}\n"; macrosOut << " IntCmp $" << component->Name << "_was_installed 0 noremove_" << component->Name << "\n"; - std::vector<std::string>::iterator pathIt; std::string path; - for (pathIt = component->Files.begin(); pathIt != component->Files.end(); - ++pathIt) { - path = *pathIt; + for (std::string const& pathIt : component->Files) { + path = pathIt; std::replace(path.begin(), path.end(), '/', '\\'); macrosOut << " Delete \"" << componentOutputDir << "\\" << path << "\"\n"; } - for (pathIt = component->Directories.begin(); - pathIt != component->Directories.end(); ++pathIt) { - path = *pathIt; + for (std::string const& pathIt : component->Directories) { + path = pathIt; std::replace(path.begin(), path.end(), '/', '\\'); macrosOut << " RMDir \"" << componentOutputDir << "\\" << path << "\"\n"; } @@ -841,17 +822,14 @@ std::string cmCPackNSISGenerator::CreateSelectionDependenciesDescription( visited.insert(component); std::ostringstream out; - std::vector<cmCPackComponent*>::iterator dependIt; - for (dependIt = component->Dependencies.begin(); - dependIt != component->Dependencies.end(); ++dependIt) { + for (cmCPackComponent* depend : component->Dependencies) { // Write NSIS code to select this dependency - out << " SectionGetFlags ${" << (*dependIt)->Name << "} $0\n"; + out << " SectionGetFlags ${" << depend->Name << "} $0\n"; out << " IntOp $0 $0 | ${SF_SELECTED}\n"; - out << " SectionSetFlags ${" << (*dependIt)->Name << "} $0\n"; - out << " IntOp $" << (*dependIt)->Name - << "_selected 0 + ${SF_SELECTED}\n"; + out << " SectionSetFlags ${" << depend->Name << "} $0\n"; + out << " IntOp $" << depend->Name << "_selected 0 + ${SF_SELECTED}\n"; // Recurse - out << CreateSelectionDependenciesDescription(*dependIt, visited).c_str(); + out << CreateSelectionDependenciesDescription(depend, visited).c_str(); } return out.str(); @@ -867,19 +845,16 @@ std::string cmCPackNSISGenerator::CreateDeselectionDependenciesDescription( visited.insert(component); std::ostringstream out; - std::vector<cmCPackComponent*>::iterator dependIt; - for (dependIt = component->ReverseDependencies.begin(); - dependIt != component->ReverseDependencies.end(); ++dependIt) { + for (cmCPackComponent* depend : component->ReverseDependencies) { // Write NSIS code to deselect this dependency - out << " SectionGetFlags ${" << (*dependIt)->Name << "} $0\n"; + out << " SectionGetFlags ${" << depend->Name << "} $0\n"; out << " IntOp $1 ${SF_SELECTED} ~\n"; out << " IntOp $0 $0 & $1\n"; - out << " SectionSetFlags ${" << (*dependIt)->Name << "} $0\n"; - out << " IntOp $" << (*dependIt)->Name << "_selected 0 + 0\n"; + out << " SectionSetFlags ${" << depend->Name << "} $0\n"; + out << " IntOp $" << depend->Name << "_selected 0 + 0\n"; // Recurse - out - << CreateDeselectionDependenciesDescription(*dependIt, visited).c_str(); + out << CreateDeselectionDependenciesDescription(depend, visited).c_str(); } return out.str(); @@ -903,20 +878,16 @@ std::string cmCPackNSISGenerator::CreateComponentGroupDescription( code += "\"" + group->DisplayName + "\" " + group->Name + "\n"; } - std::vector<cmCPackComponentGroup*>::iterator groupIt; - for (groupIt = group->Subgroups.begin(); groupIt != group->Subgroups.end(); - ++groupIt) { - code += this->CreateComponentGroupDescription(*groupIt, macrosOut); + for (cmCPackComponentGroup* g : group->Subgroups) { + code += this->CreateComponentGroupDescription(g, macrosOut); } - std::vector<cmCPackComponent*>::iterator comp; - for (comp = group->Components.begin(); comp != group->Components.end(); - ++comp) { - if ((*comp)->Files.empty()) { + for (cmCPackComponent* comp : group->Components) { + if (comp->Files.empty()) { continue; } - code += this->CreateComponentDescription(*comp, macrosOut); + code += this->CreateComponentDescription(comp, macrosOut); } code += "SectionGroupEnd\n"; return code; diff --git a/Source/CPack/cmCPackNSISGenerator.h b/Source/CPack/cmCPackNSISGenerator.h index bdd1955..fc9ad9a 100644 --- a/Source/CPack/cmCPackNSISGenerator.h +++ b/Source/CPack/cmCPackNSISGenerator.h @@ -34,22 +34,22 @@ public: * Construct generator */ cmCPackNSISGenerator(bool nsis64 = false); - ~cmCPackNSISGenerator() CM_OVERRIDE; + ~cmCPackNSISGenerator() override; protected: - int InitializeInternal() CM_OVERRIDE; + int InitializeInternal() override; void CreateMenuLinks(std::ostream& str, std::ostream& deleteStr); - int PackageFiles() CM_OVERRIDE; - const char* GetOutputExtension() CM_OVERRIDE { return ".exe"; } - const char* GetOutputPostfix() CM_OVERRIDE { return "win32"; } + int PackageFiles() override; + const char* GetOutputExtension() override { return ".exe"; } + const char* GetOutputPostfix() override { return "win32"; } bool GetListOfSubdirectories(const char* dir, std::vector<std::string>& dirs); - enum cmCPackGenerator::CPackSetDestdirSupport SupportsSetDestdir() const - CM_OVERRIDE; - bool SupportsAbsoluteDestination() const CM_OVERRIDE; - bool SupportsComponentInstallation() const CM_OVERRIDE; + enum cmCPackGenerator::CPackSetDestdirSupport SupportsSetDestdir() + const override; + bool SupportsAbsoluteDestination() const override; + bool SupportsComponentInstallation() const override; /// Produce a string that contains the NSIS code to describe a /// particular component. Any added macros will be emitted via diff --git a/Source/CPack/cmCPackOSXX11Generator.cxx b/Source/CPack/cmCPackOSXX11Generator.cxx index 8ea88a8..e75061e 100644 --- a/Source/CPack/cmCPackOSXX11Generator.cxx +++ b/Source/CPack/cmCPackOSXX11Generator.cxx @@ -154,9 +154,9 @@ int cmCPackOSXX11Generator::PackageFiles() int numTries = 10; bool res = false; while (numTries > 0) { - res = - cmSystemTools::RunSingleCommand(dmgCmd.str().c_str(), &output, &output, - &retVal, 0, this->GeneratorVerbose, 0); + res = cmSystemTools::RunSingleCommand(dmgCmd.str().c_str(), &output, + &output, &retVal, nullptr, + this->GeneratorVerbose, 0); if (res && !retVal) { numTries = -1; break; diff --git a/Source/CPack/cmCPackOSXX11Generator.h b/Source/CPack/cmCPackOSXX11Generator.h index 0a1f686..a6461c8 100644 --- a/Source/CPack/cmCPackOSXX11Generator.h +++ b/Source/CPack/cmCPackOSXX11Generator.h @@ -23,13 +23,13 @@ public: * Construct generator */ cmCPackOSXX11Generator(); - ~cmCPackOSXX11Generator() CM_OVERRIDE; + ~cmCPackOSXX11Generator() override; protected: - virtual int InitializeInternal() CM_OVERRIDE; - int PackageFiles() CM_OVERRIDE; - const char* GetPackagingInstallPrefix() CM_OVERRIDE; - const char* GetOutputExtension() CM_OVERRIDE { return ".dmg"; } + virtual int InitializeInternal() override; + int PackageFiles() override; + const char* GetPackagingInstallPrefix() override; + const char* GetOutputExtension() override { return ".dmg"; } // bool CopyCreateResourceFile(const std::string& name, // const std::string& dir); diff --git a/Source/CPack/cmCPackPKGGenerator.cxx b/Source/CPack/cmCPackPKGGenerator.cxx index 70ae267..321b6a7 100644 --- a/Source/CPack/cmCPackPKGGenerator.cxx +++ b/Source/CPack/cmCPackPKGGenerator.cxx @@ -70,7 +70,7 @@ void cmCPackPKGGenerator::WriteDistributionFile(const char* metapackageFile) std::map<std::string, cmCPackComponentGroup>::iterator groupIt; for (groupIt = this->ComponentGroups.begin(); groupIt != this->ComponentGroups.end(); ++groupIt) { - if (groupIt->second.ParentGroup == 0) { + if (groupIt->second.ParentGroup == nullptr) { CreateChoiceOutline(groupIt->second, xout); } } diff --git a/Source/CPack/cmCPackPKGGenerator.h b/Source/CPack/cmCPackPKGGenerator.h index aef795f..69286ff 100644 --- a/Source/CPack/cmCPackPKGGenerator.h +++ b/Source/CPack/cmCPackPKGGenerator.h @@ -27,13 +27,13 @@ public: * Construct generator */ cmCPackPKGGenerator(); - ~cmCPackPKGGenerator() CM_OVERRIDE; + ~cmCPackPKGGenerator() override; - bool SupportsComponentInstallation() const CM_OVERRIDE; + bool SupportsComponentInstallation() const override; protected: - int InitializeInternal() CM_OVERRIDE; - const char* GetOutputPostfix() CM_OVERRIDE { return "darwin"; } + int InitializeInternal() override; + const char* GetOutputPostfix() override { return "darwin"; } // Copies or creates the resource file with the given name to the // package or package staging directory dirName. The variable diff --git a/Source/CPack/cmCPackPackageMakerGenerator.cxx b/Source/CPack/cmCPackPackageMakerGenerator.cxx index 8db7cfb..6624b16 100644 --- a/Source/CPack/cmCPackPackageMakerGenerator.cxx +++ b/Source/CPack/cmCPackPackageMakerGenerator.cxx @@ -294,9 +294,9 @@ int cmCPackPackageMakerGenerator::PackageFiles() int numTries = 10; bool res = false; while (numTries > 0) { - res = - cmSystemTools::RunSingleCommand(dmgCmd.str().c_str(), &output, &output, - &retVal, 0, this->GeneratorVerbose, 0); + res = cmSystemTools::RunSingleCommand(dmgCmd.str().c_str(), &output, + &output, &retVal, nullptr, + this->GeneratorVerbose, 0); if (res && !retVal) { numTries = -1; break; @@ -466,7 +466,7 @@ bool cmCPackPackageMakerGenerator::RunPackageMaker(const char* command, std::string output; int retVal = 1; bool res = cmSystemTools::RunSingleCommand( - command, &output, &output, &retVal, 0, this->GeneratorVerbose, 0); + command, &output, &output, &retVal, nullptr, this->GeneratorVerbose, 0); cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Done running package maker" << std::endl); if (!res || retVal) { diff --git a/Source/CPack/cmCPackPackageMakerGenerator.h b/Source/CPack/cmCPackPackageMakerGenerator.h index a2f58ff..0575587 100644 --- a/Source/CPack/cmCPackPackageMakerGenerator.h +++ b/Source/CPack/cmCPackPackageMakerGenerator.h @@ -25,13 +25,13 @@ public: * Construct generator */ cmCPackPackageMakerGenerator(); - ~cmCPackPackageMakerGenerator() CM_OVERRIDE; - bool SupportsComponentInstallation() const CM_OVERRIDE; + ~cmCPackPackageMakerGenerator() override; + bool SupportsComponentInstallation() const override; protected: - int InitializeInternal() CM_OVERRIDE; - int PackageFiles() CM_OVERRIDE; - const char* GetOutputExtension() CM_OVERRIDE { return ".dmg"; } + int InitializeInternal() override; + int PackageFiles() override; + const char* GetOutputExtension() override { return ".dmg"; } // Run PackageMaker with the given command line, which will (if // successful) produce the given package file. Returns true if diff --git a/Source/CPack/cmCPackProductBuildGenerator.cxx b/Source/CPack/cmCPackProductBuildGenerator.cxx index 1389eaa..ed4463c 100644 --- a/Source/CPack/cmCPackProductBuildGenerator.cxx +++ b/Source/CPack/cmCPackProductBuildGenerator.cxx @@ -54,7 +54,7 @@ int cmCPackProductBuildGenerator::PackageFiles() } else { if (!this->GenerateComponentPackage(basePackageDir, this->GetOption("CPACK_PACKAGE_NAME"), - toplevel, NULL)) { + toplevel, nullptr)) { return 0; } } @@ -145,9 +145,9 @@ bool cmCPackProductBuildGenerator::RunProductBuild(const std::string& command) cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << command << std::endl); std::string output, error_output; int retVal = 1; - bool res = - cmSystemTools::RunSingleCommand(command.c_str(), &output, &error_output, - &retVal, 0, this->GeneratorVerbose, 0); + bool res = cmSystemTools::RunSingleCommand(command.c_str(), &output, + &error_output, &retVal, nullptr, + this->GeneratorVerbose, 0); cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Done running command" << std::endl); if (!res || retVal) { cmGeneratedFileStream ofs(tmpFile.c_str()); @@ -174,7 +174,7 @@ bool cmCPackProductBuildGenerator::GenerateComponentPackage( cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Building component package: " << packageFile << std::endl); - const char* comp_name = component ? component->Name.c_str() : NULL; + const char* comp_name = component ? component->Name.c_str() : nullptr; const char* preflight = this->GetComponentScript("PREFLIGHT", comp_name); const char* postflight = this->GetComponentScript("POSTFLIGHT", comp_name); diff --git a/Source/CPack/cmCPackProductBuildGenerator.h b/Source/CPack/cmCPackProductBuildGenerator.h index 984dcaa..015fe4a 100644 --- a/Source/CPack/cmCPackProductBuildGenerator.h +++ b/Source/CPack/cmCPackProductBuildGenerator.h @@ -25,12 +25,12 @@ public: * Construct generator */ cmCPackProductBuildGenerator(); - ~cmCPackProductBuildGenerator() CM_OVERRIDE; + ~cmCPackProductBuildGenerator() override; protected: - int InitializeInternal() CM_OVERRIDE; - int PackageFiles() CM_OVERRIDE; - const char* GetOutputExtension() CM_OVERRIDE { return ".pkg"; } + int InitializeInternal() override; + int PackageFiles() override; + const char* GetOutputExtension() override { return ".pkg"; } // Run ProductBuild with the given command line, which will (if // successful) produce the given package file. Returns true if diff --git a/Source/CPack/cmCPackRPMGenerator.h b/Source/CPack/cmCPackRPMGenerator.h index bfba289..27d3b63 100644 --- a/Source/CPack/cmCPackRPMGenerator.h +++ b/Source/CPack/cmCPackRPMGenerator.h @@ -26,7 +26,7 @@ public: * Construct generator */ cmCPackRPMGenerator(); - ~cmCPackRPMGenerator() CM_OVERRIDE; + ~cmCPackRPMGenerator() override; static bool CanGenerate() { @@ -43,8 +43,8 @@ public: } protected: - int InitializeInternal() CM_OVERRIDE; - int PackageFiles() CM_OVERRIDE; + int InitializeInternal() override; + int PackageFiles() override; /** * This method factors out the work done in component packaging case. */ @@ -61,10 +61,10 @@ protected: * components will be put in a single installer. */ int PackageComponentsAllInOne(const std::string& compInstDirName); - const char* GetOutputExtension() CM_OVERRIDE { return ".rpm"; } - bool SupportsComponentInstallation() const CM_OVERRIDE; + const char* GetOutputExtension() override { return ".rpm"; } + bool SupportsComponentInstallation() const override; std::string GetComponentInstallDirNameSuffix( - const std::string& componentName) CM_OVERRIDE; + const std::string& componentName) override; void AddGeneratedPackageNames(); }; diff --git a/Source/CPack/cmCPackSTGZGenerator.cxx b/Source/CPack/cmCPackSTGZGenerator.cxx index c541614..3d7fd3c 100644 --- a/Source/CPack/cmCPackSTGZGenerator.cxx +++ b/Source/CPack/cmCPackSTGZGenerator.cxx @@ -6,7 +6,6 @@ #include <sstream> #include <stdio.h> #include <string> -#include <vector> #include "cmCPackGenerator.h" #include "cmCPackLog.h" @@ -48,9 +47,8 @@ int cmCPackSTGZGenerator::PackageFiles() * have generated several packages (component packaging) * so we must iterate over generated packages. */ - for (std::vector<std::string>::iterator it = packageFileNames.begin(); - it != packageFileNames.end(); ++it) { - retval &= cmSystemTools::SetPermissions((*it).c_str(), + for (std::string const& pfn : packageFileNames) { + retval &= cmSystemTools::SetPermissions(pfn.c_str(), #if defined(_MSC_VER) || defined(__MINGW32__) S_IREAD | S_IWRITE | S_IEXEC #else diff --git a/Source/CPack/cmCPackSTGZGenerator.h b/Source/CPack/cmCPackSTGZGenerator.h index 72f525c..9cf184b 100644 --- a/Source/CPack/cmCPackSTGZGenerator.h +++ b/Source/CPack/cmCPackSTGZGenerator.h @@ -23,13 +23,13 @@ public: * Construct generator */ cmCPackSTGZGenerator(); - ~cmCPackSTGZGenerator() CM_OVERRIDE; + ~cmCPackSTGZGenerator() override; protected: - int PackageFiles() CM_OVERRIDE; - int InitializeInternal() CM_OVERRIDE; - int GenerateHeader(std::ostream* os) CM_OVERRIDE; - const char* GetOutputExtension() CM_OVERRIDE { return ".sh"; } + int PackageFiles() override; + int InitializeInternal() override; + int GenerateHeader(std::ostream* os) override; + const char* GetOutputExtension() override { return ".sh"; } }; #endif diff --git a/Source/CPack/cmCPackTGZGenerator.h b/Source/CPack/cmCPackTGZGenerator.h index e904ab5..7be3d9d 100644 --- a/Source/CPack/cmCPackTGZGenerator.h +++ b/Source/CPack/cmCPackTGZGenerator.h @@ -20,10 +20,10 @@ public: * Construct generator */ cmCPackTGZGenerator(); - ~cmCPackTGZGenerator() CM_OVERRIDE; + ~cmCPackTGZGenerator() override; protected: - const char* GetOutputExtension() CM_OVERRIDE { return ".tar.gz"; } + const char* GetOutputExtension() override { return ".tar.gz"; } }; #endif diff --git a/Source/CPack/cmCPackTXZGenerator.h b/Source/CPack/cmCPackTXZGenerator.h index f38758d..4aa5973 100644 --- a/Source/CPack/cmCPackTXZGenerator.h +++ b/Source/CPack/cmCPackTXZGenerator.h @@ -20,10 +20,10 @@ public: * Construct generator */ cmCPackTXZGenerator(); - ~cmCPackTXZGenerator() CM_OVERRIDE; + ~cmCPackTXZGenerator() override; protected: - const char* GetOutputExtension() CM_OVERRIDE { return ".tar.xz"; } + const char* GetOutputExtension() override { return ".tar.xz"; } }; #endif diff --git a/Source/CPack/cmCPackTarBZip2Generator.h b/Source/CPack/cmCPackTarBZip2Generator.h index f3dd953..7975dda 100644 --- a/Source/CPack/cmCPackTarBZip2Generator.h +++ b/Source/CPack/cmCPackTarBZip2Generator.h @@ -19,10 +19,10 @@ public: * Construct generator */ cmCPackTarBZip2Generator(); - ~cmCPackTarBZip2Generator() CM_OVERRIDE; + ~cmCPackTarBZip2Generator() override; protected: - const char* GetOutputExtension() CM_OVERRIDE { return ".tar.bz2"; } + const char* GetOutputExtension() override { return ".tar.bz2"; } }; #endif diff --git a/Source/CPack/cmCPackTarCompressGenerator.h b/Source/CPack/cmCPackTarCompressGenerator.h index 8eedb24..37c7f48 100644 --- a/Source/CPack/cmCPackTarCompressGenerator.h +++ b/Source/CPack/cmCPackTarCompressGenerator.h @@ -19,10 +19,10 @@ public: * Construct generator */ cmCPackTarCompressGenerator(); - ~cmCPackTarCompressGenerator() CM_OVERRIDE; + ~cmCPackTarCompressGenerator() override; protected: - const char* GetOutputExtension() CM_OVERRIDE { return ".tar.Z"; } + const char* GetOutputExtension() override { return ".tar.Z"; } }; #endif diff --git a/Source/CPack/cmCPackZIPGenerator.h b/Source/CPack/cmCPackZIPGenerator.h index 2f81c65..58ec79e 100644 --- a/Source/CPack/cmCPackZIPGenerator.h +++ b/Source/CPack/cmCPackZIPGenerator.h @@ -20,10 +20,10 @@ public: * Construct generator */ cmCPackZIPGenerator(); - ~cmCPackZIPGenerator() CM_OVERRIDE; + ~cmCPackZIPGenerator() override; protected: - const char* GetOutputExtension() CM_OVERRIDE { return ".zip"; } + const char* GetOutputExtension() override { return ".zip"; } }; #endif diff --git a/Source/CPack/cpack.cxx b/Source/CPack/cpack.cxx index 9970721..f2c54fc 100644 --- a/Source/CPack/cpack.cxx +++ b/Source/CPack/cpack.cxx @@ -5,6 +5,7 @@ #include "cmsys/Encoding.hxx" #include <iostream> #include <map> +#include <memory> // IWYU pragma: keep #include <sstream> #include <stddef.h> #include <string> @@ -24,7 +25,6 @@ #include "cmMakefile.h" #include "cmStateSnapshot.h" #include "cmSystemTools.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" static const char* cmDocumentationName[][2] = { @@ -135,7 +135,7 @@ int main(int argc, char const* const* argv) cpackDefinitions definitions; definitions.Log = &log; - cpackConfigFile = ""; + cpackConfigFile.clear(); cmsys::CommandLineArguments arg; arg.Initialize(argc, argv); @@ -192,8 +192,7 @@ int main(int argc, char const* const* argv) cminst.SetHomeOutputDirectory(""); cminst.GetCurrentSnapshot().SetDefaultDefinitions(); cmGlobalGenerator cmgg(&cminst); - CM_AUTO_PTR<cmMakefile> globalMF( - new cmMakefile(&cmgg, cminst.GetCurrentSnapshot())); + cmMakefile globalMF(&cmgg, cminst.GetCurrentSnapshot()); #if defined(__CYGWIN__) globalMF->AddDefinition("CMAKE_LEGACY_CYGWIN_WIN32", "0"); #endif @@ -225,16 +224,16 @@ int main(int argc, char const* const* argv) // find out which system cpack is running on, so it can setup the search // paths, so FIND_XXX() commands can be used in scripts std::string systemFile = - globalMF->GetModulesFile("CMakeDetermineSystem.cmake"); - if (!globalMF->ReadListFile(systemFile.c_str())) { + globalMF.GetModulesFile("CMakeDetermineSystem.cmake"); + if (!globalMF.ReadListFile(systemFile.c_str())) { cmCPack_Log(&log, cmCPackLog::LOG_ERROR, "Error reading CMakeDetermineSystem.cmake" << std::endl); return 1; } systemFile = - globalMF->GetModulesFile("CMakeSystemSpecificInformation.cmake"); - if (!globalMF->ReadListFile(systemFile.c_str())) { + globalMF.GetModulesFile("CMakeSystemSpecificInformation.cmake"); + if (!globalMF.ReadListFile(systemFile.c_str())) { cmCPack_Log(&log, cmCPackLog::LOG_ERROR, "Error reading CMakeSystemSpecificInformation.cmake" << std::endl); @@ -242,7 +241,7 @@ int main(int argc, char const* const* argv) } if (!cpackBuildConfig.empty()) { - globalMF->AddDefinition("CPACK_BUILD_CONFIG", cpackBuildConfig.c_str()); + globalMF.AddDefinition("CPACK_BUILD_CONFIG", cpackBuildConfig.c_str()); } if (cmSystemTools::FileExists(cpackConfigFile.c_str())) { @@ -250,7 +249,7 @@ int main(int argc, char const* const* argv) cmCPack_Log(&log, cmCPackLog::LOG_VERBOSE, "Read CPack configuration file: " << cpackConfigFile << std::endl); - if (!globalMF->ReadListFile(cpackConfigFile.c_str())) { + if (!globalMF.ReadListFile(cpackConfigFile.c_str())) { cmCPack_Log(&log, cmCPackLog::LOG_ERROR, "Problem reading CPack config file: \"" << cpackConfigFile << "\"" << std::endl); @@ -264,58 +263,53 @@ int main(int argc, char const* const* argv) } if (!generator.empty()) { - globalMF->AddDefinition("CPACK_GENERATOR", generator.c_str()); + globalMF.AddDefinition("CPACK_GENERATOR", generator.c_str()); } if (!cpackProjectName.empty()) { - globalMF->AddDefinition("CPACK_PACKAGE_NAME", cpackProjectName.c_str()); + globalMF.AddDefinition("CPACK_PACKAGE_NAME", cpackProjectName.c_str()); } if (!cpackProjectVersion.empty()) { - globalMF->AddDefinition("CPACK_PACKAGE_VERSION", - cpackProjectVersion.c_str()); + globalMF.AddDefinition("CPACK_PACKAGE_VERSION", + cpackProjectVersion.c_str()); } if (!cpackProjectVendor.empty()) { - globalMF->AddDefinition("CPACK_PACKAGE_VENDOR", - cpackProjectVendor.c_str()); + globalMF.AddDefinition("CPACK_PACKAGE_VENDOR", + cpackProjectVendor.c_str()); } // if this is not empty it has been set on the command line // go for it. Command line override values set in config file. if (!cpackProjectDirectory.empty()) { - globalMF->AddDefinition("CPACK_PACKAGE_DIRECTORY", - cpackProjectDirectory.c_str()); + globalMF.AddDefinition("CPACK_PACKAGE_DIRECTORY", + cpackProjectDirectory.c_str()); } // The value has not been set on the command line else { // get a default value (current working directory) cpackProjectDirectory = cmsys::SystemTools::GetCurrentWorkingDirectory(); // use default value iff no value has been provided by the config file - if (!globalMF->IsSet("CPACK_PACKAGE_DIRECTORY")) { - globalMF->AddDefinition("CPACK_PACKAGE_DIRECTORY", - cpackProjectDirectory.c_str()); + if (!globalMF.IsSet("CPACK_PACKAGE_DIRECTORY")) { + globalMF.AddDefinition("CPACK_PACKAGE_DIRECTORY", + cpackProjectDirectory.c_str()); } } - cpackDefinitions::MapType::iterator cdit; - for (cdit = definitions.Map.begin(); cdit != definitions.Map.end(); - ++cdit) { - globalMF->AddDefinition(cdit->first, cdit->second.c_str()); + for (auto const& cd : definitions.Map) { + globalMF.AddDefinition(cd.first, cd.second.c_str()); } - const char* cpackModulesPath = - globalMF->GetDefinition("CPACK_MODULE_PATH"); + const char* cpackModulesPath = globalMF.GetDefinition("CPACK_MODULE_PATH"); if (cpackModulesPath) { - globalMF->AddDefinition("CMAKE_MODULE_PATH", cpackModulesPath); + globalMF.AddDefinition("CMAKE_MODULE_PATH", cpackModulesPath); } - const char* genList = globalMF->GetDefinition("CPACK_GENERATOR"); + const char* genList = globalMF.GetDefinition("CPACK_GENERATOR"); if (!genList) { cmCPack_Log(&log, cmCPackLog::LOG_ERROR, "CPack generator not specified" << std::endl); } else { std::vector<std::string> generatorsVector; cmSystemTools::ExpandListArgument(genList, generatorsVector); - std::vector<std::string>::iterator it; - for (it = generatorsVector.begin(); it != generatorsVector.end(); ++it) { - const char* gen = it->c_str(); - cmMakefile::ScopePushPop raii(globalMF.get()); - cmMakefile* mf = globalMF.get(); + for (std::string const& gen : generatorsVector) { + cmMakefile::ScopePushPop raii(&globalMF); + cmMakefile* mf = &globalMF; cmCPack_Log(&log, cmCPackLog::LOG_VERBOSE, "Specified generator: " << gen << std::endl); if (parsed && !mf->GetDefinition("CPACK_PACKAGE_NAME")) { @@ -354,13 +348,14 @@ int main(int argc, char const* const* argv) } if (!mf->GetDefinition("CPACK_INSTALL_COMMANDS") && + !mf->GetDefinition("CPACK_INSTALL_SCRIPT") && !mf->GetDefinition("CPACK_INSTALLED_DIRECTORIES") && !mf->GetDefinition("CPACK_INSTALL_CMAKE_PROJECTS")) { cmCPack_Log( &log, cmCPackLog::LOG_ERROR, "Please specify build tree of the project that uses CMake " "using CPACK_INSTALL_CMAKE_PROJECTS, specify " - "CPACK_INSTALL_COMMANDS, or specify " + "CPACK_INSTALL_COMMANDS, CPACK_INSTALL_SCRIPT, or " "CPACK_INSTALLED_DIRECTORIES." << std::endl); parsed = 0; @@ -413,12 +408,10 @@ int main(int argc, char const* const* argv) doc.PrependSection("Options", cmDocumentationOptions); std::vector<cmDocumentationEntry> v; - cmCPackGeneratorFactory::DescriptionsMap::const_iterator generatorIt; - for (generatorIt = generators.GetGeneratorsList().begin(); - generatorIt != generators.GetGeneratorsList().end(); ++generatorIt) { + for (auto const& g : generators.GetGeneratorsList()) { cmDocumentationEntry e; - e.Name = generatorIt->first; - e.Brief = generatorIt->second; + e.Name = g.first; + e.Brief = g.second; v.push_back(e); } doc.SetSection("Generators", v); diff --git a/Source/CTest/cmCTestBZR.cxx b/Source/CTest/cmCTestBZR.cxx index 4c9c5ca..0152200 100644 --- a/Source/CTest/cmCTestBZR.cxx +++ b/Source/CTest/cmCTestBZR.cxx @@ -98,7 +98,7 @@ private: bool CheckOutFound; cmsys::RegularExpression RegexCheckOut; cmsys::RegularExpression RegexParent; - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (this->RegexCheckOut.find(this->Line)) { this->BZR->URL = this->RegexCheckOut.match(1); @@ -123,7 +123,7 @@ public: private: std::string& Rev; cmsys::RegularExpression RegexRevno; - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (this->RegexRevno.find(this->Line)) { this->Rev = this->RegexRevno.match(1); @@ -182,9 +182,9 @@ public: { this->InitializeParser(); } - ~LogParser() CM_OVERRIDE { this->CleanupParser(); } + ~LogParser() override { this->CleanupParser(); } - int InitializeParser() CM_OVERRIDE + int InitializeParser() override { int res = cmXMLParser::InitializeParser(); if (res) { @@ -207,14 +207,14 @@ private: cmsys::RegularExpression EmailRegex; - bool ProcessChunk(const char* data, int length) CM_OVERRIDE + bool ProcessChunk(const char* data, int length) override { this->OutputLogger::ProcessChunk(data, length); this->ParseChunk(data, length); return true; } - void StartElement(const std::string& name, const char** /*atts*/) CM_OVERRIDE + void StartElement(const std::string& name, const char** /*atts*/) override { this->CData.clear(); if (name == "log") { @@ -239,12 +239,12 @@ private: } } - void CharacterDataHandler(const char* data, int length) CM_OVERRIDE + void CharacterDataHandler(const char* data, int length) override { this->CData.insert(this->CData.end(), data, data + length); } - void EndElement(const std::string& name) CM_OVERRIDE + void EndElement(const std::string& name) override { if (name == "log") { this->BZR->DoRevision(this->Rev, this->Changes); @@ -274,7 +274,7 @@ private: this->CData.clear(); } - void ReportError(int /*line*/, int /*column*/, const char* msg) CM_OVERRIDE + void ReportError(int /*line*/, int /*column*/, const char* msg) override { this->BZR->Log << "Error parsing bzr log xml: " << msg << "\n"; } @@ -294,7 +294,7 @@ private: cmCTestBZR* BZR; cmsys::RegularExpression RegexUpdate; - bool ProcessChunk(const char* first, int length) CM_OVERRIDE + bool ProcessChunk(const char* first, int length) override { bool last_is_new_line = (*first == '\r' || *first == '\n'); @@ -309,11 +309,11 @@ private: // Hand this line to the subclass implementation. if (!this->ProcessLine()) { - this->Line = ""; + this->Line.clear(); return false; } - this->Line = ""; + this->Line.clear(); last_is_new_line = true; } } else { @@ -325,7 +325,7 @@ private: return true; } - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (this->RegexUpdate.find(this->Line)) { this->DoPath(this->RegexUpdate.match(1)[0], @@ -373,9 +373,8 @@ bool cmCTestBZR::UpdateImpl() bzr_update.push_back(this->CommandLineTool.c_str()); bzr_update.push_back("pull"); - for (std::vector<std::string>::const_iterator ai = args.begin(); - ai != args.end(); ++ai) { - bzr_update.push_back(ai->c_str()); + for (std::string const& arg : args) { + bzr_update.push_back(arg.c_str()); } bzr_update.push_back(this->URL.c_str()); @@ -432,7 +431,7 @@ public: private: cmCTestBZR* BZR; cmsys::RegularExpression RegexStatus; - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (this->RegexStatus.find(this->Line)) { this->DoPath(this->RegexStatus.match(1)[0], diff --git a/Source/CTest/cmCTestBZR.h b/Source/CTest/cmCTestBZR.h index b313b25..d5c78c7 100644 --- a/Source/CTest/cmCTestBZR.h +++ b/Source/CTest/cmCTestBZR.h @@ -22,20 +22,20 @@ public: /** Construct with a CTest instance and update log stream. */ cmCTestBZR(cmCTest* ctest, std::ostream& log); - ~cmCTestBZR() CM_OVERRIDE; + ~cmCTestBZR() override; private: // Implement cmCTestVC internal API. - bool NoteOldRevision() CM_OVERRIDE; - bool NoteNewRevision() CM_OVERRIDE; - bool UpdateImpl() CM_OVERRIDE; + bool NoteOldRevision() override; + bool NoteNewRevision() override; + bool UpdateImpl() override; // URL of repository directory checked out in the working tree. std::string URL; std::string LoadInfo(); - bool LoadModifications() CM_OVERRIDE; - bool LoadRevisions() CM_OVERRIDE; + bool LoadModifications() override; + bool LoadRevisions() override; // Parsing helper classes. class InfoParser; diff --git a/Source/CTest/cmCTestBatchTestHandler.cxx b/Source/CTest/cmCTestBatchTestHandler.cxx index beee53a..2eed8be 100644 --- a/Source/CTest/cmCTestBatchTestHandler.cxx +++ b/Source/CTest/cmCTestBatchTestHandler.cxx @@ -29,10 +29,9 @@ void cmCTestBatchTestHandler::WriteBatchScript() fout.open(this->Script.c_str()); fout << "#!/bin/sh\n"; - for (TestMap::iterator i = this->Tests.begin(); i != this->Tests.end(); - ++i) { - this->WriteSrunArgs(i->first, fout); - this->WriteTestCommand(i->first, fout); + for (auto const& t : this->Tests) { + this->WriteSrunArgs(t.first, fout); + this->WriteTestCommand(t.first, fout); fout << "\n"; } fout.flush(); @@ -80,9 +79,8 @@ void cmCTestBatchTestHandler::WriteTestCommand(int test, std::ostream& fout) this->TestHandler->GenerateTestCommand(processArgs, test); processArgs.push_back(command); - for (std::vector<std::string>::iterator arg = processArgs.begin(); - arg != processArgs.end(); ++arg) { - fout << *arg << " "; + for (std::string const& arg : processArgs) { + fout << arg << " "; } std::vector<std::string>::iterator i = args.begin(); diff --git a/Source/CTest/cmCTestBatchTestHandler.h b/Source/CTest/cmCTestBatchTestHandler.h index 3b58b13..42f87bd 100644 --- a/Source/CTest/cmCTestBatchTestHandler.h +++ b/Source/CTest/cmCTestBatchTestHandler.h @@ -17,8 +17,8 @@ class cmCTestBatchTestHandler : public cmCTestMultiProcessHandler { public: - ~cmCTestBatchTestHandler() CM_OVERRIDE; - void RunTests() CM_OVERRIDE; + ~cmCTestBatchTestHandler() override; + void RunTests() override; protected: void WriteBatchScript(); diff --git a/Source/CTest/cmCTestBuildAndTestHandler.cxx b/Source/CTest/cmCTestBuildAndTestHandler.cxx index b6c25b8..a0d68a0 100644 --- a/Source/CTest/cmCTestBuildAndTestHandler.cxx +++ b/Source/CTest/cmCTestBuildAndTestHandler.cxx @@ -32,7 +32,7 @@ const char* cmCTestBuildAndTestHandler::GetOutput() } int cmCTestBuildAndTestHandler::ProcessHandler() { - this->Output = ""; + this->Output.clear(); std::string output; cmSystemTools::ResetErrorOccuredFlag(); int retv = this->RunCMakeAndTest(&this->Output); @@ -45,7 +45,6 @@ int cmCTestBuildAndTestHandler::RunCMake(std::string* outstring, std::string& cmakeOutString, cmake* cm) { - unsigned int k; std::vector<std::string> args; args.push_back(cmSystemTools::GetCMakeCommand()); args.push_back(this->SourceDir); @@ -80,8 +79,8 @@ int cmCTestBuildAndTestHandler::RunCMake(std::string* outstring, args.push_back(btype); } - for (k = 0; k < this->BuildOptions.size(); ++k) { - args.push_back(this->BuildOptions[k]); + for (std::string const& opt : this->BuildOptions) { + args.push_back(opt); } if (cm->Run(args) != 0) { out << "Error: cmake execution failed\n"; @@ -115,21 +114,21 @@ int cmCTestBuildAndTestHandler::RunCMake(std::string* outstring, void CMakeMessageCallback(const char* m, const char* /*unused*/, bool& /*unused*/, void* s) { - std::string* out = reinterpret_cast<std::string*>(s); + std::string* out = static_cast<std::string*>(s); *out += m; *out += "\n"; } void CMakeProgressCallback(const char* msg, float /*unused*/, void* s) { - std::string* out = reinterpret_cast<std::string*>(s); + std::string* out = static_cast<std::string*>(s); *out += msg; *out += "\n"; } void CMakeOutputCallback(const char* m, size_t len, void* s) { - std::string* out = reinterpret_cast<std::string*>(s); + std::string* out = static_cast<std::string*>(s); out->append(m, len); } @@ -219,12 +218,10 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring) } // do the build - std::vector<std::string>::iterator tarIt; if (this->BuildTargets.empty()) { this->BuildTargets.push_back(""); } - for (tarIt = this->BuildTargets.begin(); tarIt != this->BuildTargets.end(); - ++tarIt) { + for (std::string const& tar : this->BuildTargets) { double remainingTime = 0; if (this->Timeout > 0) { remainingTime = this->Timeout - cmSystemTools::GetTime() + clock_start; @@ -249,7 +246,7 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring) config = "Debug"; } int retVal = cm.GetGlobalGenerator()->Build( - this->SourceDir, this->BinaryDir, this->BuildProject, *tarIt, output, + this->SourceDir, this->BinaryDir, this->BuildProject, tar, output, this->BuildMakeProgram, config, !this->BuildNoClean, false, false, remainingTime); out << output; @@ -292,8 +289,8 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring) << this->TestCommand << "\n"; out << "tried to find it in these places:\n"; out << fullPath << "\n"; - for (unsigned int i = 0; i < failed.size(); ++i) { - out << failed[i] << "\n"; + for (std::string const& fail : failed) { + out << fail << "\n"; } if (outstring) { *outstring = out.str(); @@ -305,8 +302,8 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring) std::vector<const char*> testCommand; testCommand.push_back(fullPath.c_str()); - for (size_t k = 0; k < this->TestCommandArgs.size(); ++k) { - testCommand.push_back(this->TestCommandArgs[k].c_str()); + for (std::string const& testCommandArg : this->TestCommandArgs) { + testCommand.push_back(testCommandArg.c_str()); } testCommand.push_back(nullptr); std::string outs; @@ -317,8 +314,8 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring) cmSystemTools::ChangeDirectory(this->BuildRunDir); } out << "Running test command: \"" << fullPath << "\""; - for (size_t k = 0; k < this->TestCommandArgs.size(); ++k) { - out << " \"" << this->TestCommandArgs[k] << "\""; + for (std::string const& testCommandArg : this->TestCommandArgs) { + out << " \"" << testCommandArg << "\""; } out << "\n"; diff --git a/Source/CTest/cmCTestBuildAndTestHandler.h b/Source/CTest/cmCTestBuildAndTestHandler.h index a0d3674..f19cb67 100644 --- a/Source/CTest/cmCTestBuildAndTestHandler.h +++ b/Source/CTest/cmCTestBuildAndTestHandler.h @@ -26,12 +26,12 @@ public: /* * The main entry point for this class */ - int ProcessHandler() CM_OVERRIDE; + int ProcessHandler() override; //! Set all the build and test arguments - int ProcessCommandLineArguments(const std::string& currentArg, size_t& idx, - const std::vector<std::string>& allArgs) - CM_OVERRIDE; + int ProcessCommandLineArguments( + const std::string& currentArg, size_t& idx, + const std::vector<std::string>& allArgs) override; /* * Get the output variable @@ -40,7 +40,7 @@ public: cmCTestBuildAndTestHandler(); - void Initialize() CM_OVERRIDE; + void Initialize() override; protected: ///! Run CMake and build a test and then run it as a single test. diff --git a/Source/CTest/cmCTestBuildCommand.h b/Source/CTest/cmCTestBuildCommand.h index f03bb2c..77b0549 100644 --- a/Source/CTest/cmCTestBuildCommand.h +++ b/Source/CTest/cmCTestBuildCommand.h @@ -25,12 +25,12 @@ class cmCTestBuildCommand : public cmCTestHandlerCommand { public: cmCTestBuildCommand(); - ~cmCTestBuildCommand() CM_OVERRIDE; + ~cmCTestBuildCommand() override; /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmCTestBuildCommand* ni = new cmCTestBuildCommand; ni->CTest = this->CTest; @@ -41,10 +41,10 @@ public: /** * The name of the command as specified in CMakeList.txt. */ - std::string GetName() const CM_OVERRIDE { return "ctest_build"; } + std::string GetName() const override { return "ctest_build"; } bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; cmGlobalGenerator* GlobalGenerator; @@ -62,7 +62,7 @@ protected: ctb_LAST }; - cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE; + cmCTestGenericHandler* InitializeHandler() override; }; #endif diff --git a/Source/CTest/cmCTestBuildHandler.cxx b/Source/CTest/cmCTestBuildHandler.cxx index 3762e13..1da42d4 100644 --- a/Source/CTest/cmCTestBuildHandler.cxx +++ b/Source/CTest/cmCTestBuildHandler.cxx @@ -171,8 +171,8 @@ cmCTestBuildHandler::cmCTestBuildHandler() void cmCTestBuildHandler::Initialize() { this->Superclass::Initialize(); - this->StartBuild = ""; - this->EndBuild = ""; + this->StartBuild.clear(); + this->EndBuild.clear(); this->CustomErrorMatches.clear(); this->CustomErrorExceptions.clear(); this->CustomWarningMatches.clear(); @@ -190,8 +190,8 @@ void cmCTestBuildHandler::Initialize() this->BuildOutputLogSize = 0; this->CurrentProcessingLine.clear(); - this->SimplifySourceDir = ""; - this->SimplifyBuildDir = ""; + this->SimplifySourceDir.clear(); + this->SimplifyBuildDir.clear(); this->OutputLineCounter = 0; this->ErrorsAndWarnings.clear(); this->LastErrorOrWarning = this->ErrorsAndWarnings.end(); @@ -260,11 +260,11 @@ std::string cmCTestBuildHandler::GetMakeCommand() "MakeCommand:" << makeCommand << "\n", this->Quiet); std::string configType = this->CTest->GetConfigType(); - if (configType == "") { + if (configType.empty()) { configType = this->CTest->GetCTestConfiguration("DefaultCTestConfigurationType"); } - if (configType == "") { + if (configType.empty()) { configType = "Release"; } @@ -350,18 +350,16 @@ int cmCTestBuildHandler::ProcessHandler() this->CustomWarningExceptions.push_back(cmCTestWarningExceptions[cc]); } - // Pre-compile regular expressions objects for all regular expressions - std::vector<std::string>::iterator it; +// Pre-compile regular expressions objects for all regular expressions #define cmCTestBuildHandlerPopulateRegexVector(strings, regexes) \ regexes.clear(); \ cmCTestOptionalLog(this->CTest, DEBUG, \ this << "Add " #regexes << std::endl, this->Quiet); \ - for (it = (strings).begin(); it != (strings).end(); ++it) { \ + for (std::string const& s : (strings)) { \ cmCTestOptionalLog(this->CTest, DEBUG, \ - "Add " #strings ": " << *it << std::endl, \ - this->Quiet); \ - (regexes).push_back(it->c_str()); \ + "Add " #strings ": " << s << std::endl, this->Quiet); \ + (regexes).push_back(s.c_str()); \ } cmCTestBuildHandlerPopulateRegexVector(this->CustomErrorMatches, this->ErrorMatchRegex); @@ -373,8 +371,8 @@ int cmCTestBuildHandler::ProcessHandler() this->WarningExceptionRegex); // Determine source and binary tree substitutions to simplify the output. - this->SimplifySourceDir = ""; - this->SimplifyBuildDir = ""; + this->SimplifySourceDir.clear(); + this->SimplifyBuildDir.clear(); if (this->CTest->GetCTestConfiguration("SourceDirectory").size() > 20) { std::string srcdir = this->CTest->GetCTestConfiguration("SourceDirectory") + "/"; @@ -426,27 +424,24 @@ int cmCTestBuildHandler::ProcessHandler() double elapsed_build_time = cmSystemTools::GetTime() - elapsed_time_start; // Cleanups strings in the errors and warnings list. - t_ErrorsAndWarningsVector::iterator evit; if (!this->SimplifySourceDir.empty()) { - for (evit = this->ErrorsAndWarnings.begin(); - evit != this->ErrorsAndWarnings.end(); ++evit) { - cmSystemTools::ReplaceString(evit->Text, this->SimplifySourceDir.c_str(), + for (cmCTestBuildErrorWarning& evit : this->ErrorsAndWarnings) { + cmSystemTools::ReplaceString(evit.Text, this->SimplifySourceDir.c_str(), "/.../"); - cmSystemTools::ReplaceString(evit->PreContext, + cmSystemTools::ReplaceString(evit.PreContext, this->SimplifySourceDir.c_str(), "/.../"); - cmSystemTools::ReplaceString(evit->PostContext, + cmSystemTools::ReplaceString(evit.PostContext, this->SimplifySourceDir.c_str(), "/.../"); } } if (!this->SimplifyBuildDir.empty()) { - for (evit = this->ErrorsAndWarnings.begin(); - evit != this->ErrorsAndWarnings.end(); ++evit) { - cmSystemTools::ReplaceString(evit->Text, this->SimplifyBuildDir.c_str(), + for (cmCTestBuildErrorWarning& evit : this->ErrorsAndWarnings) { + cmSystemTools::ReplaceString(evit.Text, this->SimplifyBuildDir.c_str(), "/.../"); - cmSystemTools::ReplaceString(evit->PreContext, + cmSystemTools::ReplaceString(evit.PreContext, this->SimplifyBuildDir.c_str(), "/.../"); - cmSystemTools::ReplaceString(evit->PostContext, + cmSystemTools::ReplaceString(evit.PostContext, this->SimplifyBuildDir.c_str(), "/.../"); } } @@ -556,9 +551,8 @@ void cmCTestBuildHandler::GenerateXMLLaunched(cmXMLWriter& xml) } // Copy the fragments into the final XML file. - for (Fragments::const_iterator fi = fragments.begin(); fi != fragments.end(); - ++fi) { - xml.FragmentFile(fi->c_str()); + for (std::string const& f : fragments) { + xml.FragmentFile(f.c_str()); } } @@ -588,12 +582,11 @@ void cmCTestBuildHandler::GenerateXMLLogScraped(cmXMLWriter& xml) xml.StartElement(cm->Error ? "Error" : "Warning"); xml.Element("BuildLogLine", cm->LogLine); xml.Element("Text", cm->Text); - std::vector<cmCTestCompileErrorWarningRex>::iterator rit; - for (rit = this->ErrorWarningFileLineRegex.begin(); - rit != this->ErrorWarningFileLineRegex.end(); ++rit) { - cmsys::RegularExpression* re = &rit->RegularExpression; + for (cmCTestCompileErrorWarningRex& rit : + this->ErrorWarningFileLineRegex) { + cmsys::RegularExpression* re = &rit.RegularExpression; if (re->find(cm->Text.c_str())) { - cm->SourceFile = re->match(rit->FileIndex); + cm->SourceFile = re->match(rit.FileIndex); // At this point we need to make this->SourceFile relative to // the source root of the project, so cvs links will work cmSystemTools::ConvertToUnixSlashes(cm->SourceFile); @@ -609,7 +602,7 @@ void cmCTestBuildHandler::GenerateXMLLogScraped(cmXMLWriter& xml) cm->SourceFile = cmSystemTools::CollapseFullPath(cm->SourceFile); cmSystemTools::ReplaceString(cm->SourceFile, srcdir.c_str(), ""); } - cm->LineNumber = atoi(re->match(rit->LineIndex).c_str()); + cm->LineNumber = atoi(re->match(rit.LineIndex).c_str()); break; } } @@ -759,9 +752,8 @@ void cmCTestBuildHandler::LaunchHelper::WriteScrapeMatchers( fname += purpose; fname += ".txt"; cmGeneratedFileStream fout(fname.c_str()); - for (std::vector<std::string>::const_iterator mi = matchers.begin(); - mi != matchers.end(); ++mi) { - fout << *mi << "\n"; + for (std::string const& m : matchers) { + fout << m << "\n"; } } @@ -777,18 +769,19 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal, } std::vector<const char*> argv; - for (std::vector<std::string>::const_iterator a = args.begin(); - a != args.end(); ++a) { - argv.push_back(a->c_str()); + for (std::string const& arg : args) { + argv.push_back(arg.c_str()); } argv.push_back(nullptr); cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Run command:", this->Quiet); - std::vector<const char*>::iterator ait; - for (ait = argv.begin(); ait != argv.end() && *ait; ++ait) { + for (char const* arg : argv) { + if (!arg) { + break; + } cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, - " \"" << *ait << "\"", this->Quiet); + " \"" << arg << "\"", this->Quiet); } cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, std::endl, this->Quiet); @@ -895,8 +888,8 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal, errorwarning.Text = "*** WARNING non-zero return value in ctest from: "; errorwarning.Text += argv[0]; - errorwarning.PreContext = ""; - errorwarning.PostContext = ""; + errorwarning.PreContext.clear(); + errorwarning.PostContext.clear(); errorwarning.Error = false; this->ErrorsAndWarnings.push_back(errorwarning); this->TotalWarnings++; @@ -918,8 +911,8 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal, errorwarning.LogLine = 1; errorwarning.Text = "*** ERROR executing: "; errorwarning.Text += cmsysProcess_GetErrorString(cp); - errorwarning.PreContext = ""; - errorwarning.PostContext = ""; + errorwarning.PreContext.clear(); + errorwarning.PostContext.clear(); errorwarning.Error = true; this->ErrorsAndWarnings.push_back(errorwarning); this->TotalErrors++; @@ -1003,14 +996,12 @@ void cmCTestBuildHandler::ProcessBuffer(const char* data, size_t length, // This is an error or warning, so generate report errorwarning.LogLine = static_cast<int>(this->OutputLineCounter + 1); errorwarning.Text = line; - errorwarning.PreContext = ""; - errorwarning.PostContext = ""; + errorwarning.PreContext.clear(); + errorwarning.PostContext.clear(); // Copy pre-context to report - std::deque<std::string>::iterator pcit; - for (pcit = this->PreContext.begin(); pcit != this->PreContext.end(); - ++pcit) { - errorwarning.PreContext += *pcit + "\n"; + for (std::string const& pc : this->PreContext) { + errorwarning.PreContext += pc + "\n"; } this->PreContext.clear(); @@ -1082,8 +1073,6 @@ int cmCTestBuildHandler::ProcessSingleLine(const char* data) cmCTestOptionalLog(this->CTest, DEBUG, "Line: [" << data << "]" << std::endl, this->Quiet); - std::vector<cmsys::RegularExpression>::iterator it; - int warningLine = 0; int errorLine = 0; @@ -1092,9 +1081,8 @@ int cmCTestBuildHandler::ProcessSingleLine(const char* data) if (!this->ErrorQuotaReached) { // Errors int wrxCnt = 0; - for (it = this->ErrorMatchRegex.begin(); it != this->ErrorMatchRegex.end(); - ++it) { - if (it->find(data)) { + for (cmsys::RegularExpression& rx : this->ErrorMatchRegex) { + if (rx.find(data)) { errorLine = 1; cmCTestOptionalLog(this->CTest, DEBUG, " Error Line: " << data << " (matches: " @@ -1107,9 +1095,8 @@ int cmCTestBuildHandler::ProcessSingleLine(const char* data) } // Error exceptions wrxCnt = 0; - for (it = this->ErrorExceptionRegex.begin(); - it != this->ErrorExceptionRegex.end(); ++it) { - if (it->find(data)) { + for (cmsys::RegularExpression& rx : this->ErrorExceptionRegex) { + if (rx.find(data)) { errorLine = 0; cmCTestOptionalLog(this->CTest, DEBUG, " Not an error Line: " << data << " (matches: " @@ -1124,9 +1111,8 @@ int cmCTestBuildHandler::ProcessSingleLine(const char* data) if (!this->WarningQuotaReached) { // Warnings int wrxCnt = 0; - for (it = this->WarningMatchRegex.begin(); - it != this->WarningMatchRegex.end(); ++it) { - if (it->find(data)) { + for (cmsys::RegularExpression& rx : this->WarningMatchRegex) { + if (rx.find(data)) { warningLine = 1; cmCTestOptionalLog(this->CTest, DEBUG, " Warning Line: " << data << " (matches: " @@ -1140,9 +1126,8 @@ int cmCTestBuildHandler::ProcessSingleLine(const char* data) wrxCnt = 0; // Warning exceptions - for (it = this->WarningExceptionRegex.begin(); - it != this->WarningExceptionRegex.end(); ++it) { - if (it->find(data)) { + for (cmsys::RegularExpression& rx : this->WarningExceptionRegex) { + if (rx.find(data)) { warningLine = 0; cmCTestOptionalLog(this->CTest, DEBUG, " Not a warning Line: " << data << " (matches: " diff --git a/Source/CTest/cmCTestBuildHandler.h b/Source/CTest/cmCTestBuildHandler.h index ca11143..6e71ad6 100644 --- a/Source/CTest/cmCTestBuildHandler.h +++ b/Source/CTest/cmCTestBuildHandler.h @@ -31,16 +31,16 @@ public: /* * The main entry point for this class */ - int ProcessHandler() CM_OVERRIDE; + int ProcessHandler() override; cmCTestBuildHandler(); - void PopulateCustomVectors(cmMakefile* mf) CM_OVERRIDE; + void PopulateCustomVectors(cmMakefile* mf) override; /** * Initialize handler */ - void Initialize() CM_OVERRIDE; + void Initialize() override; int GetTotalErrors() { return this->TotalErrors; } int GetTotalWarnings() { return this->TotalWarnings; } diff --git a/Source/CTest/cmCTestCVS.cxx b/Source/CTest/cmCTestCVS.cxx index f2a9a85..5779935 100644 --- a/Source/CTest/cmCTestCVS.cxx +++ b/Source/CTest/cmCTestCVS.cxx @@ -46,7 +46,7 @@ private: cmsys::RegularExpression RegexFileRemoved1; cmsys::RegularExpression RegexFileRemoved2; - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (this->RegexFileUpdated.find(this->Line)) { this->DoFile(PathUpdated, this->RegexFileUpdated.match(2)); @@ -92,9 +92,8 @@ bool cmCTestCVS::UpdateImpl() cvs_update.push_back(this->CommandLineTool.c_str()); cvs_update.push_back("-z3"); cvs_update.push_back("update"); - for (std::vector<std::string>::const_iterator ai = args.begin(); - ai != args.end(); ++ai) { - cvs_update.push_back(ai->c_str()); + for (std::string const& arg : args) { + cvs_update.push_back(arg.c_str()); } cvs_update.push_back(nullptr); @@ -133,7 +132,7 @@ private: SectionType Section; Revision Rev; - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (this->Line == ("=======================================" "======================================")) { @@ -242,12 +241,12 @@ void cmCTestCVS::WriteXMLDirectory(cmXMLWriter& xml, std::string const& path, // Load revisions and write an entry for each file in this directory. std::vector<Revision> revisions; - for (Directory::const_iterator fi = dir.begin(); fi != dir.end(); ++fi) { - std::string full = path + slash + fi->first; + for (auto const& fi : dir) { + std::string full = path + slash + fi.first; // Load two real or unknown revisions. revisions.clear(); - if (fi->second != PathUpdated) { + if (fi.second != PathUpdated) { // For local modifications the current rev is unknown and the // prior rev is the latest from cvs. revisions.push_back(this->Unknown); @@ -256,8 +255,8 @@ void cmCTestCVS::WriteXMLDirectory(cmXMLWriter& xml, std::string const& path, revisions.resize(2, this->Unknown); // Write the entry for this file with these revisions. - File f(fi->second, &revisions[0], &revisions[1]); - this->WriteXMLEntry(xml, path, fi->first, full, f); + File f(fi.second, &revisions[0], &revisions[1]); + this->WriteXMLEntry(xml, path, fi.first, full, f); } xml.EndElement(); // Directory } @@ -269,10 +268,8 @@ bool cmCTestCVS::WriteXMLUpdates(cmXMLWriter& xml) " " << std::flush); - for (std::map<std::string, Directory>::const_iterator di = - this->Dirs.begin(); - di != this->Dirs.end(); ++di) { - this->WriteXMLDirectory(xml, di->first, di->second); + for (auto const& d : this->Dirs) { + this->WriteXMLDirectory(xml, d.first, d.second); } cmCTestLog(this->CTest, HANDLER_OUTPUT, std::endl); diff --git a/Source/CTest/cmCTestCVS.h b/Source/CTest/cmCTestCVS.h index 171460e..77fc3cc 100644 --- a/Source/CTest/cmCTestCVS.h +++ b/Source/CTest/cmCTestCVS.h @@ -25,12 +25,12 @@ public: /** Construct with a CTest instance and update log stream. */ cmCTestCVS(cmCTest* ctest, std::ostream& log); - ~cmCTestCVS() CM_OVERRIDE; + ~cmCTestCVS() override; private: // Implement cmCTestVC internal API. - bool UpdateImpl() CM_OVERRIDE; - bool WriteXMLUpdates(cmXMLWriter& xml) CM_OVERRIDE; + bool UpdateImpl() override; + bool WriteXMLUpdates(cmXMLWriter& xml) override; // Update status for files in each directory. class Directory : public std::map<std::string, PathStatus> diff --git a/Source/CTest/cmCTestConfigureCommand.cxx b/Source/CTest/cmCTestConfigureCommand.cxx index faa75d3..c44b866 100644 --- a/Source/CTest/cmCTestConfigureCommand.cxx +++ b/Source/CTest/cmCTestConfigureCommand.cxx @@ -79,11 +79,7 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler() cmakeConfigureCommand += cmSystemTools::GetCMakeCommand(); cmakeConfigureCommand += "\""; - std::vector<std::string>::const_iterator it; - std::string option; - for (it = options.begin(); it != options.end(); ++it) { - option = *it; - + for (std::string const& option : options) { cmakeConfigureCommand += " \""; cmakeConfigureCommand += option; cmakeConfigureCommand += "\""; diff --git a/Source/CTest/cmCTestConfigureCommand.h b/Source/CTest/cmCTestConfigureCommand.h index dfb3a59..0cbcbfa 100644 --- a/Source/CTest/cmCTestConfigureCommand.h +++ b/Source/CTest/cmCTestConfigureCommand.h @@ -25,7 +25,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmCTestConfigureCommand* ni = new cmCTestConfigureCommand; ni->CTest = this->CTest; @@ -36,10 +36,10 @@ public: /** * The name of the command as specified in CMakeList.txt. */ - std::string GetName() const CM_OVERRIDE { return "ctest_configure"; } + std::string GetName() const override { return "ctest_configure"; } protected: - cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE; + cmCTestGenericHandler* InitializeHandler() override; enum { diff --git a/Source/CTest/cmCTestConfigureHandler.h b/Source/CTest/cmCTestConfigureHandler.h index 32a6ba7..680401c 100644 --- a/Source/CTest/cmCTestConfigureHandler.h +++ b/Source/CTest/cmCTestConfigureHandler.h @@ -19,11 +19,11 @@ public: /* * The main entry point for this class */ - int ProcessHandler() CM_OVERRIDE; + int ProcessHandler() override; cmCTestConfigureHandler(); - void Initialize() CM_OVERRIDE; + void Initialize() override; }; #endif diff --git a/Source/CTest/cmCTestCoverageCommand.h b/Source/CTest/cmCTestCoverageCommand.h index 9ea0223..1ae2d86 100644 --- a/Source/CTest/cmCTestCoverageCommand.h +++ b/Source/CTest/cmCTestCoverageCommand.h @@ -26,7 +26,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmCTestCoverageCommand* ni = new cmCTestCoverageCommand; ni->CTest = this->CTest; @@ -37,15 +37,15 @@ public: /** * The name of the command as specified in CMakeList.txt. */ - std::string GetName() const CM_OVERRIDE { return "ctest_coverage"; } + std::string GetName() const override { return "ctest_coverage"; } typedef cmCTestHandlerCommand Superclass; protected: - cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE; + cmCTestGenericHandler* InitializeHandler() override; - bool CheckArgumentKeyword(std::string const& arg) CM_OVERRIDE; - bool CheckArgumentValue(std::string const& arg) CM_OVERRIDE; + bool CheckArgumentKeyword(std::string const& arg) override; + bool CheckArgumentValue(std::string const& arg) override; enum { diff --git a/Source/CTest/cmCTestCoverageHandler.cxx b/Source/CTest/cmCTestCoverageHandler.cxx index e3d68c6..56eeceb 100644 --- a/Source/CTest/cmCTestCoverageHandler.cxx +++ b/Source/CTest/cmCTestCoverageHandler.cxx @@ -67,10 +67,8 @@ public: bool StartProcess() { std::vector<const char*> args; - for (std::vector<std::string>::iterator i = - this->CommandLineStrings.begin(); - i != this->CommandLineStrings.end(); ++i) { - args.push_back(i->c_str()); + for (std::string const& cl : this->CommandLineStrings) { + args.push_back(cl.c_str()); } args.push_back(nullptr); // null terminate cmsysProcess_SetCommand(this->Process, &*args.begin()); @@ -136,10 +134,9 @@ void cmCTestCoverageHandler::CleanCoverageLogFiles(std::ostream& log) cmsys::Glob gl; gl.FindFiles(logGlob); std::vector<std::string> const& files = gl.GetFiles(); - for (std::vector<std::string>::const_iterator fi = files.begin(); - fi != files.end(); ++fi) { - log << "Removing old coverage log: " << *fi << "\n"; - cmSystemTools::RemoveFile(*fi); + for (std::string const& f : files) { + log << "Removing old coverage log: " << f << "\n"; + cmSystemTools::RemoveFile(f); } } @@ -188,18 +185,16 @@ void cmCTestCoverageHandler::EndCoverageLogXML(cmXMLWriter& xml) this->CTest->EndXML(xml); } -bool cmCTestCoverageHandler::ShouldIDoCoverage(const char* file, - const char* srcDir, - const char* binDir) +bool cmCTestCoverageHandler::ShouldIDoCoverage(std::string const& file, + std::string const& srcDir, + std::string const& binDir) { if (this->IsFilteredOut(file)) { return false; } - std::vector<cmsys::RegularExpression>::iterator sit; - for (sit = this->CustomCoverageExcludeRegex.begin(); - sit != this->CustomCoverageExcludeRegex.end(); ++sit) { - if (sit->find(file)) { + for (cmsys::RegularExpression& rx : this->CustomCoverageExcludeRegex) { + if (rx.find(file)) { cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " File " << file << " is excluded in CTestCustom.ctest" << std::endl; @@ -319,11 +314,9 @@ int cmCTestCoverageHandler::ProcessHandler() // setup the regex exclude stuff this->CustomCoverageExcludeRegex.clear(); - std::vector<std::string>::iterator rexIt; - for (rexIt = this->CustomCoverageExclude.begin(); - rexIt != this->CustomCoverageExclude.end(); ++rexIt) { + for (std::string const& rex : this->CustomCoverageExclude) { this->CustomCoverageExcludeRegex.push_back( - cmsys::RegularExpression(rexIt->c_str())); + cmsys::RegularExpression(rex.c_str())); } if (this->HandleBullseyeCoverage(&cont)) { @@ -414,7 +407,6 @@ int cmCTestCoverageHandler::ProcessHandler() return -1; } this->StartCoverageLogXML(covLogXML); - cmCTestCoverageHandlerContainer::TotalCoverageMap::iterator fileIterator; int cnt = 0; long total_tested = 0; long total_untested = 0; @@ -430,8 +422,7 @@ int cmCTestCoverageHandler::ProcessHandler() std::vector<std::string> errorsWhileAccumulating; file_count = 0; - for (fileIterator = cont.TotalCoverage.begin(); - fileIterator != cont.TotalCoverage.end(); ++fileIterator) { + for (auto const& file : cont.TotalCoverage) { cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "." << std::flush, this->Quiet); file_count++; @@ -443,9 +434,9 @@ int cmCTestCoverageHandler::ProcessHandler() cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet); } - const std::string fullFileName = fileIterator->first; - bool shouldIDoCoverage = this->ShouldIDoCoverage( - fullFileName.c_str(), sourceDir.c_str(), binaryDir.c_str()); + const std::string fullFileName = file.first; + bool shouldIDoCoverage = + this->ShouldIDoCoverage(fullFileName, sourceDir, binaryDir); if (!shouldIDoCoverage) { cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, ".NoDartCoverage found, so skip coverage check for: " @@ -478,7 +469,7 @@ int cmCTestCoverageHandler::ProcessHandler() std::string shortFileName = this->CTest->GetShortPathToFile(fullFileName.c_str()); const cmCTestCoverageHandlerContainer::SingleFileCoverageVector& fcov = - fileIterator->second; + file.second; covLogXML.StartElement("File"); covLogXML.Attribute("Name", fileName); covLogXML.Attribute("FullPath", shortFileName); @@ -554,14 +545,13 @@ int cmCTestCoverageHandler::ProcessHandler() } // Handle all the files in the extra coverage globs that have no cov data - for (std::set<std::string>::iterator i = uncovered.begin(); - i != uncovered.end(); ++i) { - std::string fileName = cmSystemTools::GetFilenameName(*i); - std::string fullPath = cont.SourceDir + "/" + *i; + for (std::string const& u : uncovered) { + std::string fileName = cmSystemTools::GetFilenameName(u); + std::string fullPath = cont.SourceDir + "/" + u; covLogXML.StartElement("File"); covLogXML.Attribute("Name", fileName); - covLogXML.Attribute("FullPath", *i); + covLogXML.Attribute("FullPath", u); covLogXML.StartElement("Report"); cmsys::ifstream ifs(fullPath.c_str()); @@ -570,12 +560,14 @@ int cmCTestCoverageHandler::ProcessHandler() ostr << "Cannot open source file: " << fullPath; errorsWhileAccumulating.push_back(ostr.str()); error++; + covLogXML.EndElement(); // Report + covLogXML.EndElement(); // File continue; } int untested = 0; std::string line; cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, - "Actually performing coverage for: " << *i << std::endl, + "Actually performing coverage for: " << u << std::endl, this->Quiet); while (cmSystemTools::GetLineFromStream(ifs, line)) { covLogXML.StartElement("Line"); @@ -591,13 +583,13 @@ int cmCTestCoverageHandler::ProcessHandler() total_untested += untested; covSumXML.StartElement("File"); covSumXML.Attribute("Name", fileName); - covSumXML.Attribute("FullPath", *i); + covSumXML.Attribute("FullPath", u); covSumXML.Attribute("Covered", "true"); covSumXML.Element("LOCTested", 0); covSumXML.Element("LOCUnTested", untested); covSumXML.Element("PercentCoverage", 0); covSumXML.Element("CoverageMetric", 0); - this->WriteXMLLabels(covSumXML, *i); + this->WriteXMLLabels(covSumXML, u); covSumXML.EndElement(); // File } @@ -608,10 +600,8 @@ int cmCTestCoverageHandler::ProcessHandler() cmCTestLog(this->CTest, ERROR_MESSAGE, std::endl); cmCTestLog(this->CTest, ERROR_MESSAGE, "Error(s) while accumulating results:" << std::endl); - std::vector<std::string>::iterator erIt; - for (erIt = errorsWhileAccumulating.begin(); - erIt != errorsWhileAccumulating.end(); ++erIt) { - cmCTestLog(this->CTest, ERROR_MESSAGE, " " << *erIt << std::endl); + for (std::string const& er : errorsWhileAccumulating) { + cmCTestLog(this->CTest, ERROR_MESSAGE, " " << er << std::endl); } } @@ -668,17 +658,14 @@ void cmCTestCoverageHandler::PopulateCustomVectors(cmMakefile* mf) this->CustomCoverageExclude); this->CTest->PopulateCustomVector(mf, "CTEST_EXTRA_COVERAGE_GLOB", this->ExtraCoverageGlobs); - std::vector<std::string>::iterator it; - for (it = this->CustomCoverageExclude.begin(); - it != this->CustomCoverageExclude.end(); ++it) { + for (std::string const& cce : this->CustomCoverageExclude) { cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, - " Add coverage exclude: " << *it << std::endl, + " Add coverage exclude: " << cce << std::endl, this->Quiet); } - for (it = this->ExtraCoverageGlobs.begin(); - it != this->ExtraCoverageGlobs.end(); ++it) { + for (std::string const& ecg : this->ExtraCoverageGlobs) { cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, - " Add coverage glob: " << *it << std::endl, + " Add coverage glob: " << ecg << std::endl, this->Quiet); } } @@ -875,6 +862,24 @@ int cmCTestCoverageHandler::HandleDelphiCoverage( return static_cast<int>(cont->TotalCoverage.size()); } +static std::string joinCommandLine(const std::vector<std::string>& args) +{ + std::string ret; + + for (std::string const& s : args) { + if (s.find(' ') == std::string::npos) { + ret += s + ' '; + } else { + ret += "\"" + s + "\" "; + } + } + + // drop trailing whitespace + ret.erase(ret.size() - 1); + + return ret; +} + int cmCTestCoverageHandler::HandleBlanketJSCoverage( cmCTestCoverageHandlerContainer* cont) { @@ -893,12 +898,12 @@ int cmCTestCoverageHandler::HandleBlanketJSCoverage( // Blanket.js output. Check for the "node-jscoverage" // string on the second line std::string line; - for (unsigned int fileEntry = 0; fileEntry < files.size(); fileEntry++) { - cmsys::ifstream in(files[fileEntry].c_str()); + for (std::string const& fileEntry : files) { + cmsys::ifstream in(fileEntry.c_str()); cmSystemTools::GetLineFromStream(in, line); cmSystemTools::GetLineFromStream(in, line); if (line.find("node-jscoverage") != std::string::npos) { - blanketFiles.push_back(files[fileEntry]); + blanketFiles.push_back(fileEntry); } } // Take all files with the node-jscoverage string and parse those @@ -959,7 +964,6 @@ int cmCTestCoverageHandler::HandleGCovCoverage( std::vector<std::string> files; this->FindGCovFiles(files); - std::vector<std::string>::iterator it; if (files.empty()) { cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, @@ -990,19 +994,26 @@ int cmCTestCoverageHandler::HandleGCovCoverage( cmCTestCoverageHandlerLocale locale_C; static_cast<void>(locale_C); + std::vector<std::string> basecovargs = + cmSystemTools::ParseArguments(gcovExtraFlags.c_str()); + basecovargs.insert(basecovargs.begin(), gcovCommand); + basecovargs.push_back("-o"); + // files is a list of *.da and *.gcda files with coverage data in them. // These are binary files that you give as input to gcov so that it will // give us text output we can analyze to summarize coverage. // - for (it = files.begin(); it != files.end(); ++it) { + for (std::string const& f : files) { cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "." << std::flush, this->Quiet); // Call gcov to get coverage data for this *.gcda file: // - std::string fileDir = cmSystemTools::GetFilenamePath(*it); - std::string command = "\"" + gcovCommand + "\" " + gcovExtraFlags + " " + - "-o \"" + fileDir + "\" " + "\"" + *it + "\""; + std::string fileDir = cmSystemTools::GetFilenamePath(f); + std::vector<std::string> covargs = basecovargs; + covargs.push_back(fileDir); + covargs.push_back(f); + const std::string command = joinCommandLine(covargs); cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, command << std::endl, this->Quiet); @@ -1012,15 +1023,14 @@ int cmCTestCoverageHandler::HandleGCovCoverage( int retVal = 0; *cont->OFS << "* Run coverage for: " << fileDir << std::endl; *cont->OFS << " Command: " << command << std::endl; - int res = - this->CTest->RunCommand(command.c_str(), &output, &errors, &retVal, - tempDir.c_str(), 0 /*this->TimeOut*/); + int res = this->CTest->RunCommand(covargs, &output, &errors, &retVal, + tempDir.c_str(), 0 /*this->TimeOut*/); *cont->OFS << " Output: " << output << std::endl; *cont->OFS << " Errors: " << errors << std::endl; if (!res) { cmCTestLog(this->CTest, ERROR_MESSAGE, - "Problem running coverage on file: " << *it << std::endl); + "Problem running coverage on file: " << f << std::endl); cmCTestLog(this->CTest, ERROR_MESSAGE, "Command produced error: " << errors << std::endl); cont->Error++; @@ -1028,7 +1038,7 @@ int cmCTestCoverageHandler::HandleGCovCoverage( } if (retVal != 0) { cmCTestLog(this->CTest, ERROR_MESSAGE, "Coverage command returned: " - << retVal << " while processing: " << *it << std::endl); + << retVal << " while processing: " << f << std::endl); cmCTestLog(this->CTest, ERROR_MESSAGE, "Command produced error: " << cont->Error << std::endl); } @@ -1042,20 +1052,19 @@ int cmCTestCoverageHandler::HandleGCovCoverage( this->Quiet); std::vector<std::string> lines; - std::vector<std::string>::iterator line; cmSystemTools::Split(output.c_str(), lines); - for (line = lines.begin(); line != lines.end(); ++line) { + for (std::string const& line : lines) { std::string sourceFile; std::string gcovFile; cmCTestOptionalLog(this->CTest, DEBUG, - "Line: [" << *line << "]" << std::endl, this->Quiet); + "Line: [" << line << "]" << std::endl, this->Quiet); - if (line->empty()) { + if (line.empty()) { // Ignore empty line; probably style 2 - } else if (st1re1.find(line->c_str())) { + } else if (st1re1.find(line.c_str())) { if (gcovStyle == 0) { gcovStyle = 1; } @@ -1066,9 +1075,9 @@ int cmCTestCoverageHandler::HandleGCovCoverage( break; } - actualSourceFile = ""; + actualSourceFile.clear(); sourceFile = st1re1.match(2); - } else if (st1re2.find(line->c_str())) { + } else if (st1re2.find(line.c_str())) { if (gcovStyle == 0) { gcovStyle = 1; } @@ -1080,7 +1089,7 @@ int cmCTestCoverageHandler::HandleGCovCoverage( } gcovFile = st1re2.match(1); - } else if (st2re1.find(line->c_str())) { + } else if (st2re1.find(line.c_str())) { if (gcovStyle == 0) { gcovStyle = 2; } @@ -1091,9 +1100,9 @@ int cmCTestCoverageHandler::HandleGCovCoverage( break; } - actualSourceFile = ""; + actualSourceFile.clear(); sourceFile = st2re1.match(1); - } else if (st2re2.find(line->c_str())) { + } else if (st2re2.find(line.c_str())) { if (gcovStyle == 0) { gcovStyle = 2; } @@ -1103,7 +1112,7 @@ int cmCTestCoverageHandler::HandleGCovCoverage( cont->Error++; break; } - } else if (st2re3.find(line->c_str())) { + } else if (st2re3.find(line.c_str())) { if (gcovStyle == 0) { gcovStyle = 2; } @@ -1115,7 +1124,7 @@ int cmCTestCoverageHandler::HandleGCovCoverage( } gcovFile = st2re3.match(2); - } else if (st2re4.find(line->c_str())) { + } else if (st2re4.find(line.c_str())) { if (gcovStyle == 0) { gcovStyle = 2; } @@ -1130,7 +1139,7 @@ int cmCTestCoverageHandler::HandleGCovCoverage( "Warning: " << st2re4.match(1) << " had unexpected EOF" << std::endl, this->Quiet); - } else if (st2re5.find(line->c_str())) { + } else if (st2re5.find(line.c_str())) { if (gcovStyle == 0) { gcovStyle = 2; } @@ -1144,7 +1153,7 @@ int cmCTestCoverageHandler::HandleGCovCoverage( cmCTestOptionalLog(this->CTest, WARNING, "Warning: Cannot open file: " << st2re5.match(1) << std::endl, this->Quiet); - } else if (st2re6.find(line->c_str())) { + } else if (st2re6.find(line.c_str())) { if (gcovStyle == 0) { gcovStyle = 2; } @@ -1162,10 +1171,10 @@ int cmCTestCoverageHandler::HandleGCovCoverage( } else { // gcov 4.7 can have output lines saying "No executable lines" and // "Removing 'filename.gcov'"... Don't log those as "errors." - if (*line != "No executable lines" && - !cmSystemTools::StringStartsWith(line->c_str(), "Removing ")) { + if (line != "No executable lines" && + !cmSystemTools::StringStartsWith(line.c_str(), "Removing ")) { cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output line: [" - << *line << "]" << std::endl); + << line << "]" << std::endl); cont->Error++; // abort(); } @@ -1233,11 +1242,11 @@ int cmCTestCoverageHandler::HandleGCovCoverage( } } - actualSourceFile = ""; + actualSourceFile.clear(); } if (!sourceFile.empty() && actualSourceFile.empty()) { - gcovFile = ""; + gcovFile.clear(); // Is it in the source dir or the binary dir? // @@ -1330,7 +1339,6 @@ int cmCTestCoverageHandler::HandleLCovCoverage( "Error while finding LCov files.\n"); return 0; } - std::vector<std::string>::iterator it; if (files.empty()) { cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, @@ -1355,14 +1363,18 @@ int cmCTestCoverageHandler::HandleLCovCoverage( cmCTestCoverageHandlerLocale locale_C; static_cast<void>(locale_C); + std::vector<std::string> covargs = + cmSystemTools::ParseArguments(lcovExtraFlags.c_str()); + covargs.insert(covargs.begin(), lcovCommand); + const std::string command = joinCommandLine(covargs); + // In intel compiler we have to call codecov only once in each executable // directory. It collects all *.dyn files to generate .dpi file. - for (it = files.begin(); it != files.end(); ++it) { + for (std::string const& f : files) { cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "." << std::flush, this->Quiet); - std::string fileDir = cmSystemTools::GetFilenamePath(*it); + std::string fileDir = cmSystemTools::GetFilenamePath(f); cmWorkingDirectory workdir(fileDir); - std::string command = "\"" + lcovCommand + "\" " + lcovExtraFlags + " "; cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Current coverage dir: " << fileDir << std::endl, @@ -1375,15 +1387,14 @@ int cmCTestCoverageHandler::HandleLCovCoverage( int retVal = 0; *cont->OFS << "* Run coverage for: " << fileDir << std::endl; *cont->OFS << " Command: " << command << std::endl; - int res = - this->CTest->RunCommand(command.c_str(), &output, &errors, &retVal, - fileDir.c_str(), 0 /*this->TimeOut*/); + int res = this->CTest->RunCommand(covargs, &output, &errors, &retVal, + fileDir.c_str(), 0 /*this->TimeOut*/); *cont->OFS << " Output: " << output << std::endl; *cont->OFS << " Errors: " << errors << std::endl; if (!res) { cmCTestLog(this->CTest, ERROR_MESSAGE, - "Problem running coverage on file: " << *it << std::endl); + "Problem running coverage on file: " << f << std::endl); cmCTestLog(this->CTest, ERROR_MESSAGE, "Command produced error: " << errors << std::endl); cont->Error++; @@ -1391,7 +1402,7 @@ int cmCTestCoverageHandler::HandleLCovCoverage( } if (retVal != 0) { cmCTestLog(this->CTest, ERROR_MESSAGE, "Coverage command returned: " - << retVal << " while processing: " << *it << std::endl); + << retVal << " while processing: " << f << std::endl); cmCTestLog(this->CTest, ERROR_MESSAGE, "Command produced error: " << cont->Error << std::endl); } @@ -1405,15 +1416,14 @@ int cmCTestCoverageHandler::HandleLCovCoverage( this->Quiet); std::vector<std::string> lines; - std::vector<std::string>::iterator line; cmSystemTools::Split(output.c_str(), lines); - for (line = lines.begin(); line != lines.end(); ++line) { + for (std::string const& line : lines) { std::string sourceFile; std::string lcovFile; - if (line->empty()) { + if (line.empty()) { // Ignore empty line } // Look for LCOV files in binary directory @@ -1436,9 +1446,8 @@ int cmCTestCoverageHandler::HandleLCovCoverage( lcovFiles.insert(lcovFiles.end(), gl.GetFiles().begin(), gl.GetFiles().end()); - for (std::vector<std::string>::iterator a = lcovFiles.begin(); - a != lcovFiles.end(); ++a) { - lcovFile = *a; + for (std::string const& file : lcovFiles) { + lcovFile = file; cmsys::ifstream srcead(lcovFile.c_str()); if (!srcead) { cmCTestLog(this->CTest, ERROR_MESSAGE, @@ -1460,10 +1469,9 @@ int cmCTestCoverageHandler::HandleLCovCoverage( sourceFile = srcname; actualSourceFile = srcname; - for (std::vector<std::string>::iterator t = lcovFiles.begin(); - t != lcovFiles.end(); ++t) { + for (std::string const& t : lcovFiles) { cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, - "Found LCOV File: " << *t << std::endl, + "Found LCOV File: " << t << std::endl, this->Quiet); } cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, @@ -1535,7 +1543,7 @@ int cmCTestCoverageHandler::HandleLCovCoverage( } } - actualSourceFile = ""; + actualSourceFile.clear(); } } } @@ -1560,10 +1568,9 @@ void cmCTestCoverageHandler::FindGCovFiles(std::vector<std::string>& files) gl.RecurseOn(); gl.RecurseThroughSymlinksOff(); - for (LabelMapType::const_iterator lmi = this->TargetDirs.begin(); - lmi != this->TargetDirs.end(); ++lmi) { + for (auto const& lm : this->TargetDirs) { // Skip targets containing no interesting labels. - if (!this->IntersectsFilter(lmi->second)) { + if (!this->IntersectsFilter(lm.second)) { continue; } @@ -1571,12 +1578,12 @@ void cmCTestCoverageHandler::FindGCovFiles(std::vector<std::string>& files) // support directory. cmCTestOptionalLog( this->CTest, HANDLER_VERBOSE_OUTPUT, - " globbing for coverage in: " << lmi->first << std::endl, this->Quiet); - std::string daGlob = lmi->first; + " globbing for coverage in: " << lm.first << std::endl, this->Quiet); + std::string daGlob = lm.first; daGlob += "/*.da"; gl.FindFiles(daGlob); files.insert(files.end(), gl.GetFiles().begin(), gl.GetFiles().end()); - daGlob = lmi->first; + daGlob = lm.first; daGlob += "/*.gcda"; gl.FindFiles(daGlob); files.insert(files.end(), gl.GetFiles().begin(), gl.GetFiles().end()); @@ -1639,14 +1646,13 @@ int cmCTestCoverageHandler::HandleTracePyCoverage( std::string tempDir = testingDir + "/CoverageInfo"; cmSystemTools::MakeDirectory(tempDir.c_str()); - std::vector<std::string>::iterator fileIt; int file_count = 0; - for (fileIt = files.begin(); fileIt != files.end(); ++fileIt) { - std::string fileName = this->FindFile(cont, *fileIt); + for (std::string const& file : files) { + std::string fileName = this->FindFile(cont, file); if (fileName.empty()) { cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot find source Python file corresponding to: " - << *fileIt << std::endl); + << file << std::endl); continue; } @@ -1658,11 +1664,11 @@ int cmCTestCoverageHandler::HandleTracePyCoverage( cmCTestCoverageHandlerContainer::SingleFileCoverageVector* vec = &cont->TotalCoverage[actualSourceFile]; cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, - " in file: " << *fileIt << std::endl, this->Quiet); - cmsys::ifstream ifile(fileIt->c_str()); + " in file: " << file << std::endl, this->Quiet); + cmsys::ifstream ifile(file.c_str()); if (!ifile) { cmCTestLog(this->CTest, ERROR_MESSAGE, - "Cannot open file: " << *fileIt << std::endl); + "Cannot open file: " << file << std::endl); } else { long cnt = -1; std::string nl; @@ -2012,8 +2018,8 @@ int cmCTestCoverageHandler::RunBullseyeSourceSummary( file += sourceFile; } file = cmSystemTools::CollapseFullPath(file); - bool shouldIDoCoverage = this->ShouldIDoCoverage( - file.c_str(), cont->SourceDir.c_str(), cont->BinaryDir.c_str()); + bool shouldIDoCoverage = + this->ShouldIDoCoverage(file, cont->SourceDir, cont->BinaryDir); if (!shouldIDoCoverage) { cmCTestOptionalLog( this->CTest, HANDLER_VERBOSE_OUTPUT, @@ -2254,9 +2260,8 @@ void cmCTestCoverageHandler::WriteXMLLabels(cmXMLWriter& xml, LabelMapType::const_iterator li = this->SourceLabels.find(source); if (li != this->SourceLabels.end() && !li->second.empty()) { xml.StartElement("Labels"); - for (LabelSet::const_iterator lsi = li->second.begin(); - lsi != li->second.end(); ++lsi) { - xml.Element("Label", this->Labels[*lsi]); + for (auto const& ls : li->second) { + xml.Element("Label", this->Labels[ls]); } xml.EndElement(); // Labels } @@ -2266,9 +2271,8 @@ void cmCTestCoverageHandler::SetLabelFilter( std::set<std::string> const& labels) { this->LabelFilter.clear(); - for (std::set<std::string>::const_iterator li = labels.begin(); - li != labels.end(); ++li) { - this->LabelFilter.insert(this->GetLabelId(*li)); + for (std::string const& l : labels) { + this->LabelFilter.insert(this->GetLabelId(l)); } } @@ -2308,29 +2312,23 @@ std::set<std::string> cmCTestCoverageHandler::FindUncoveredFiles( { std::set<std::string> extraMatches; - for (std::vector<std::string>::iterator i = this->ExtraCoverageGlobs.begin(); - i != this->ExtraCoverageGlobs.end(); ++i) { + for (std::string const& ecg : this->ExtraCoverageGlobs) { cmsys::Glob gl; gl.RecurseOn(); gl.RecurseThroughSymlinksOff(); - std::string glob = cont->SourceDir + "/" + *i; + std::string glob = cont->SourceDir + "/" + ecg; gl.FindFiles(glob); std::vector<std::string> files = gl.GetFiles(); - for (std::vector<std::string>::iterator f = files.begin(); - f != files.end(); ++f) { - if (this->ShouldIDoCoverage(f->c_str(), cont->SourceDir.c_str(), - cont->BinaryDir.c_str())) { - extraMatches.insert(this->CTest->GetShortPathToFile(f->c_str())); + for (std::string const& f : files) { + if (this->ShouldIDoCoverage(f, cont->SourceDir, cont->BinaryDir)) { + extraMatches.insert(this->CTest->GetShortPathToFile(f.c_str())); } } } if (!extraMatches.empty()) { - for (cmCTestCoverageHandlerContainer::TotalCoverageMap::iterator i = - cont->TotalCoverage.begin(); - i != cont->TotalCoverage.end(); ++i) { - std::string shortPath = - this->CTest->GetShortPathToFile(i->first.c_str()); + for (auto const& i : cont->TotalCoverage) { + std::string shortPath = this->CTest->GetShortPathToFile(i.first.c_str()); extraMatches.erase(shortPath); } } diff --git a/Source/CTest/cmCTestCoverageHandler.h b/Source/CTest/cmCTestCoverageHandler.h index 83eb561..6492fe9 100644 --- a/Source/CTest/cmCTestCoverageHandler.h +++ b/Source/CTest/cmCTestCoverageHandler.h @@ -42,23 +42,23 @@ public: /* * The main entry point for this class */ - int ProcessHandler() CM_OVERRIDE; + int ProcessHandler() override; cmCTestCoverageHandler(); - void Initialize() CM_OVERRIDE; + void Initialize() override; /** * This method is called when reading CTest custom file */ - void PopulateCustomVectors(cmMakefile* mf) CM_OVERRIDE; + void PopulateCustomVectors(cmMakefile* mf) override; /** Report coverage only for sources with these labels. */ void SetLabelFilter(std::set<std::string> const& labels); private: - bool ShouldIDoCoverage(const char* file, const char* srcDir, - const char* binDir); + bool ShouldIDoCoverage(std::string const& file, std::string const& srcDir, + std::string const& binDir); void CleanCoverageLogFiles(std::ostream& log); bool StartCoverageLogFile(cmGeneratedFileStream& ostr, int logFileCount); void EndCoverageLogFile(cmGeneratedFileStream& ostr, int logFileCount); diff --git a/Source/CTest/cmCTestCurl.cxx b/Source/CTest/cmCTestCurl.cxx index b175d44..7b5ea60 100644 --- a/Source/CTest/cmCTestCurl.cxx +++ b/Source/CTest/cmCTestCurl.cxx @@ -61,12 +61,11 @@ size_t curlDebugCallback(CURL* /*unused*/, curl_infotype /*unused*/, void cmCTestCurl::SetCurlOptions(std::vector<std::string> const& args) { - for (std::vector<std::string>::const_iterator i = args.begin(); - i != args.end(); ++i) { - if (*i == "CURLOPT_SSL_VERIFYPEER_OFF") { + for (std::string const& arg : args) { + if (arg == "CURLOPT_SSL_VERIFYPEER_OFF") { this->VerifyPeerOff = true; } - if (*i == "CURLOPT_SSL_VERIFYHOST_OFF") { + if (arg == "CURLOPT_SSL_VERIFYHOST_OFF") { this->VerifyHostOff = true; } } @@ -110,7 +109,7 @@ bool cmCTestCurl::UploadFile(std::string const& local_file, std::string const& url, std::string const& fields, std::string& response) { - response = ""; + response.clear(); if (!this->InitCurl()) { cmCTestLog(this->CTest, ERROR_MESSAGE, "Initialization of curl failed"); return false; @@ -146,12 +145,11 @@ bool cmCTestCurl::UploadFile(std::string const& local_file, struct curl_slist* headers = ::curl_slist_append(nullptr, "Content-Type: text/xml"); // Add any additional headers that the user specified. - for (std::vector<std::string>::const_iterator h = this->HttpHeaders.begin(); - h != this->HttpHeaders.end(); ++h) { + for (std::string const& h : this->HttpHeaders) { cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, - " Add HTTP Header: \"" << *h << "\"" << std::endl, + " Add HTTP Header: \"" << h << "\"" << std::endl, this->Quiet); - headers = ::curl_slist_append(headers, h->c_str()); + headers = ::curl_slist_append(headers, h.c_str()); } ::curl_easy_setopt(this->Curl, CURLOPT_HTTPHEADER, headers); std::vector<char> responseData; @@ -187,7 +185,7 @@ bool cmCTestCurl::UploadFile(std::string const& local_file, bool cmCTestCurl::HttpRequest(std::string const& url, std::string const& fields, std::string& response) { - response = ""; + response.clear(); cmCTestOptionalLog(this->CTest, DEBUG, "HttpRequest\n" << "url: " << url << "\n" << "fields " << fields << "\n", @@ -213,13 +211,11 @@ bool cmCTestCurl::HttpRequest(std::string const& url, // Add headers if any were specified. struct curl_slist* headers = nullptr; if (!this->HttpHeaders.empty()) { - for (std::vector<std::string>::const_iterator h = - this->HttpHeaders.begin(); - h != this->HttpHeaders.end(); ++h) { + for (std::string const& h : this->HttpHeaders) { cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, - " Add HTTP Header: \"" << *h << "\"" << std::endl, + " Add HTTP Header: \"" << h << "\"" << std::endl, this->Quiet); - headers = ::curl_slist_append(headers, h->c_str()); + headers = ::curl_slist_append(headers, h.c_str()); } } @@ -244,10 +240,10 @@ bool cmCTestCurl::HttpRequest(std::string const& url, void cmCTestCurl::SetProxyType() { - this->HTTPProxy = ""; + this->HTTPProxy.clear(); // this is the default this->HTTPProxyType = CURLPROXY_HTTP; - this->HTTPProxyAuth = ""; + this->HTTPProxyAuth.clear(); if (cmSystemTools::GetEnv("HTTP_PROXY", this->HTTPProxy)) { std::string port; if (cmSystemTools::GetEnv("HTTP_PROXY_PORT", port)) { diff --git a/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h b/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h index 9a8b735..9425ece 100644 --- a/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h +++ b/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h @@ -27,7 +27,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmCTestEmptyBinaryDirectoryCommand* ni = new cmCTestEmptyBinaryDirectoryCommand; @@ -41,7 +41,7 @@ public: * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/CTest/cmCTestGIT.cxx b/Source/CTest/cmCTestGIT.cxx index ed8d932..7fe74af 100644 --- a/Source/CTest/cmCTestGIT.cxx +++ b/Source/CTest/cmCTestGIT.cxx @@ -46,7 +46,7 @@ public: private: std::string& Line1; - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { // Only the first line is of interest. this->Line1 = this->Line; @@ -163,9 +163,8 @@ bool cmCTestGIT::UpdateByFetchAndReset() opts = this->CTest->GetCTestConfiguration("GITUpdateOptions"); } std::vector<std::string> args = cmSystemTools::ParseArguments(opts.c_str()); - for (std::vector<std::string>::const_iterator ai = args.begin(); - ai != args.end(); ++ai) { - git_fetch.push_back(ai->c_str()); + for (std::string const& arg : args) { + git_fetch.push_back(arg.c_str()); } // Sentinel argument. @@ -215,9 +214,8 @@ bool cmCTestGIT::UpdateByCustom(std::string const& custom) std::vector<std::string> git_custom_command; cmSystemTools::ExpandListArgument(custom, git_custom_command, true); std::vector<char const*> git_custom; - for (std::vector<std::string>::const_iterator i = git_custom_command.begin(); - i != git_custom_command.end(); ++i) { - git_custom.push_back(i->c_str()); + for (std::string const& i : git_custom_command) { + git_custom.push_back(i.c_str()); } git_custom.push_back(nullptr); @@ -356,7 +354,7 @@ protected: this->Changes.clear(); } - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (this->Line[0] == ':') { this->DiffField = DiffFieldChange; @@ -514,7 +512,7 @@ private: person.TimeZone = strtol(c, const_cast<char**>(&c), 10); } - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (this->Line.empty()) { if (this->Section == SectionBody && this->LineEnd == '\0') { @@ -655,9 +653,8 @@ bool cmCTestGIT::LoadModifications() OutputLogger err(this->Log, "di-err> "); this->RunChild(git_diff_index, &out, &err, nullptr, cmProcessOutput::UTF8); - for (std::vector<Change>::const_iterator ci = out.Changes.begin(); - ci != out.Changes.end(); ++ci) { - this->DoModification(PathModified, ci->Path); + for (Change const& c : out.Changes) { + this->DoModification(PathModified, c.Path); } return true; } diff --git a/Source/CTest/cmCTestGIT.h b/Source/CTest/cmCTestGIT.h index 222bc50..ade430f 100644 --- a/Source/CTest/cmCTestGIT.h +++ b/Source/CTest/cmCTestGIT.h @@ -22,15 +22,15 @@ public: /** Construct with a CTest instance and update log stream. */ cmCTestGIT(cmCTest* ctest, std::ostream& log); - ~cmCTestGIT() CM_OVERRIDE; + ~cmCTestGIT() override; private: unsigned int CurrentGitVersion; unsigned int GetGitVersion(); std::string GetWorkingRevision(); - bool NoteOldRevision() CM_OVERRIDE; - bool NoteNewRevision() CM_OVERRIDE; - bool UpdateImpl() CM_OVERRIDE; + bool NoteOldRevision() override; + bool NoteNewRevision() override; + bool UpdateImpl() override; std::string FindGitDir(); std::string FindTopDir(); @@ -39,8 +39,8 @@ private: bool UpdateByCustom(std::string const& custom); bool UpdateInternal(); - bool LoadRevisions() CM_OVERRIDE; - bool LoadModifications() CM_OVERRIDE; + bool LoadRevisions() override; + bool LoadModifications() override; // "public" needed by older Sun compilers public: diff --git a/Source/CTest/cmCTestGenericHandler.cxx b/Source/CTest/cmCTestGenericHandler.cxx index 53a4018..ce8f709 100644 --- a/Source/CTest/cmCTestGenericHandler.cxx +++ b/Source/CTest/cmCTestGenericHandler.cxx @@ -57,10 +57,8 @@ void cmCTestGenericHandler::Initialize() this->AppendXML = false; this->TestLoad = 0; this->Options.clear(); - t_StringToString::iterator it; - for (it = this->PersistentOptions.begin(); - it != this->PersistentOptions.end(); ++it) { - this->Options[it->first] = it->second; + for (auto const& po : this->PersistentOptions) { + this->Options[po.first] = po.second; } } diff --git a/Source/CTest/cmCTestGlobalVC.cxx b/Source/CTest/cmCTestGlobalVC.cxx index 25294b5..d2714d90 100644 --- a/Source/CTest/cmCTestGlobalVC.cxx +++ b/Source/CTest/cmCTestGlobalVC.cxx @@ -48,15 +48,14 @@ void cmCTestGlobalVC::DoRevision(Revision const& revision, /* clang-format on */ // Update information about revisions of the changed files. - for (std::vector<Change>::const_iterator ci = changes.begin(); - ci != changes.end(); ++ci) { - if (const char* local = this->LocalPath(ci->Path)) { + for (Change const& c : changes) { + if (const char* local = this->LocalPath(c.Path)) { std::string dir = cmSystemTools::GetFilenamePath(local); std::string name = cmSystemTools::GetFilenameName(local); File& file = this->Dirs[dir][name]; file.PriorRev = file.Rev ? file.Rev : &this->PriorRev; file.Rev = &rev; - this->Log << " " << ci->Action << " " << local << " " + this->Log << " " << c.Action << " " << local << " " << "\n"; } } @@ -83,9 +82,9 @@ void cmCTestGlobalVC::WriteXMLDirectory(cmXMLWriter& xml, const char* slash = path.empty() ? "" : "/"; xml.StartElement("Directory"); xml.Element("Name", path); - for (Directory::const_iterator fi = dir.begin(); fi != dir.end(); ++fi) { - std::string full = path + slash + fi->first; - this->WriteXMLEntry(xml, path, fi->first, full, fi->second); + for (auto const& f : dir) { + std::string const full = path + slash + f.first; + this->WriteXMLEntry(xml, path, f.first, full, f.second); } xml.EndElement(); // Directory } @@ -114,10 +113,8 @@ bool cmCTestGlobalVC::WriteXMLUpdates(cmXMLWriter& xml) this->WriteXMLGlobal(xml); - for (std::map<std::string, Directory>::const_iterator di = - this->Dirs.begin(); - di != this->Dirs.end(); ++di) { - this->WriteXMLDirectory(xml, di->first, di->second); + for (auto const& d : this->Dirs) { + this->WriteXMLDirectory(xml, d.first, d.second); } return result; diff --git a/Source/CTest/cmCTestGlobalVC.h b/Source/CTest/cmCTestGlobalVC.h index b4bf077..76377ed 100644 --- a/Source/CTest/cmCTestGlobalVC.h +++ b/Source/CTest/cmCTestGlobalVC.h @@ -26,11 +26,11 @@ public: /** Construct with a CTest instance and update log stream. */ cmCTestGlobalVC(cmCTest* ctest, std::ostream& log); - ~cmCTestGlobalVC() CM_OVERRIDE; + ~cmCTestGlobalVC() override; protected: // Implement cmCTestVC internal API. - bool WriteXMLUpdates(cmXMLWriter& xml) CM_OVERRIDE; + bool WriteXMLUpdates(cmXMLWriter& xml) override; /** Represent a vcs-reported action for one path in a revision. */ struct Change diff --git a/Source/CTest/cmCTestHG.cxx b/Source/CTest/cmCTestHG.cxx index 7bf5b67..525dacc 100644 --- a/Source/CTest/cmCTestHG.cxx +++ b/Source/CTest/cmCTestHG.cxx @@ -36,7 +36,7 @@ private: std::string& Rev; cmsys::RegularExpression RegexIdentify; - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (this->RegexIdentify.find(this->Line)) { this->Rev = this->RegexIdentify.match(1); @@ -60,7 +60,7 @@ private: cmCTestHG* HG; cmsys::RegularExpression RegexStatus; - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (this->RegexStatus.find(this->Line)) { this->DoPath(this->RegexStatus.match(1)[0], this->RegexStatus.match(2)); @@ -145,9 +145,8 @@ bool cmCTestHG::UpdateImpl() opts = this->CTest->GetCTestConfiguration("HGUpdateOptions"); } std::vector<std::string> args = cmSystemTools::ParseArguments(opts.c_str()); - for (std::vector<std::string>::const_iterator ai = args.begin(); - ai != args.end(); ++ai) { - hg_update.push_back(ai->c_str()); + for (std::string const& arg : args) { + hg_update.push_back(arg.c_str()); } // Sentinel argument. @@ -168,7 +167,7 @@ public: { this->InitializeParser(); } - ~LogParser() CM_OVERRIDE { this->CleanupParser(); } + ~LogParser() override { this->CleanupParser(); } private: cmCTestHG* HG; @@ -179,14 +178,14 @@ private: Change CurChange; std::vector<char> CData; - bool ProcessChunk(const char* data, int length) CM_OVERRIDE + bool ProcessChunk(const char* data, int length) override { this->OutputLogger::ProcessChunk(data, length); this->ParseChunk(data, length); return true; } - void StartElement(const std::string& name, const char** atts) CM_OVERRIDE + void StartElement(const std::string& name, const char** atts) override { this->CData.clear(); if (name == "logentry") { @@ -198,12 +197,12 @@ private: } } - void CharacterDataHandler(const char* data, int length) CM_OVERRIDE + void CharacterDataHandler(const char* data, int length) override { this->CData.insert(this->CData.end(), data, data + length); } - void EndElement(const std::string& name) CM_OVERRIDE + void EndElement(const std::string& name) override { if (name == "logentry") { this->HG->DoRevision(this->Rev, this->Changes); @@ -217,25 +216,25 @@ private: this->Rev.Log.assign(&this->CData[0], this->CData.size()); } else if (!this->CData.empty() && name == "files") { std::vector<std::string> paths = this->SplitCData(); - for (unsigned int i = 0; i < paths.size(); ++i) { + for (std::string const& path : paths) { // Updated by default, will be modified using file_adds and // file_dels. this->CurChange = Change('U'); - this->CurChange.Path = paths[i]; + this->CurChange.Path = path; this->Changes.push_back(this->CurChange); } } else if (!this->CData.empty() && name == "file_adds") { std::string added_paths(this->CData.begin(), this->CData.end()); - for (unsigned int i = 0; i < this->Changes.size(); ++i) { - if (added_paths.find(this->Changes[i].Path) != std::string::npos) { - this->Changes[i].Action = 'A'; + for (Change& change : this->Changes) { + if (added_paths.find(change.Path) != std::string::npos) { + change.Action = 'A'; } } } else if (!this->CData.empty() && name == "file_dels") { std::string added_paths(this->CData.begin(), this->CData.end()); - for (unsigned int i = 0; i < this->Changes.size(); ++i) { - if (added_paths.find(this->Changes[i].Path) != std::string::npos) { - this->Changes[i].Action = 'D'; + for (Change& change : this->Changes) { + if (added_paths.find(change.Path) != std::string::npos) { + change.Action = 'D'; } } } @@ -246,19 +245,19 @@ private: { std::vector<std::string> output; std::string currPath; - for (unsigned int i = 0; i < this->CData.size(); ++i) { - if (this->CData[i] != ' ') { - currPath += this->CData[i]; + for (char i : this->CData) { + if (i != ' ') { + currPath += i; } else { output.push_back(currPath); - currPath = ""; + currPath.clear(); } } output.push_back(currPath); return output; } - void ReportError(int /*line*/, int /*column*/, const char* msg) CM_OVERRIDE + void ReportError(int /*line*/, int /*column*/, const char* msg) override { this->HG->Log << "Error parsing hg log xml: " << msg << "\n"; } diff --git a/Source/CTest/cmCTestHG.h b/Source/CTest/cmCTestHG.h index 90c38dc..c12d618 100644 --- a/Source/CTest/cmCTestHG.h +++ b/Source/CTest/cmCTestHG.h @@ -22,16 +22,16 @@ public: /** Construct with a CTest instance and update log stream. */ cmCTestHG(cmCTest* ctest, std::ostream& log); - ~cmCTestHG() CM_OVERRIDE; + ~cmCTestHG() override; private: std::string GetWorkingRevision(); - bool NoteOldRevision() CM_OVERRIDE; - bool NoteNewRevision() CM_OVERRIDE; - bool UpdateImpl() CM_OVERRIDE; + bool NoteOldRevision() override; + bool NoteNewRevision() override; + bool UpdateImpl() override; - bool LoadRevisions() CM_OVERRIDE; - bool LoadModifications() CM_OVERRIDE; + bool LoadRevisions() override; + bool LoadModifications() override; // Parsing helper classes. class IdentifyParser; diff --git a/Source/CTest/cmCTestHandlerCommand.cxx b/Source/CTest/cmCTestHandlerCommand.cxx index 9266d1f..5a7baf5 100644 --- a/Source/CTest/cmCTestHandlerCommand.cxx +++ b/Source/CTest/cmCTestHandlerCommand.cxx @@ -97,12 +97,11 @@ bool cmCTestHandlerCommand::InitialPass(std::vector<std::string> const& args, // bad one so that CAPTURE_CMAKE_ERROR can override setting the // global error state bool foundBadArgument = false; - for (unsigned int i = 0; i < args.size(); ++i) { + for (std::string const& arg : args) { // Check this argument. - if (!this->CheckArgumentKeyword(args[i]) && - !this->CheckArgumentValue(args[i])) { + if (!this->CheckArgumentKeyword(arg) && !this->CheckArgumentValue(arg)) { std::ostringstream e; - e << "called with unknown argument \"" << args[i] << "\"."; + e << "called with unknown argument \"" << arg << "\"."; this->SetError(e.str()); foundBadArgument = true; } diff --git a/Source/CTest/cmCTestHandlerCommand.h b/Source/CTest/cmCTestHandlerCommand.h index b838074..79d61f3 100644 --- a/Source/CTest/cmCTestHandlerCommand.h +++ b/Source/CTest/cmCTestHandlerCommand.h @@ -34,7 +34,7 @@ public: * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; enum { diff --git a/Source/CTest/cmCTestLaunch.cxx b/Source/CTest/cmCTestLaunch.cxx index 041cc92..a1249f5 100644 --- a/Source/CTest/cmCTestLaunch.cxx +++ b/Source/CTest/cmCTestLaunch.cxx @@ -6,6 +6,7 @@ #include "cmsys/Process.h" #include "cmsys/RegularExpression.hxx" #include <iostream> +#include <memory> // IWYU pragma: keep #include <stdlib.h> #include <string.h> @@ -17,7 +18,6 @@ #include "cmStateSnapshot.h" #include "cmSystemTools.h" #include "cmXMLWriter.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" #ifdef _WIN32 @@ -169,9 +169,8 @@ void cmCTestLaunch::ComputeFileNames() cmCryptoHash md5(cmCryptoHash::AlgoMD5); md5.Initialize(); md5.Append(this->CWD); - for (std::vector<std::string>::const_iterator ai = this->RealArgs.begin(); - ai != this->RealArgs.end(); ++ai) { - md5.Append(*ai); + for (std::string const& realArg : this->RealArgs) { + md5.Append(realArg); } this->LogHash = md5.FinalizeHex(); @@ -422,9 +421,8 @@ void cmCTestLaunch::WriteXMLCommand(cmXMLWriter& xml) if (!this->CWD.empty()) { xml.Element("WorkingDirectory", this->CWD); } - for (std::vector<std::string>::const_iterator ai = this->RealArgs.begin(); - ai != this->RealArgs.end(); ++ai) { - xml.Element("Argument", *ai); + for (std::string const& realArg : this->RealArgs) { + xml.Element("Argument", realArg); } xml.EndElement(); // Command } @@ -487,9 +485,8 @@ void cmCTestLaunch::WriteXMLLabels(cmXMLWriter& xml) if (!this->Labels.empty()) { xml.Comment("Interested parties"); xml.StartElement("Labels"); - for (std::set<std::string>::const_iterator li = this->Labels.begin(); - li != this->Labels.end(); ++li) { - xml.Element("Label", *li); + for (std::string const& label : this->Labels) { + xml.Element("Label", label); } xml.EndElement(); // Labels } @@ -597,9 +594,8 @@ bool cmCTestLaunch::ScrapeLog(std::string const& fname) bool cmCTestLaunch::Match(std::string const& line, std::vector<cmsys::RegularExpression>& regexps) { - for (std::vector<cmsys::RegularExpression>::iterator ri = regexps.begin(); - ri != regexps.end(); ++ri) { - if (ri->find(line.c_str())) { + for (cmsys::RegularExpression& r : regexps) { + if (r.find(line.c_str())) { return true; } } @@ -630,12 +626,12 @@ void cmCTestLaunch::LoadConfig() cm.SetHomeOutputDirectory(""); cm.GetCurrentSnapshot().SetDefaultDefinitions(); cmGlobalGenerator gg(&cm); - CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot())); + cmMakefile mf(&gg, cm.GetCurrentSnapshot()); std::string fname = this->LogDir; fname += "CTestLaunchConfig.cmake"; if (cmSystemTools::FileExists(fname.c_str()) && - mf->ReadListFile(fname.c_str())) { - this->SourceDir = mf->GetSafeDefinition("CTEST_SOURCE_DIRECTORY"); + mf.ReadListFile(fname.c_str())) { + this->SourceDir = mf.GetSafeDefinition("CTEST_SOURCE_DIRECTORY"); cmSystemTools::ConvertToUnixSlashes(this->SourceDir); } } diff --git a/Source/CTest/cmCTestMemCheckCommand.h b/Source/CTest/cmCTestMemCheckCommand.h index aaa8c6b..b6b3c40 100644 --- a/Source/CTest/cmCTestMemCheckCommand.h +++ b/Source/CTest/cmCTestMemCheckCommand.h @@ -23,7 +23,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmCTestMemCheckCommand* ni = new cmCTestMemCheckCommand; ni->CTest = this->CTest; @@ -32,9 +32,9 @@ public: } protected: - cmCTestGenericHandler* InitializeActualHandler() CM_OVERRIDE; + cmCTestGenericHandler* InitializeActualHandler() override; - void ProcessAdditionalValues(cmCTestGenericHandler* handler) CM_OVERRIDE; + void ProcessAdditionalValues(cmCTestGenericHandler* handler) override; enum { diff --git a/Source/CTest/cmCTestMemCheckHandler.cxx b/Source/CTest/cmCTestMemCheckHandler.cxx index 7d11550..3efb039 100644 --- a/Source/CTest/cmCTestMemCheckHandler.cxx +++ b/Source/CTest/cmCTestMemCheckHandler.cxx @@ -33,7 +33,7 @@ static CatToErrorType cmCTestMemCheckBoundsChecker[] = { static void xmlReportError(int line, const char* msg, void* data) { - cmCTest* ctest = reinterpret_cast<cmCTest*>(data); + cmCTest* ctest = static_cast<cmCTest*>(data); cmCTestLog(ctest, ERROR_MESSAGE, "Error parsing XML in stream at line " << line << ": " << msg << std::endl); } @@ -47,7 +47,7 @@ public: this->CTest = c; this->SetErrorCallback(xmlReportError, c); } - void StartElement(const std::string& name, const char** atts) CM_OVERRIDE + void StartElement(const std::string& name, const char** atts) override { if (name == "MemoryLeak" || name == "ResourceLeak") { this->Errors.push_back(cmCTestMemCheckHandler::MLK); @@ -64,7 +64,7 @@ public: ostr << "\n"; this->Log += ostr.str(); } - void EndElement(const std::string& /*name*/) CM_OVERRIDE {} + void EndElement(const std::string& /*name*/) override {} const char* GetAttribute(const char* name, const char** atts) { @@ -122,11 +122,11 @@ void cmCTestMemCheckHandler::Initialize() this->LogWithPID = false; this->CustomMaximumPassedTestOutputSize = 0; this->CustomMaximumFailedTestOutputSize = 0; - this->MemoryTester = ""; + this->MemoryTester.clear(); this->MemoryTesterDynamicOptions.clear(); this->MemoryTesterOptions.clear(); this->MemoryTesterStyle = UNKNOWN; - this->MemoryTesterOutputFile = ""; + this->MemoryTesterOutputFile.clear(); this->DefectCount = 0; } @@ -157,15 +157,13 @@ int cmCTestMemCheckHandler::PostProcessHandler() void cmCTestMemCheckHandler::GenerateTestCommand( std::vector<std::string>& args, int test) { - std::vector<std::string>::size_type pp; std::string index; std::ostringstream stream; std::string memcheckcommand = cmSystemTools::ConvertToOutputPath(this->MemoryTester.c_str()); stream << test; index = stream.str(); - for (pp = 0; pp < this->MemoryTesterDynamicOptions.size(); pp++) { - std::string arg = this->MemoryTesterDynamicOptions[pp]; + for (std::string arg : this->MemoryTesterDynamicOptions) { std::string::size_type pos = arg.find("??"); if (pos != std::string::npos) { arg.replace(pos, 2, index); @@ -180,18 +178,18 @@ void cmCTestMemCheckHandler::GenerateTestCommand( // via environment varaibles. std::string memTesterEnvironmentVariable = this->MemoryTesterEnvironmentVariable; - for (pp = 0; pp < this->MemoryTesterOptions.size(); pp++) { + for (std::string const& arg : this->MemoryTesterOptions) { if (!memTesterEnvironmentVariable.empty()) { // If we are using env to pass options, append all the options to // this string with space separation. - memTesterEnvironmentVariable += " " + this->MemoryTesterOptions[pp]; + memTesterEnvironmentVariable += " " + arg; } // for regular options just add them to args and memcheckcommand // which is just used for display else { - args.push_back(this->MemoryTesterOptions[pp]); + args.push_back(arg); memcheckcommand += " \""; - memcheckcommand += this->MemoryTesterOptions[pp]; + memcheckcommand += arg; memcheckcommand += "\""; } } @@ -326,9 +324,8 @@ void cmCTestMemCheckHandler::GenerateDartOutput(cmXMLWriter& xml) xml.Element("StartTestTime", this->StartTestTime); xml.StartElement("TestList"); cmCTestMemCheckHandler::TestResultsVector::size_type cc; - for (cc = 0; cc < this->TestResults.size(); cc++) { - cmCTestTestResult* result = &this->TestResults[cc]; - std::string testPath = result->Path + "/" + result->Name; + for (cmCTestTestResult const& result : this->TestResults) { + std::string testPath = result.Path + "/" + result.Name; xml.Element("Test", this->CTest->GetShortPathToFile(testPath.c_str())); } xml.EndElement(); // TestList @@ -336,12 +333,12 @@ void cmCTestMemCheckHandler::GenerateDartOutput(cmXMLWriter& xml) "-- Processing memory checking output:\n", this->Quiet); size_t total = this->TestResults.size(); for (cc = 0; cc < this->TestResults.size(); cc++) { - cmCTestTestResult* result = &this->TestResults[cc]; + cmCTestTestResult const& result = this->TestResults[cc]; std::string memcheckstr; std::vector<int> memcheckresults(this->ResultStrings.size(), 0); - bool res = this->ProcessMemCheckOutput(result->Output, memcheckstr, - memcheckresults); - if (res && result->Status == cmCTestMemCheckHandler::COMPLETED) { + bool res = + this->ProcessMemCheckOutput(result.Output, memcheckstr, memcheckresults); + if (res && result.Status == cmCTestMemCheckHandler::COMPLETED) { continue; } this->CleanTestOutput( @@ -364,11 +361,11 @@ void cmCTestMemCheckHandler::GenerateDartOutput(cmXMLWriter& xml) xml.EndElement(); // Results if (memoryErrors > 0) { const int maxTestNameWidth = this->CTest->GetMaxTestNameWidth(); - std::string outname = result->Name + " "; + std::string outname = result.Name + " "; outname.resize(maxTestNameWidth + 4, '.'); cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, cc + 1 << "/" << total << " MemCheck: #" - << result->TestCount << ": " << outname + << result.TestCount << ": " << outname << " Defects: " << memoryErrors << std::endl, this->Quiet); } @@ -420,8 +417,8 @@ void cmCTestMemCheckHandler::GenerateDartOutput(cmXMLWriter& xml) bool cmCTestMemCheckHandler::InitializeMemoryChecking() { - this->MemoryTesterEnvironmentVariable = ""; - this->MemoryTester = ""; + this->MemoryTesterEnvironmentVariable.clear(); + this->MemoryTester.clear(); // Setup the command if (cmSystemTools::FileExists( this->CTest->GetCTestConfiguration("MemoryCheckCommand").c_str())) { @@ -728,13 +725,12 @@ bool cmCTestMemCheckHandler::ProcessMemCheckSanitizerOutput( std::vector<std::string> lines; cmSystemTools::Split(str.c_str(), lines); std::ostringstream ostr; - log = ""; - for (std::vector<std::string>::iterator i = lines.begin(); i != lines.end(); - ++i) { + log.clear(); + for (std::string const& l : lines) { std::string resultFound; - if (leakWarning.find(*i)) { + if (leakWarning.find(l)) { resultFound = leakWarning.match(1) + " leak"; - } else if (sanitizerWarning.find(*i)) { + } else if (sanitizerWarning.find(l)) { resultFound = sanitizerWarning.match(1); } if (!resultFound.empty()) { @@ -747,7 +743,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckSanitizerOutput( defects++; ostr << "<b>" << this->ResultStrings[idx] << "</b> "; } - ostr << *i << std::endl; + ostr << l << std::endl; } log = ostr.str(); this->DefectCount += defects; @@ -759,16 +755,15 @@ bool cmCTestMemCheckHandler::ProcessMemCheckPurifyOutput( std::vector<std::string> lines; cmSystemTools::Split(str.c_str(), lines); std::ostringstream ostr; - log = ""; + log.clear(); cmsys::RegularExpression pfW("^\\[[WEI]\\] ([A-Z][A-Z][A-Z][A-Z]*): "); int defects = 0; - for (std::vector<std::string>::iterator i = lines.begin(); i != lines.end(); - ++i) { + for (std::string const& l : lines) { std::vector<int>::size_type failure = this->ResultStrings.size(); - if (pfW.find(*i)) { + if (pfW.find(l)) { std::vector<int>::size_type cc; for (cc = 0; cc < this->ResultStrings.size(); cc++) { if (pfW.match(1) == this->ResultStrings[cc]) { @@ -788,7 +783,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckPurifyOutput( results[failure]++; defects++; } - ostr << *i << std::endl; + ostr << l << std::endl; } log = ostr.str(); @@ -810,7 +805,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckValgrindOutput( std::string::size_type cc; std::ostringstream ostr; - log = ""; + log.clear(); int defects = 0; @@ -908,11 +903,9 @@ bool cmCTestMemCheckHandler::ProcessMemCheckValgrindOutput( // Now put all all the non valgrind output into the test output // This should be last in case it gets truncated by the output // limiting code - for (std::vector<std::string::size_type>::iterator i = - nonValGrindOutput.begin(); - i != nonValGrindOutput.end(); ++i) { - totalOutputSize += lines[*i].size(); - ostr << lines[*i] << std::endl; + for (std::string::size_type i : nonValGrindOutput) { + totalOutputSize += lines[i].size(); + ostr << lines[i] << std::endl; if (!unlimitedOutput && totalOutputSize > static_cast<size_t>(this->CustomMaximumFailedTestOutputSize)) { @@ -935,7 +928,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckValgrindOutput( bool cmCTestMemCheckHandler::ProcessMemCheckBoundsCheckerOutput( const std::string& str, std::string& log, std::vector<int>& results) { - log = ""; + log.clear(); double sttime = cmSystemTools::GetTime(); std::vector<std::string> lines; cmSystemTools::Split(str.c_str(), lines); @@ -963,8 +956,8 @@ bool cmCTestMemCheckHandler::ProcessMemCheckBoundsCheckerOutput( } } int defects = 0; - for (cc = 0; cc < parser.Errors.size(); ++cc) { - results[parser.Errors[cc]]++; + for (int err : parser.Errors) { + results[err]++; defects++; } cmCTestOptionalLog(this->CTest, DEBUG, "End test (elapsed: " @@ -991,9 +984,8 @@ void cmCTestMemCheckHandler::PostProcessTest(cmCTestTestResult& res, int test) } else { std::vector<std::string> files; this->TestOutputFileNames(test, files); - for (std::vector<std::string>::iterator i = files.begin(); - i != files.end(); ++i) { - this->AppendMemTesterOutput(res, *i); + for (std::string const& f : files) { + this->AppendMemTesterOutput(res, f); } } } @@ -1087,7 +1079,7 @@ void cmCTestMemCheckHandler::TestOutputFileNames( if (g.GetFiles().empty()) { std::string log = "Cannot find memory tester output file: " + ofile; cmCTestLog(this->CTest, ERROR_MESSAGE, log << std::endl); - ofile = ""; + ofile.clear(); } else { files = g.GetFiles(); return; @@ -1095,7 +1087,7 @@ void cmCTestMemCheckHandler::TestOutputFileNames( } else if (!cmSystemTools::FileExists(ofile.c_str())) { std::string log = "Cannot find memory tester output file: " + ofile; cmCTestLog(this->CTest, ERROR_MESSAGE, log << std::endl); - ofile = ""; + ofile.clear(); } files.push_back(ofile); } diff --git a/Source/CTest/cmCTestMemCheckHandler.h b/Source/CTest/cmCTestMemCheckHandler.h index 1228c42..9218294 100644 --- a/Source/CTest/cmCTestMemCheckHandler.h +++ b/Source/CTest/cmCTestMemCheckHandler.h @@ -24,19 +24,18 @@ class cmCTestMemCheckHandler : public cmCTestTestHandler public: typedef cmCTestTestHandler Superclass; - void PopulateCustomVectors(cmMakefile* mf) CM_OVERRIDE; + void PopulateCustomVectors(cmMakefile* mf) override; cmCTestMemCheckHandler(); - void Initialize() CM_OVERRIDE; + void Initialize() override; int GetDefectCount(); protected: - int PreProcessHandler() CM_OVERRIDE; - int PostProcessHandler() CM_OVERRIDE; - void GenerateTestCommand(std::vector<std::string>& args, - int test) CM_OVERRIDE; + int PreProcessHandler() override; + int PostProcessHandler() override; + void GenerateTestCommand(std::vector<std::string>& args, int test) override; private: enum @@ -121,7 +120,7 @@ private: /** * Generate the Dart compatible output */ - void GenerateDartOutput(cmXMLWriter& xml) CM_OVERRIDE; + void GenerateDartOutput(cmXMLWriter& xml) override; std::vector<std::string> CustomPreMemCheck; std::vector<std::string> CustomPostMemCheck; diff --git a/Source/CTest/cmCTestMultiProcessHandler.cxx b/Source/CTest/cmCTestMultiProcessHandler.cxx index 2c16a0d..6a7bdc0 100644 --- a/Source/CTest/cmCTestMultiProcessHandler.cxx +++ b/Source/CTest/cmCTestMultiProcessHandler.cxx @@ -64,10 +64,9 @@ void cmCTestMultiProcessHandler::SetTests(TestMap& tests, this->Properties = properties; this->Total = this->Tests.size(); // set test run map to false for all - for (TestMap::iterator i = this->Tests.begin(); i != this->Tests.end(); - ++i) { - this->TestRunningMap[i->first] = false; - this->TestFinishMap[i->first] = false; + for (auto const& t : this->Tests) { + this->TestRunningMap[t.first] = false; + this->TestFinishMap[t.first] = false; } if (!this->CTest->GetShowOnly()) { this->ReadCostData(); @@ -131,11 +130,10 @@ void cmCTestMultiProcessHandler::StartTestProcess(int test) // Find any failed dependencies for this test. We assume the more common // scenario has no failed tests, so make it the outer loop. - for (std::vector<std::string>::const_iterator it = this->Failed->begin(); - it != this->Failed->end(); ++it) { - if (this->Properties[test]->RequireSuccessDepends.find(*it) != + for (std::string const& f : *this->Failed) { + if (this->Properties[test]->RequireSuccessDepends.find(f) != this->Properties[test]->RequireSuccessDepends.end()) { - testRun->AddFailedDependency(*it); + testRun->AddFailedDependency(f); } } @@ -152,9 +150,8 @@ void cmCTestMultiProcessHandler::StartTestProcess(int test) return; } else { - for (TestMap::iterator j = this->Tests.begin(); j != this->Tests.end(); - ++j) { - j->second.erase(test); + for (auto& j : this->Tests) { + j.second.erase(test); } this->UnlockResources(test); @@ -183,10 +180,8 @@ void cmCTestMultiProcessHandler::LockResources(int index) void cmCTestMultiProcessHandler::UnlockResources(int index) { - for (std::set<std::string>::iterator i = - this->Properties[index]->LockedResources.begin(); - i != this->Properties[index]->LockedResources.end(); ++i) { - this->LockedResources.erase(*i); + for (std::string const& i : this->Properties[index]->LockedResources) { + this->LockedResources.erase(i); } if (this->Properties[index]->RunSerial) { this->SerialTestRunning = false; @@ -219,10 +214,8 @@ std::string cmCTestMultiProcessHandler::GetName(int test) bool cmCTestMultiProcessHandler::StartTest(int test) { // Check for locked resources - for (std::set<std::string>::iterator i = - this->Properties[test]->LockedResources.begin(); - i != this->Properties[test]->LockedResources.end(); ++i) { - if (this->LockedResources.find(*i) != this->LockedResources.end()) { + for (std::string const& i : this->Properties[test]->LockedResources) { + if (this->LockedResources.find(i) != this->LockedResources.end()) { return false; } } @@ -292,22 +285,22 @@ void cmCTestMultiProcessHandler::StartNextTests() } TestList copy = this->SortedTests; - for (TestList::iterator test = copy.begin(); test != copy.end(); ++test) { + for (auto const& test : copy) { // Take a nap if we're currently performing a RUN_SERIAL test. if (this->SerialTestRunning) { break; } // We can only start a RUN_SERIAL test if no other tests are also running. - if (this->Properties[*test]->RunSerial && this->RunningCount > 0) { + if (this->Properties[test]->RunSerial && this->RunningCount > 0) { continue; } - size_t processors = GetProcessorsUsed(*test); + size_t processors = GetProcessorsUsed(test); bool testLoadOk = true; if (this->TestLoad > 0) { if (processors <= spareLoad) { cmCTestLog(this->CTest, DEBUG, "OK to run " - << GetName(*test) << ", it requires " << processors + << GetName(test) << ", it requires " << processors << " procs & system load is: " << systemLoad << std::endl); allTestsFailedTestLoadCheck = false; @@ -318,10 +311,10 @@ void cmCTestMultiProcessHandler::StartNextTests() if (processors <= minProcessorsRequired) { minProcessorsRequired = processors; - testWithMinProcessors = GetName(*test); + testWithMinProcessors = GetName(test); } - if (testLoadOk && processors <= numToStart && this->StartTest(*test)) { + if (testLoadOk && processors <= numToStart && this->StartTest(test)) { if (this->StopTimePassed) { return; } @@ -368,18 +361,13 @@ bool cmCTestMultiProcessHandler::CheckOutput() } std::vector<cmCTestRunTest*> finished; std::string out, err; - for (std::set<cmCTestRunTest*>::const_iterator i = - this->RunningTests.begin(); - i != this->RunningTests.end(); ++i) { - cmCTestRunTest* p = *i; + for (cmCTestRunTest* p : this->RunningTests) { if (!p->CheckOutput()) { finished.push_back(p); } } - for (std::vector<cmCTestRunTest*>::iterator i = finished.begin(); - i != finished.end(); ++i) { + for (cmCTestRunTest* p : finished) { this->Completed++; - cmCTestRunTest* p = *i; int test = p->GetIndex(); bool testResult = p->EndTest(this->Completed, this->Total, true); @@ -392,9 +380,8 @@ bool cmCTestMultiProcessHandler::CheckOutput() } else { this->Failed->push_back(p->GetTestProperties()->Name); } - for (TestMap::iterator j = this->Tests.begin(); j != this->Tests.end(); - ++j) { - j->second.erase(test); + for (auto& t : this->Tests) { + t.second.erase(test); } this->TestFinishMap[test] = true; this->TestRunningMap[test] = false; @@ -451,16 +438,15 @@ void cmCTestMultiProcessHandler::UpdateCostData() } // Add all tests not previously listed in the file - for (PropertiesMap::iterator i = temp.begin(); i != temp.end(); ++i) { - fout << i->second->Name << " " << i->second->PreviousRuns << " " - << i->second->Cost << "\n"; + for (auto const& i : temp) { + fout << i.second->Name << " " << i.second->PreviousRuns << " " + << i.second->Cost << "\n"; } // Write list of failed tests fout << "---\n"; - for (std::vector<std::string>::iterator i = this->Failed->begin(); - i != this->Failed->end(); ++i) { - fout << *i << "\n"; + for (std::string const& f : *this->Failed) { + fout << f << "\n"; } fout.close(); cmSystemTools::RenameFile(tmpout.c_str(), fname.c_str()); @@ -505,7 +491,7 @@ void cmCTestMultiProcessHandler::ReadCostData() } // Next part of the file is the failed tests while (std::getline(fin, line)) { - if (line != "") { + if (!line.empty()) { this->LastTestsFailed.push_back(line); } } @@ -517,10 +503,9 @@ int cmCTestMultiProcessHandler::SearchByName(std::string const& name) { int index = -1; - for (PropertiesMap::iterator i = this->Properties.begin(); - i != this->Properties.end(); ++i) { - if (i->second->Name == name) { - index = i->first; + for (auto const& p : this->Properties) { + if (p.second->Name == name) { + index = p.first; } } return index; @@ -545,16 +530,15 @@ void cmCTestMultiProcessHandler::CreateParallelTestCostList() // In parallel test runs add previously failed tests to the front // of the cost list and queue other tests for further sorting - for (TestMap::const_iterator i = this->Tests.begin(); i != this->Tests.end(); - ++i) { + for (auto const& t : this->Tests) { if (std::find(this->LastTestsFailed.begin(), this->LastTestsFailed.end(), - this->Properties[i->first]->Name) != + this->Properties[t.first]->Name) != this->LastTestsFailed.end()) { // If the test failed last time, it should be run first. - this->SortedTests.push_back(i->first); - alreadySortedTests.insert(i->first); + this->SortedTests.push_back(t.first); + alreadySortedTests.insert(t.first); } else { - topLevel.insert(i->first); + topLevel.insert(t.first); } } @@ -566,15 +550,13 @@ void cmCTestMultiProcessHandler::CreateParallelTestCostList() priorityStack.push_back(TestSet()); TestSet& currentSet = priorityStack.back(); - for (TestSet::const_iterator i = previousSet.begin(); - i != previousSet.end(); ++i) { - TestSet const& dependencies = this->Tests[*i]; + for (auto const& i : previousSet) { + TestSet const& dependencies = this->Tests[i]; currentSet.insert(dependencies.begin(), dependencies.end()); } - for (TestSet::const_iterator i = currentSet.begin(); i != currentSet.end(); - ++i) { - previousSet.erase(*i); + for (auto const& i : currentSet) { + previousSet.erase(i); } } @@ -594,11 +576,10 @@ void cmCTestMultiProcessHandler::CreateParallelTestCostList() std::stable_sort(sortedCopy.begin(), sortedCopy.end(), comp); - for (TestList::const_iterator j = sortedCopy.begin(); - j != sortedCopy.end(); ++j) { - if (alreadySortedTests.find(*j) == alreadySortedTests.end()) { - this->SortedTests.push_back(*j); - alreadySortedTests.insert(*j); + for (auto const& j : sortedCopy) { + if (alreadySortedTests.find(j) == alreadySortedTests.end()) { + this->SortedTests.push_back(j); + alreadySortedTests.insert(j); } } } @@ -608,10 +589,9 @@ void cmCTestMultiProcessHandler::GetAllTestDependencies(int test, TestList& dependencies) { TestSet const& dependencySet = this->Tests[test]; - for (TestSet::const_iterator i = dependencySet.begin(); - i != dependencySet.end(); ++i) { - GetAllTestDependencies(*i, dependencies); - dependencies.push_back(*i); + for (int i : dependencySet) { + GetAllTestDependencies(i, dependencies); + dependencies.push_back(i); } } @@ -619,9 +599,8 @@ void cmCTestMultiProcessHandler::CreateSerialTestCostList() { TestList presortedList; - for (TestMap::iterator i = this->Tests.begin(); i != this->Tests.end(); - ++i) { - presortedList.push_back(i->first); + for (auto const& i : this->Tests) { + presortedList.push_back(i.first); } TestComparator comp(this); @@ -629,10 +608,7 @@ void cmCTestMultiProcessHandler::CreateSerialTestCostList() TestSet alreadySortedTests; - for (TestList::const_iterator i = presortedList.begin(); - i != presortedList.end(); ++i) { - int test = *i; - + for (int test : presortedList) { if (alreadySortedTests.find(test) != alreadySortedTests.end()) { continue; } @@ -640,10 +616,7 @@ void cmCTestMultiProcessHandler::CreateSerialTestCostList() TestList dependencies; GetAllTestDependencies(test, dependencies); - for (TestList::const_iterator j = dependencies.begin(); - j != dependencies.end(); ++j) { - int testDependency = *j; - + for (int testDependency : dependencies) { if (alreadySortedTests.find(testDependency) == alreadySortedTests.end()) { alreadySortedTests.insert(testDependency); @@ -679,10 +652,9 @@ void cmCTestMultiProcessHandler::PrintTestList() this->TestHandler->SetMaxIndex(this->FindMaxIndex()); int count = 0; - for (PropertiesMap::iterator it = this->Properties.begin(); - it != this->Properties.end(); ++it) { + for (auto& it : this->Properties) { count++; - cmCTestTestHandler::cmCTestTestProperties& p = *it->second; + cmCTestTestHandler::cmCTestTestProperties& p = *it.second; cmWorkingDirectory workdir(p.Directory); @@ -696,9 +668,8 @@ void cmCTestMultiProcessHandler::PrintTestList() cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Labels:", this->Quiet); } - for (std::vector<std::string>::iterator label = p.Labels.begin(); - label != p.Labels.end(); ++label) { - cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " " << *label, + for (std::string const& label : p.Labels) { + cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " " << label, this->Quiet); } if (!p.Labels.empty()) // print the labels @@ -737,9 +708,8 @@ void cmCTestMultiProcessHandler::PrintTestList() void cmCTestMultiProcessHandler::PrintLabels() { std::set<std::string> allLabels; - for (PropertiesMap::iterator it = this->Properties.begin(); - it != this->Properties.end(); ++it) { - cmCTestTestHandler::cmCTestTestProperties& p = *it->second; + for (auto& it : this->Properties) { + cmCTestTestHandler::cmCTestTestProperties& p = *it.second; allLabels.insert(p.Labels.begin(), p.Labels.end()); } @@ -750,10 +720,9 @@ void cmCTestMultiProcessHandler::PrintLabels() cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "No Labels Exist" << std::endl, this->Quiet); } - for (std::set<std::string>::iterator label = allLabels.begin(); - label != allLabels.end(); ++label) { - cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, - " " << *label << std::endl, this->Quiet); + for (std::string const& label : allLabels) { + cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " " << label << std::endl, + this->Quiet); } } @@ -794,10 +763,9 @@ void cmCTestMultiProcessHandler::RemoveTest(int index) int cmCTestMultiProcessHandler::FindMaxIndex() { int max = 0; - cmCTestMultiProcessHandler::TestMap::iterator i = this->Tests.begin(); - for (; i != this->Tests.end(); ++i) { - if (i->first > max) { - max = i->first; + for (auto const& i : this->Tests) { + if (i.first > max) { + max = i.first; } } return max; @@ -809,10 +777,9 @@ bool cmCTestMultiProcessHandler::CheckCycles() cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Checking test dependency graph..." << std::endl, this->Quiet); - for (TestMap::iterator it = this->Tests.begin(); it != this->Tests.end(); - ++it) { + for (auto const& it : this->Tests) { // DFS from each element to itself - int root = it->first; + int root = it.first; std::set<int> visited; std::stack<int> s; s.push(root); @@ -820,9 +787,8 @@ bool cmCTestMultiProcessHandler::CheckCycles() int test = s.top(); s.pop(); if (visited.insert(test).second) { - for (TestSet::iterator d = this->Tests[test].begin(); - d != this->Tests[test].end(); ++d) { - if (*d == root) { + for (auto const& d : this->Tests[test]) { + if (d == root) { // cycle exists cmCTestLog( this->CTest, ERROR_MESSAGE, @@ -832,7 +798,7 @@ bool cmCTestMultiProcessHandler::CheckCycles() << "\".\nPlease fix the cycle and run ctest again.\n"); return false; } - s.push(*d); + s.push(d); } } } diff --git a/Source/CTest/cmCTestP4.cxx b/Source/CTest/cmCTestP4.cxx index ab057ad..11f6a00 100644 --- a/Source/CTest/cmCTestP4.cxx +++ b/Source/CTest/cmCTestP4.cxx @@ -37,7 +37,7 @@ private: std::string& Rev; cmsys::RegularExpression RegexIdentify; - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (this->RegexIdentify.find(this->Line)) { this->Rev = this->RegexIdentify.match(1); @@ -61,7 +61,7 @@ private: cmsys::RegularExpression RegexIdentify; cmCTestP4* P4; - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (this->RegexIdentify.find(this->Line)) { P4->ChangeLists.push_back(this->RegexIdentify.match(1)); @@ -84,7 +84,7 @@ private: cmsys::RegularExpression RegexUser; cmCTestP4* P4; - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (this->RegexUser.find(this->Line)) { User NewUser; @@ -127,7 +127,7 @@ private: std::string CurrentPath; cmsys::RegularExpression RegexDiff; - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (!this->Line.empty() && this->Line[0] == '=' && this->RegexDiff.find(this->Line)) { @@ -217,7 +217,7 @@ private: SectionType Section; Revision Rev; - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (this->Line.empty()) { this->NextSection(); @@ -332,9 +332,8 @@ void cmCTestP4::SetP4Options(std::vector<char const*>& CommandOptions) } CommandOptions.clear(); - for (std::vector<std::string>::iterator i = P4Options.begin(); - i != P4Options.end(); ++i) { - CommandOptions.push_back(i->c_str()); + for (std::string const& o : P4Options) { + CommandOptions.push_back(o.c_str()); } } @@ -465,9 +464,8 @@ bool cmCTestP4::UpdateCustom(const std::string& custom) cmSystemTools::ExpandListArgument(custom, p4_custom_command, true); std::vector<char const*> p4_custom; - for (std::vector<std::string>::const_iterator i = p4_custom_command.begin(); - i != p4_custom_command.end(); ++i) { - p4_custom.push_back(i->c_str()); + for (std::string const& i : p4_custom_command) { + p4_custom.push_back(i.c_str()); } p4_custom.push_back(nullptr); @@ -502,9 +500,8 @@ bool cmCTestP4::UpdateImpl() opts = this->CTest->GetCTestConfiguration("P4UpdateOptions"); } std::vector<std::string> args = cmSystemTools::ParseArguments(opts.c_str()); - for (std::vector<std::string>::const_iterator ai = args.begin(); - ai != args.end(); ++ai) { - p4_sync.push_back(ai->c_str()); + for (std::string const& arg : args) { + p4_sync.push_back(arg.c_str()); } std::string source = this->SourceDirectory + "/..."; diff --git a/Source/CTest/cmCTestP4.h b/Source/CTest/cmCTestP4.h index faeeaf2..b14edf7 100644 --- a/Source/CTest/cmCTestP4.h +++ b/Source/CTest/cmCTestP4.h @@ -24,7 +24,7 @@ public: /** Construct with a CTest instance and update log stream. */ cmCTestP4(cmCTest* ctest, std::ostream& log); - ~cmCTestP4() CM_OVERRIDE; + ~cmCTestP4() override; private: std::vector<std::string> ChangeLists; @@ -51,13 +51,13 @@ private: void SetP4Options(std::vector<char const*>& options); std::string GetWorkingRevision(); - bool NoteOldRevision() CM_OVERRIDE; - bool NoteNewRevision() CM_OVERRIDE; - bool UpdateImpl() CM_OVERRIDE; + bool NoteOldRevision() override; + bool NoteNewRevision() override; + bool UpdateImpl() override; bool UpdateCustom(const std::string& custom); - bool LoadRevisions() CM_OVERRIDE; - bool LoadModifications() CM_OVERRIDE; + bool LoadRevisions() override; + bool LoadModifications() override; class ChangesParser; class DescribeParser; diff --git a/Source/CTest/cmCTestReadCustomFilesCommand.cxx b/Source/CTest/cmCTestReadCustomFilesCommand.cxx index b21be87..ed14d06 100644 --- a/Source/CTest/cmCTestReadCustomFilesCommand.cxx +++ b/Source/CTest/cmCTestReadCustomFilesCommand.cxx @@ -14,9 +14,8 @@ bool cmCTestReadCustomFilesCommand::InitialPass( return false; } - std::vector<std::string>::const_iterator dit; - for (dit = args.begin(); dit != args.end(); ++dit) { - this->CTest->ReadCustomConfigurationFileTree(dit->c_str(), this->Makefile); + for (std::string const& arg : args) { + this->CTest->ReadCustomConfigurationFileTree(arg.c_str(), this->Makefile); } return true; diff --git a/Source/CTest/cmCTestReadCustomFilesCommand.h b/Source/CTest/cmCTestReadCustomFilesCommand.h index 157710a..ba25c51 100644 --- a/Source/CTest/cmCTestReadCustomFilesCommand.h +++ b/Source/CTest/cmCTestReadCustomFilesCommand.h @@ -27,7 +27,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmCTestReadCustomFilesCommand* ni = new cmCTestReadCustomFilesCommand; ni->CTest = this->CTest; @@ -39,7 +39,7 @@ public: * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/CTest/cmCTestRunScriptCommand.h b/Source/CTest/cmCTestRunScriptCommand.h index 9821c2e..9d8b4b5 100644 --- a/Source/CTest/cmCTestRunScriptCommand.h +++ b/Source/CTest/cmCTestRunScriptCommand.h @@ -27,7 +27,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmCTestRunScriptCommand* ni = new cmCTestRunScriptCommand; ni->CTest = this->CTest; @@ -40,7 +40,7 @@ public: * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/CTest/cmCTestRunTest.cxx b/Source/CTest/cmCTestRunTest.cxx index 1a339b7..abdb643 100644 --- a/Source/CTest/cmCTestRunTest.cxx +++ b/Source/CTest/cmCTestRunTest.cxx @@ -30,8 +30,8 @@ cmCTestRunTest::cmCTestRunTest(cmCTestTestHandler* handler) this->TestResult.Status = cmCTestTestHandler::NOT_RUN; this->TestResult.TestCount = 0; this->TestResult.Properties = nullptr; - this->ProcessOutput = ""; - this->CompressedOutput = ""; + this->ProcessOutput.clear(); + this->CompressedOutput.clear(); this->CompressionRatio = 2; this->StopTimePassed = false; this->NumberOfRunsLeft = 1; // default to 1 run of the test @@ -64,12 +64,8 @@ bool cmCTestRunTest::CheckOutput() // Check for TIMEOUT_AFTER_MATCH property. if (!this->TestProperties->TimeoutRegularExpressions.empty()) { - std::vector< - std::pair<cmsys::RegularExpression, std::string> >::iterator regIt; - for (regIt = this->TestProperties->TimeoutRegularExpressions.begin(); - regIt != this->TestProperties->TimeoutRegularExpressions.end(); - ++regIt) { - if (regIt->first.find(this->ProcessOutput.c_str())) { + for (auto& reg : this->TestProperties->TimeoutRegularExpressions) { + if (reg.first.find(this->ProcessOutput.c_str())) { cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, this->GetIndex() << ": " << "Test timeout changed to " @@ -163,18 +159,14 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started) int res = started ? this->TestProcess->GetProcessStatus() : cmsysProcess_State_Error; int retVal = this->TestProcess->GetExitValue(); - std::vector<std::pair<cmsys::RegularExpression, std::string> >::iterator - passIt; bool forceFail = false; bool skipped = false; bool outputTestErrorsToConsole = false; if (!this->TestProperties->RequiredRegularExpressions.empty() && this->FailedDependencies.empty()) { bool found = false; - for (passIt = this->TestProperties->RequiredRegularExpressions.begin(); - passIt != this->TestProperties->RequiredRegularExpressions.end(); - ++passIt) { - if (passIt->first.find(this->ProcessOutput.c_str())) { + for (auto& pass : this->TestProperties->RequiredRegularExpressions) { + if (pass.first.find(this->ProcessOutput.c_str())) { found = true; reason = "Required regular expression found."; break; @@ -185,23 +177,19 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started) forceFail = true; } reason += "Regex=["; - for (passIt = this->TestProperties->RequiredRegularExpressions.begin(); - passIt != this->TestProperties->RequiredRegularExpressions.end(); - ++passIt) { - reason += passIt->second; + for (auto& pass : this->TestProperties->RequiredRegularExpressions) { + reason += pass.second; reason += "\n"; } reason += "]"; } if (!this->TestProperties->ErrorRegularExpressions.empty() && this->FailedDependencies.empty()) { - for (passIt = this->TestProperties->ErrorRegularExpressions.begin(); - passIt != this->TestProperties->ErrorRegularExpressions.end(); - ++passIt) { - if (passIt->first.find(this->ProcessOutput.c_str())) { + for (auto& pass : this->TestProperties->ErrorRegularExpressions) { + if (pass.first.find(this->ProcessOutput.c_str())) { reason = "Error regular expression found in output."; reason += " Regex=["; - reason += passIt->second; + reason += pass.second; reason += "]"; forceFail = true; break; @@ -438,7 +426,7 @@ bool cmCTestRunTest::StartTest(size_t total) this->TestResult.Path = this->TestProperties->Directory; this->TestProcess = new cmProcess; this->TestResult.Output = "Disabled"; - this->TestResult.FullCommandLine = ""; + this->TestResult.FullCommandLine.clear(); return false; } @@ -457,15 +445,13 @@ bool cmCTestRunTest::StartTest(size_t total) if (!this->FailedDependencies.empty()) { this->TestProcess = new cmProcess; std::string msg = "Failed test dependencies:"; - for (std::set<std::string>::const_iterator it = - this->FailedDependencies.begin(); - it != this->FailedDependencies.end(); ++it) { - msg += " " + *it; + for (std::string const& failedDep : this->FailedDependencies) { + msg += " " + failedDep; } *this->TestHandler->LogFile << msg << std::endl; cmCTestLog(this->CTest, HANDLER_OUTPUT, msg << std::endl); this->TestResult.Output = msg; - this->TestResult.FullCommandLine = ""; + this->TestResult.FullCommandLine.clear(); this->TestResult.CompletionStatus = "Fixture dependency failed"; this->TestResult.Status = cmCTestTestHandler::NOT_RUN; return false; @@ -485,18 +471,14 @@ bool cmCTestRunTest::StartTest(size_t total) *this->TestHandler->LogFile << msg << std::endl; cmCTestLog(this->CTest, ERROR_MESSAGE, msg << std::endl); this->TestResult.Output = msg; - this->TestResult.FullCommandLine = ""; + this->TestResult.FullCommandLine.clear(); this->TestResult.CompletionStatus = "Missing Configuration"; this->TestResult.Status = cmCTestTestHandler::NOT_RUN; return false; } // Check if all required files exist - for (std::vector<std::string>::iterator i = - this->TestProperties->RequiredFiles.begin(); - i != this->TestProperties->RequiredFiles.end(); ++i) { - std::string file = *i; - + for (std::string const& file : this->TestProperties->RequiredFiles) { if (!cmSystemTools::FileExists(file.c_str())) { // Required file was not found this->TestProcess = new cmProcess; @@ -505,14 +487,14 @@ bool cmCTestRunTest::StartTest(size_t total) cmCTestLog(this->CTest, ERROR_MESSAGE, "Unable to find required file: " << file << std::endl); this->TestResult.Output = "Unable to find required file: " + file; - this->TestResult.FullCommandLine = ""; + this->TestResult.FullCommandLine.clear(); this->TestResult.CompletionStatus = "Required Files Missing"; this->TestResult.Status = cmCTestTestHandler::NOT_RUN; return false; } } // log and return if we did not find the executable - if (this->ActualCommand == "") { + if (this->ActualCommand.empty()) { // if the command was not found create a TestResult object // that has that information this->TestProcess = new cmProcess; @@ -521,7 +503,7 @@ bool cmCTestRunTest::StartTest(size_t total) cmCTestLog(this->CTest, ERROR_MESSAGE, "Unable to find executable: " << args[1] << std::endl); this->TestResult.Output = "Unable to find executable: " + args[1]; - this->TestResult.FullCommandLine = ""; + this->TestResult.FullCommandLine.clear(); this->TestResult.CompletionStatus = "Unable to find executable"; this->TestResult.Status = cmCTestTestHandler::NOT_RUN; return false; @@ -560,10 +542,9 @@ void cmCTestRunTest::ComputeArguments() // Prepends memcheck args to our command string this->TestHandler->GenerateTestCommand(this->Arguments, this->Index); - for (std::vector<std::string>::iterator i = this->Arguments.begin(); - i != this->Arguments.end(); ++i) { + for (std::string const& arg : this->Arguments) { testCommand += " \""; - testCommand += *i; + testCommand += arg; testCommand += "\""; } @@ -587,10 +568,8 @@ void cmCTestRunTest::ComputeArguments() << ": " << "Environment variables: " << std::endl); } - for (std::vector<std::string>::const_iterator e = - this->TestProperties->Environment.begin(); - e != this->TestProperties->Environment.end(); ++e) { - cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, this->Index << ": " << *e + for (std::string const& env : this->TestProperties->Environment) { + cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, this->Index << ": " << env << std::endl); } } @@ -616,7 +595,7 @@ double cmCTestRunTest::ResolveTimeout() { double timeout = this->TestProperties->Timeout; - if (this->CTest->GetStopTime() == "") { + if (this->CTest->GetStopTime().empty()) { return timeout; } struct tm* lctime; @@ -764,9 +743,8 @@ void cmCTestRunTest::WriteLogOutputTop(size_t completed, size_t total) << std::endl; *this->TestHandler->LogFile << "Command: \"" << this->ActualCommand << "\""; - for (std::vector<std::string>::iterator i = this->Arguments.begin(); - i != this->Arguments.end(); ++i) { - *this->TestHandler->LogFile << " \"" << *i << "\""; + for (std::string const& arg : this->Arguments) { + *this->TestHandler->LogFile << " \"" << arg << "\""; } *this->TestHandler->LogFile << std::endl diff --git a/Source/CTest/cmCTestSVN.cxx b/Source/CTest/cmCTestSVN.cxx index 36582a2..ce96224 100644 --- a/Source/CTest/cmCTestSVN.cxx +++ b/Source/CTest/cmCTestSVN.cxx @@ -59,7 +59,7 @@ private: cmsys::RegularExpression RegexRev; cmsys::RegularExpression RegexURL; cmsys::RegularExpression RegexRoot; - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (this->RegexRev.find(this->Line)) { this->Rev = this->RegexRev.match(1); @@ -103,10 +103,7 @@ bool cmCTestSVN::NoteOldRevision() return false; } - std::vector<SVNInfo>::iterator itbeg = this->Repositories.begin(); - std::vector<SVNInfo>::iterator itend = this->Repositories.end(); - for (; itbeg != itend; itbeg++) { - SVNInfo& svninfo = *itbeg; + for (SVNInfo& svninfo : this->Repositories) { svninfo.OldRevision = this->LoadInfo(svninfo); this->Log << "Revision for repository '" << svninfo.LocalPath << "' before update: " << svninfo.OldRevision << "\n"; @@ -127,10 +124,7 @@ bool cmCTestSVN::NoteNewRevision() return false; } - std::vector<SVNInfo>::iterator itbeg = this->Repositories.begin(); - std::vector<SVNInfo>::iterator itend = this->Repositories.end(); - for (; itbeg != itend; itbeg++) { - SVNInfo& svninfo = *itbeg; + for (SVNInfo& svninfo : this->Repositories) { svninfo.NewRevision = this->LoadInfo(svninfo); this->Log << "Revision for repository '" << svninfo.LocalPath << "' after update: " << svninfo.NewRevision << "\n"; @@ -205,7 +199,7 @@ private: cmCTestSVN* SVN; cmsys::RegularExpression RegexUpdate; - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (this->RegexUpdate.find(this->Line)) { this->DoPath(this->RegexUpdate.match(1)[0], @@ -257,9 +251,8 @@ bool cmCTestSVN::UpdateImpl() std::vector<char const*> svn_update; svn_update.push_back("update"); - for (std::vector<std::string>::const_iterator ai = args.begin(); - ai != args.end(); ++ai) { - svn_update.push_back(ai->c_str()); + for (std::string const& arg : args) { + svn_update.push_back(arg.c_str()); } UpdateParser out(this, "up-out> "); @@ -285,9 +278,8 @@ bool cmCTestSVN::RunSVNCommand(std::vector<char const*> const& parameters, std::vector<std::string> parsedUserOptions = cmSystemTools::ParseArguments(userOptions.c_str()); - for (std::vector<std::string>::iterator i = parsedUserOptions.begin(); - i != parsedUserOptions.end(); ++i) { - args.push_back(i->c_str()); + for (std::string const& opt : parsedUserOptions) { + args.push_back(opt.c_str()); } args.push_back(nullptr); @@ -309,7 +301,7 @@ public: { this->InitializeParser(); } - ~LogParser() CM_OVERRIDE { this->CleanupParser(); } + ~LogParser() override { this->CleanupParser(); } private: cmCTestSVN* SVN; cmCTestSVN::SVNInfo& SVNRepo; @@ -321,14 +313,14 @@ private: Change CurChange; std::vector<char> CData; - bool ProcessChunk(const char* data, int length) CM_OVERRIDE + bool ProcessChunk(const char* data, int length) override { this->OutputLogger::ProcessChunk(data, length); this->ParseChunk(data, length); return true; } - void StartElement(const std::string& name, const char** atts) CM_OVERRIDE + void StartElement(const std::string& name, const char** atts) override { this->CData.clear(); if (name == "logentry") { @@ -346,12 +338,12 @@ private: } } - void CharacterDataHandler(const char* data, int length) CM_OVERRIDE + void CharacterDataHandler(const char* data, int length) override { this->CData.insert(this->CData.end(), data, data + length); } - void EndElement(const std::string& name) CM_OVERRIDE + void EndElement(const std::string& name) override { if (name == "logentry") { this->SVN->DoRevisionSVN(this->Rev, this->Changes); @@ -370,7 +362,7 @@ private: this->CData.clear(); } - void ReportError(int /*line*/, int /*column*/, const char* msg) CM_OVERRIDE + void ReportError(int /*line*/, int /*column*/, const char* msg) override { this->SVN->Log << "Error parsing svn log xml: " << msg << "\n"; } @@ -380,10 +372,7 @@ bool cmCTestSVN::LoadRevisions() { bool result = true; // Get revisions for all the external repositories - std::vector<SVNInfo>::iterator itbeg = this->Repositories.begin(); - std::vector<SVNInfo>::iterator itend = this->Repositories.end(); - for (; itbeg != itend; itbeg++) { - SVNInfo& svninfo = *itbeg; + for (SVNInfo& svninfo : this->Repositories) { result = this->LoadRevisions(svninfo) && result; } return result; @@ -421,7 +410,7 @@ void cmCTestSVN::DoRevisionSVN(Revision const& revision, // Ignore changes in the old revision for external repositories if (revision.Rev == revision.SVNInfo->OldRevision && - revision.SVNInfo->LocalPath != "") { + !revision.SVNInfo->LocalPath.empty()) { return; } @@ -441,7 +430,7 @@ public: private: cmCTestSVN* SVN; cmsys::RegularExpression RegexStatus; - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (this->RegexStatus.find(this->Line)) { this->DoPath(this->RegexStatus.match(1)[0], @@ -507,7 +496,7 @@ public: private: cmCTestSVN* SVN; cmsys::RegularExpression RegexExternal; - bool ProcessLine() CM_OVERRIDE + bool ProcessLine() override { if (this->RegexExternal.find(this->Line)) { this->DoPath(this->RegexExternal.match(1)); diff --git a/Source/CTest/cmCTestSVN.h b/Source/CTest/cmCTestSVN.h index 94af837..dbc7fde 100644 --- a/Source/CTest/cmCTestSVN.h +++ b/Source/CTest/cmCTestSVN.h @@ -24,14 +24,14 @@ public: /** Construct with a CTest instance and update log stream. */ cmCTestSVN(cmCTest* ctest, std::ostream& log); - ~cmCTestSVN() CM_OVERRIDE; + ~cmCTestSVN() override; private: // Implement cmCTestVC internal API. - void CleanupImpl() CM_OVERRIDE; - bool NoteOldRevision() CM_OVERRIDE; - bool NoteNewRevision() CM_OVERRIDE; - bool UpdateImpl() CM_OVERRIDE; + void CleanupImpl() override; + bool NoteOldRevision() override; + bool NoteNewRevision() override; + bool UpdateImpl() override; bool RunSVNCommand(std::vector<char const*> const& parameters, OutputParser* out, OutputParser* err); @@ -77,8 +77,8 @@ private: std::string LoadInfo(SVNInfo& svninfo); bool LoadRepositories(); - bool LoadModifications() CM_OVERRIDE; - bool LoadRevisions() CM_OVERRIDE; + bool LoadModifications() override; + bool LoadRevisions() override; bool LoadRevisions(SVNInfo& svninfo); void GuessBase(SVNInfo& svninfo, std::vector<Change> const& changes); @@ -86,7 +86,7 @@ private: void DoRevisionSVN(Revision const& revision, std::vector<Change> const& changes); - void WriteXMLGlobal(cmXMLWriter& xml) CM_OVERRIDE; + void WriteXMLGlobal(cmXMLWriter& xml) override; class ExternalParser; // Parsing helper classes. diff --git a/Source/CTest/cmCTestScriptHandler.cxx b/Source/CTest/cmCTestScriptHandler.cxx index 6fd24a5..fdd9622 100644 --- a/Source/CTest/cmCTestScriptHandler.cxx +++ b/Source/CTest/cmCTestScriptHandler.cxx @@ -52,9 +52,9 @@ class cmCTestScriptFunctionBlocker : public cmFunctionBlocker { public: cmCTestScriptFunctionBlocker() {} - ~cmCTestScriptFunctionBlocker() CM_OVERRIDE {} + ~cmCTestScriptFunctionBlocker() override {} bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf, - cmExecutionStatus& /*status*/) CM_OVERRIDE; + cmExecutionStatus& /*status*/) override; // virtual bool ShouldRemove(const cmListFileFunction& lff, cmMakefile &mf); // virtual void ScopeEnded(cmMakefile &mf); @@ -93,18 +93,18 @@ void cmCTestScriptHandler::Initialize() this->EmptyBinDir = false; this->EmptyBinDirOnce = false; - this->SourceDir = ""; - this->BinaryDir = ""; - this->BackupSourceDir = ""; - this->BackupBinaryDir = ""; - this->CTestRoot = ""; - this->CVSCheckOut = ""; - this->CTestCmd = ""; - this->UpdateCmd = ""; - this->CTestEnv = ""; - this->InitialCache = ""; - this->CMakeCmd = ""; - this->CMOutFile = ""; + this->SourceDir.clear(); + this->BinaryDir.clear(); + this->BackupSourceDir.clear(); + this->BackupBinaryDir.clear(); + this->CTestRoot.clear(); + this->CVSCheckOut.clear(); + this->CTestCmd.clear(); + this->UpdateCmd.clear(); + this->CTestEnv.clear(); + this->InitialCache.clear(); + this->CMakeCmd.clear(); + this->CMOutFile.clear(); this->ExtraUpdates.clear(); this->MinimumInterval = 20 * 60; @@ -245,10 +245,9 @@ int cmCTestScriptHandler::ExecuteScript(const std::string& total_script_arg) std::ostringstream message; message << "Error running command: ["; message << result << "] "; - for (std::vector<const char*>::iterator i = argv.begin(); i != argv.end(); - ++i) { - if (*i) { - message << *i << " "; + for (const char* arg : argv) { + if (arg) { + message << arg << " "; } } cmCTestLog(this->CTest, ERROR_MESSAGE, message.str() << argv[0] @@ -377,9 +376,8 @@ int cmCTestScriptHandler::ReadInScript(const std::string& total_script_arg) // Add definitions of variables passed in on the command line: const std::map<std::string, std::string>& defs = this->CTest->GetDefinitions(); - for (std::map<std::string, std::string>::const_iterator it = defs.begin(); - it != defs.end(); ++it) { - this->Makefile->AddDefinition(it->first, it->second.c_str()); + for (auto const& d : defs) { + this->Makefile->AddDefinition(d.first, d.second.c_str()); } // finally read in the script @@ -595,7 +593,7 @@ int cmCTestScriptHandler::CheckOutSourceDir() if (!cmSystemTools::FileExists(this->SourceDir.c_str()) && !this->CVSCheckOut.empty()) { // we must now checkout the src dir - output = ""; + output.clear(); cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Run cvs: " << this->CVSCheckOut << std::endl); res = cmSystemTools::RunSingleCommand( @@ -654,15 +652,14 @@ int cmCTestScriptHandler::PerformExtraUpdates() // do an initial cvs update as required command = this->UpdateCmd; - std::vector<std::string>::iterator it; - for (it = this->ExtraUpdates.begin(); it != this->ExtraUpdates.end(); ++it) { + for (std::string const& eu : this->ExtraUpdates) { std::vector<std::string> cvsArgs; - cmSystemTools::ExpandListArgument(*it, cvsArgs); + cmSystemTools::ExpandListArgument(eu, cvsArgs); if (cvsArgs.size() == 2) { std::string fullCommand = command; fullCommand += " update "; fullCommand += cvsArgs[1]; - output = ""; + output.clear(); retVal = 0; cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Run Update: " << fullCommand << std::endl); @@ -670,7 +667,7 @@ int cmCTestScriptHandler::PerformExtraUpdates() fullCommand.c_str(), &output, &output, &retVal, cvsArgs[0].c_str(), this->HandlerVerbose, 0 /*this->TimeOut*/); if (!res || retVal != 0) { - cmSystemTools::Error("Unable to perform extra updates:\n", it->c_str(), + cmSystemTools::Error("Unable to perform extra updates:\n", eu.c_str(), "\nWith output:\n", output.c_str()); return 0; } @@ -765,7 +762,7 @@ int cmCTestScriptHandler::RunConfigurationDashboard() command = this->CMakeCmd; command += " \""; command += this->SourceDir; - output = ""; + output.clear(); command += "\""; retVal = 0; cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, @@ -803,9 +800,9 @@ int cmCTestScriptHandler::RunConfigurationDashboard() std::vector<std::string> ctestCommands; cmSystemTools::ExpandListArgument(this->CTestCmd, ctestCommands); // for each variable/argument do a putenv - for (unsigned i = 0; i < ctestCommands.size(); ++i) { - command = ctestCommands[i]; - output = ""; + for (std::string const& ctestCommand : ctestCommands) { + command = ctestCommand; + output.clear(); retVal = 0; cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Run ctest command: " << command << std::endl); diff --git a/Source/CTest/cmCTestScriptHandler.h b/Source/CTest/cmCTestScriptHandler.h index c2631ce..b6cd97b 100644 --- a/Source/CTest/cmCTestScriptHandler.h +++ b/Source/CTest/cmCTestScriptHandler.h @@ -65,7 +65,7 @@ public: /** * Run a dashboard using a specified confiuration script */ - int ProcessHandler() CM_OVERRIDE; + int ProcessHandler() override; /* * Run a script @@ -98,9 +98,9 @@ public: double GetRemainingTimeAllowed(); cmCTestScriptHandler(); - ~cmCTestScriptHandler() CM_OVERRIDE; + ~cmCTestScriptHandler() override; - void Initialize() CM_OVERRIDE; + void Initialize() override; void CreateCMake(); cmake* GetCMake() { return this->CMake; } diff --git a/Source/CTest/cmCTestSleepCommand.h b/Source/CTest/cmCTestSleepCommand.h index ade9c96..5cd185a 100644 --- a/Source/CTest/cmCTestSleepCommand.h +++ b/Source/CTest/cmCTestSleepCommand.h @@ -27,7 +27,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmCTestSleepCommand* ni = new cmCTestSleepCommand; ni->CTest = this->CTest; @@ -40,7 +40,7 @@ public: * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/CTest/cmCTestStartCommand.h b/Source/CTest/cmCTestStartCommand.h index 2e02838..542f27c 100644 --- a/Source/CTest/cmCTestStartCommand.h +++ b/Source/CTest/cmCTestStartCommand.h @@ -27,7 +27,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmCTestStartCommand* ni = new cmCTestStartCommand; ni->CTest = this->CTest; @@ -42,7 +42,7 @@ public: * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; /** * Will this invocation of ctest_start create a new TAG file? diff --git a/Source/CTest/cmCTestSubmitCommand.h b/Source/CTest/cmCTestSubmitCommand.h index 44f0d68..c4b84ce 100644 --- a/Source/CTest/cmCTestSubmitCommand.h +++ b/Source/CTest/cmCTestSubmitCommand.h @@ -38,7 +38,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmCTestSubmitCommand* ni = new cmCTestSubmitCommand; ni->CTest = this->CTest; @@ -47,20 +47,20 @@ public: } bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; /** * The name of the command as specified in CMakeList.txt. */ - std::string GetName() const CM_OVERRIDE { return "ctest_submit"; } + std::string GetName() const override { return "ctest_submit"; } typedef cmCTestHandlerCommand Superclass; protected: - cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE; + cmCTestGenericHandler* InitializeHandler() override; - bool CheckArgumentKeyword(std::string const& arg) CM_OVERRIDE; - bool CheckArgumentValue(std::string const& arg) CM_OVERRIDE; + bool CheckArgumentKeyword(std::string const& arg) override; + bool CheckArgumentValue(std::string const& arg) override; enum { diff --git a/Source/CTest/cmCTestSubmitHandler.cxx b/Source/CTest/cmCTestSubmitHandler.cxx index b7d0d1f..e51e168 100644 --- a/Source/CTest/cmCTestSubmitHandler.cxx +++ b/Source/CTest/cmCTestSubmitHandler.cxx @@ -38,7 +38,7 @@ class cmCTestSubmitHandler::ResponseParser : public cmXMLParser { public: ResponseParser() { this->Status = STATUS_OK; } - ~ResponseParser() CM_OVERRIDE {} + ~ResponseParser() override {} public: enum StatusType @@ -66,17 +66,17 @@ private: } void StartElement(const std::string& /*name*/, - const char** /*atts*/) CM_OVERRIDE + const char** /*atts*/) override { this->CurrentValue.clear(); } - void CharacterDataHandler(const char* data, int length) CM_OVERRIDE + void CharacterDataHandler(const char* data, int length) override { this->CurrentValue.insert(this->CurrentValue.end(), data, data + length); } - void EndElement(const std::string& name) CM_OVERRIDE + void EndElement(const std::string& name) override { if (name == "status") { std::string status = cmSystemTools::UpperCase(this->GetCurrentValue()); @@ -140,10 +140,10 @@ void cmCTestSubmitHandler::Initialize() this->HasWarnings = false; this->HasErrors = false; this->Superclass::Initialize(); - this->HTTPProxy = ""; + this->HTTPProxy.clear(); this->HTTPProxyType = 0; - this->HTTPProxyAuth = ""; - this->FTPProxy = ""; + this->HTTPProxyAuth.clear(); + this->FTPProxy.clear(); this->FTPProxyType = 0; this->LogFile = nullptr; this->Files.clear(); @@ -162,8 +162,7 @@ bool cmCTestSubmitHandler::SubmitUsingFTP(const std::string& localprefix, /* In windows, this will init the winsock stuff */ ::curl_global_init(CURL_GLOBAL_ALL); - cmCTest::SetOfStrings::const_iterator file; - for (file = files.begin(); file != files.end(); ++file) { + for (std::string const& file : files) { /* get a curl handle */ curl = curl_easy_init(); if (curl) { @@ -192,12 +191,12 @@ bool cmCTestSubmitHandler::SubmitUsingFTP(const std::string& localprefix, ::curl_easy_setopt(curl, CURLOPT_UPLOAD, 1); - std::string local_file = *file; + std::string local_file = file; if (!cmSystemTools::FileExists(local_file.c_str())) { - local_file = localprefix + "/" + *file; + local_file = localprefix + "/" + file; } std::string upload_as = - url + "/" + remoteprefix + cmSystemTools::GetFilenameName(*file); + url + "/" + remoteprefix + cmSystemTools::GetFilenameName(file); if (!cmSystemTools::FileExists(local_file.c_str())) { cmCTestLog(this->CTest, ERROR_MESSAGE, @@ -307,12 +306,11 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const std::string& localprefix, ::curl_slist_append(nullptr, "Content-Type: text/xml"); // Add any additional headers that the user specified. - for (std::vector<std::string>::const_iterator h = this->HttpHeaders.begin(); - h != this->HttpHeaders.end(); ++h) { + for (std::string const& h : this->HttpHeaders) { cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, - " Add HTTP Header: \"" << *h << "\"" << std::endl, + " Add HTTP Header: \"" << h << "\"" << std::endl, this->Quiet); - headers = ::curl_slist_append(headers, h->c_str()); + headers = ::curl_slist_append(headers, h.c_str()); } /* In windows, this will init the winsock stuff */ @@ -323,18 +321,15 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const std::string& localprefix, cmSystemTools::ExpandListArgument(curlopt, args); bool verifyPeerOff = false; bool verifyHostOff = false; - for (std::vector<std::string>::iterator i = args.begin(); i != args.end(); - ++i) { - if (*i == "CURLOPT_SSL_VERIFYPEER_OFF") { + for (std::string const& arg : args) { + if (arg == "CURLOPT_SSL_VERIFYPEER_OFF") { verifyPeerOff = true; } - if (*i == "CURLOPT_SSL_VERIFYHOST_OFF") { + if (arg == "CURLOPT_SSL_VERIFYHOST_OFF") { verifyHostOff = true; } } - std::string::size_type kk; - cmCTest::SetOfStrings::const_iterator file; - for (file = files.begin(); file != files.end(); ++file) { + for (std::string const& file : files) { /* get a curl handle */ curl = curl_easy_init(); if (curl) { @@ -389,19 +384,18 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const std::string& localprefix, ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); - std::string local_file = *file; + std::string local_file = file; if (!cmSystemTools::FileExists(local_file.c_str())) { - local_file = localprefix + "/" + *file; + local_file = localprefix + "/" + file; } std::string remote_file = - remoteprefix + cmSystemTools::GetFilenameName(*file); + remoteprefix + cmSystemTools::GetFilenameName(file); *this->LogFile << "\tUpload file: " << local_file << " to " << remote_file << std::endl; std::string ofile; - for (kk = 0; kk < remote_file.size(); kk++) { - char c = remote_file[kk]; + for (char c : remote_file) { char hexCh[4] = { 0, 0, 0, 0 }; hexCh[0] = c; switch (c) { @@ -502,11 +496,11 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const std::string& localprefix, ? "" : this->GetOption("RetryCount"); - int delay = retryDelay == "" + int delay = retryDelay.empty() ? atoi(this->CTest->GetCTestConfiguration("CTestSubmitRetryDelay") .c_str()) : atoi(retryDelay.c_str()); - int count = retryCount == "" + int count = retryCount.empty() ? atoi(this->CTest->GetCTestConfiguration("CTestSubmitRetryCount") .c_str()) : atoi(retryCount.c_str()); @@ -629,8 +623,7 @@ bool cmCTestSubmitHandler::TriggerUsingHTTP(const std::set<std::string>& files, /* In windows, this will init the winsock stuff */ ::curl_global_init(CURL_GLOBAL_ALL); - cmCTest::SetOfStrings::const_iterator file; - for (file = files.begin(); file != files.end(); ++file) { + for (std::string const& file : files) { /* get a curl handle */ curl = curl_easy_init(); if (curl) { @@ -670,11 +663,9 @@ bool cmCTestSubmitHandler::TriggerUsingHTTP(const std::set<std::string>& files, ::curl_easy_setopt(curl, CURLOPT_FILE, &chunk); ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug); - std::string rfile = remoteprefix + cmSystemTools::GetFilenameName(*file); + std::string rfile = remoteprefix + cmSystemTools::GetFilenameName(file); std::string ofile; - std::string::iterator kk; - for (kk = rfile.begin(); kk < rfile.end(); ++kk) { - char c = *kk; + for (char c : rfile) { char hexCh[4] = { 0, 0, 0, 0 }; hexCh[0] = c; switch (c) { @@ -772,16 +763,15 @@ bool cmCTestSubmitHandler::SubmitUsingSCP(const std::string& scp_command, int problems = 0; - cmCTest::SetOfStrings::const_iterator file; - for (file = files.begin(); file != files.end(); ++file) { + for (std::string const& file : files) { int retVal; std::string lfname = localprefix; cmSystemTools::ConvertToUnixSlashes(lfname); - lfname += "/" + *file; + lfname += "/" + file; lfname = cmSystemTools::ConvertToOutputPath(lfname.c_str()); argv[1] = lfname.c_str(); - std::string rfname = url + "/" + remoteprefix + *file; + std::string rfname = url + "/" + remoteprefix + file; argv[2] = rfname.c_str(); cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Execute \"" << argv[0] << "\" \"" << argv[1] << "\" \"" << argv[2] @@ -864,12 +854,11 @@ bool cmCTestSubmitHandler::SubmitUsingCP(const std::string& localprefix, return false; } - cmCTest::SetOfStrings::const_iterator file; - for (file = files.begin(); file != files.end(); ++file) { + for (std::string const& file : files) { std::string lfname = localprefix; cmSystemTools::ConvertToUnixSlashes(lfname); - lfname += "/" + *file; - std::string rfname = destination + "/" + remoteprefix + *file; + lfname += "/" + file; + std::string rfname = destination + "/" + remoteprefix + file; cmSystemTools::CopyFileAlways(lfname, rfname); cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " Copy file: " << lfname << " to " << rfname << std::endl, @@ -902,13 +891,12 @@ bool cmCTestSubmitHandler::SubmitUsingXMLRPC( cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " Submitting to: " << realURL << " (" << remoteprefix << ")" << std::endl, this->Quiet); - cmCTest::SetOfStrings::const_iterator file; - for (file = files.begin(); file != files.end(); ++file) { + for (std::string const& file : files) { xmlrpc_value* result; - std::string local_file = *file; + std::string local_file = file; if (!cmSystemTools::FileExists(local_file.c_str())) { - local_file = localprefix + "/" + *file; + local_file = localprefix + "/" + file; } cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " Submit file: " << local_file << std::endl, @@ -1044,14 +1032,14 @@ int cmCTestSubmitHandler::HandleCDashUploadFile(std::string const& file, ? "" : this->GetOption("RetryCount"); unsigned long retryDelay = 0; - if (retryDelayString != "") { + if (!retryDelayString.empty()) { if (!cmSystemTools::StringToULong(retryDelayString.c_str(), &retryDelay)) { cmCTestLog(this->CTest, WARNING, "Invalid value for 'RETRY_DELAY' : " << retryDelayString << std::endl); } } unsigned long retryCount = 0; - if (retryCountString != "") { + if (!retryCountString.empty()) { if (!cmSystemTools::StringToULong(retryCountString.c_str(), &retryCount)) { cmCTestLog(this->CTest, WARNING, "Invalid value for 'RETRY_DELAY' : " << retryCountString << std::endl); @@ -1323,13 +1311,11 @@ int cmCTestSubmitHandler::ProcessHandler() cmCTestOptionalLog(this->CTest, DEBUG, "Globbing for: " << gpath << std::endl, this->Quiet); if (cmSystemTools::SimpleGlob(gpath, gfiles, 1)) { - size_t cc; - for (cc = 0; cc < gfiles.size(); cc++) { - gfiles[cc] = gfiles[cc].substr(glen); + for (std::string& gfile : gfiles) { + gfile = gfile.substr(glen); cmCTestOptionalLog(this->CTest, DEBUG, - "Glob file: " << gfiles[cc] << std::endl, - this->Quiet); - this->CTest->AddSubmitFile(cmCTest::PartCoverage, gfiles[cc].c_str()); + "Glob file: " << gfile << std::endl, this->Quiet); + this->CTest->AddSubmitFile(cmCTest::PartCoverage, gfile.c_str()); } } else { cmCTestLog(this->CTest, ERROR_MESSAGE, "Problem globbing" << std::endl); @@ -1356,9 +1342,8 @@ int cmCTestSubmitHandler::ProcessHandler() if (ofs) { ofs << "Upload files:" << std::endl; int cnt = 0; - cmCTest::SetOfStrings::iterator it; - for (it = files.begin(); it != files.end(); ++it) { - ofs << cnt << "\t" << *it << std::endl; + for (std::string const& file : files) { + ofs << cnt << "\t" << file << std::endl; cnt++; } } @@ -1376,7 +1361,7 @@ int cmCTestSubmitHandler::ProcessHandler() std::string dropMethod(this->CTest->GetCTestConfiguration("DropMethod")); - if (dropMethod == "" || dropMethod == "ftp") { + if (dropMethod.empty() || dropMethod == "ftp") { ofs << "Using drop method: FTP" << std::endl; cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " Using FTP submit method" << std::endl diff --git a/Source/CTest/cmCTestSubmitHandler.h b/Source/CTest/cmCTestSubmitHandler.h index 7b409fb..b4d0e77 100644 --- a/Source/CTest/cmCTestSubmitHandler.h +++ b/Source/CTest/cmCTestSubmitHandler.h @@ -25,14 +25,14 @@ public: typedef cmCTestGenericHandler Superclass; cmCTestSubmitHandler(); - ~cmCTestSubmitHandler() CM_OVERRIDE { this->LogFile = nullptr; } + ~cmCTestSubmitHandler() override { this->LogFile = nullptr; } /* * The main entry point for this class */ - int ProcessHandler() CM_OVERRIDE; + int ProcessHandler() override; - void Initialize() CM_OVERRIDE; + void Initialize() override; /** Specify a set of parts (by name) to submit. */ void SelectParts(std::set<cmCTest::Part> const& parts); diff --git a/Source/CTest/cmCTestTestCommand.h b/Source/CTest/cmCTestTestCommand.h index e8c8c60..11c0db9 100644 --- a/Source/CTest/cmCTestTestCommand.h +++ b/Source/CTest/cmCTestTestCommand.h @@ -25,7 +25,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmCTestTestCommand* ni = new cmCTestTestCommand; ni->CTest = this->CTest; @@ -36,11 +36,11 @@ public: /** * The name of the command as specified in CMakeList.txt. */ - std::string GetName() const CM_OVERRIDE { return "ctest_test"; } + std::string GetName() const override { return "ctest_test"; } protected: virtual cmCTestGenericHandler* InitializeActualHandler(); - cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE; + cmCTestGenericHandler* InitializeHandler() override; enum { diff --git a/Source/CTest/cmCTestTestHandler.cxx b/Source/CTest/cmCTestTestHandler.cxx index 57075c7..c7ed927 100644 --- a/Source/CTest/cmCTestTestHandler.cxx +++ b/Source/CTest/cmCTestTestHandler.cxx @@ -8,6 +8,7 @@ #include <functional> #include <iomanip> #include <iterator> +#include <memory> // IWYU pragma: keep #include <set> #include <sstream> #include <stdio.h> @@ -28,7 +29,6 @@ #include "cmSystemTools.h" #include "cmWorkingDirectory.h" #include "cmXMLWriter.h" -#include "cm_auto_ptr.hxx" #include "cm_utf8.h" #include "cmake.h" #include "cmsys/FStream.hxx" @@ -41,7 +41,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmCTestSubdirCommand* c = new cmCTestSubdirCommand; c->TestHandler = this->TestHandler; @@ -53,7 +53,7 @@ public: * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& /*unused*/) CM_OVERRIDE; + cmExecutionStatus& /*unused*/) override; cmCTestTestHandler* TestHandler; }; @@ -65,17 +65,16 @@ bool cmCTestSubdirCommand::InitialPass(std::vector<std::string> const& args, this->SetError("called with incorrect number of arguments"); return false; } - std::vector<std::string>::const_iterator it; std::string cwd = cmSystemTools::GetCurrentWorkingDirectory(); - for (it = args.begin(); it != args.end(); ++it) { + for (std::string const& arg : args) { std::string fname; - if (cmSystemTools::FileIsFullPath(it->c_str())) { - fname = *it; + if (cmSystemTools::FileIsFullPath(arg.c_str())) { + fname = arg; } else { fname = cwd; fname += "/"; - fname += *it; + fname += arg; } if (!cmSystemTools::FileIsDirectory(fname)) { @@ -116,7 +115,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmCTestAddSubdirectoryCommand* c = new cmCTestAddSubdirectoryCommand; c->TestHandler = this->TestHandler; @@ -128,7 +127,7 @@ public: * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& /*unused*/) CM_OVERRIDE; + cmExecutionStatus& /*unused*/) override; cmCTestTestHandler* TestHandler; }; @@ -181,7 +180,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmCTestAddTestCommand* c = new cmCTestAddTestCommand; c->TestHandler = this->TestHandler; @@ -193,7 +192,7 @@ public: * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& /*args*/, - cmExecutionStatus& /*unused*/) CM_OVERRIDE; + cmExecutionStatus& /*unused*/) override; cmCTestTestHandler* TestHandler; }; @@ -214,7 +213,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmCTestSetTestsPropertiesCommand* c = new cmCTestSetTestsPropertiesCommand; c->TestHandler = this->TestHandler; @@ -226,7 +225,7 @@ public: * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& /*args*/, - cmExecutionStatus& /*unused*/) CM_OVERRIDE; + cmExecutionStatus& /*unused*/) override; cmCTestTestHandler* TestHandler; }; @@ -243,7 +242,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmCTestSetDirectoryPropertiesCommand* c = new cmCTestSetDirectoryPropertiesCommand; @@ -256,7 +255,7 @@ public: * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& /*unused*/, - cmExecutionStatus& /*unused*/) CM_OVERRIDE; + cmExecutionStatus& /*unused*/) override; cmCTestTestHandler* TestHandler; }; @@ -352,8 +351,8 @@ void cmCTestTestHandler::Initialize() this->TestResults.clear(); this->CustomTestsIgnore.clear(); - this->StartTest = ""; - this->EndTest = ""; + this->StartTest.clear(); + this->EndTest.clear(); this->CustomPreTest.clear(); this->CustomPostTest.clear(); @@ -369,13 +368,13 @@ void cmCTestTestHandler::Initialize() this->UseExcludeRegExpFirst = false; this->IncludeLabelRegularExpression = ""; this->ExcludeLabelRegularExpression = ""; - this->IncludeRegExp = ""; - this->ExcludeRegExp = ""; + this->IncludeRegExp.clear(); + this->ExcludeRegExp.clear(); this->ExcludeFixtureRegExp.clear(); this->ExcludeFixtureSetupRegExp.clear(); this->ExcludeFixtureCleanupRegExp.clear(); - TestsToRunString = ""; + TestsToRunString.clear(); this->UseUnion = false; this->TestList.clear(); } @@ -505,10 +504,9 @@ int cmCTestTestHandler::ProcessHandler() cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, std::endl << "The following tests passed:" << std::endl, this->Quiet); - for (std::vector<std::string>::iterator j = passed.begin(); - j != passed.end(); ++j) { + for (std::string const& j : passed) { cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, - "\t" << *j << std::endl, this->Quiet); + "\t" << j << std::endl, this->Quiet); } } @@ -518,11 +516,10 @@ int cmCTestTestHandler::ProcessHandler() SetOfTests resultsSet(this->TestResults.begin(), this->TestResults.end()); std::vector<cmCTestTestHandler::cmCTestTestResult> disabledTests; - for (SetOfTests::iterator ftit = resultsSet.begin(); - ftit != resultsSet.end(); ++ftit) { - if (cmHasLiteralPrefix(ftit->CompletionStatus, "SKIP_RETURN_CODE=") || - ftit->CompletionStatus == "Disabled") { - disabledTests.push_back(*ftit); + for (cmCTestTestResult const& ft : resultsSet) { + if (cmHasLiteralPrefix(ft.CompletionStatus, "SKIP_RETURN_CODE=") || + ft.CompletionStatus == "Disabled") { + disabledTests.push_back(ft); } } @@ -535,14 +532,13 @@ int cmCTestTestHandler::ProcessHandler() << static_cast<int>(percent + .5f) << "% tests passed, " << failed.size() << " tests failed out of " << total << std::endl); - - if (!this->CTest->GetLabelsForSubprojects().empty() && - this->CTest->GetSubprojectSummary()) { - this->PrintSubprojectSummary(); - } else if (this->CTest->GetLabelSummary()) { - this->PrintLabelSummary(); + if ((!this->CTest->GetLabelsForSubprojects().empty() && + this->CTest->GetSubprojectSummary())) { + this->PrintLabelOrSubprojectSummary(true); + } + if (this->CTest->GetLabelSummary()) { + this->PrintLabelOrSubprojectSummary(false); } - char realBuf[1024]; sprintf(realBuf, "%6.2f sec", clock_finish - clock_start); cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, @@ -556,17 +552,15 @@ int cmCTestTestHandler::ProcessHandler() this->StartLogFile("TestsDisabled", ofs); const char* disabled_reason; - for (std::vector<cmCTestTestHandler::cmCTestTestResult>::iterator dtit = - disabledTests.begin(); - dtit != disabledTests.end(); ++dtit) { - ofs << dtit->TestCount << ":" << dtit->Name << std::endl; - if (dtit->CompletionStatus == "Disabled") { + for (cmCTestTestResult const& dt : disabledTests) { + ofs << dt.TestCount << ":" << dt.Name << std::endl; + if (dt.CompletionStatus == "Disabled") { disabled_reason = "Disabled"; } else { disabled_reason = "Skipped"; } cmCTestLog(this->CTest, HANDLER_OUTPUT, "\t" - << std::setw(3) << dtit->TestCount << " - " << dtit->Name + << std::setw(3) << dt.TestCount << " - " << dt.Name << " (" << disabled_reason << ")" << std::endl); } } @@ -577,16 +571,14 @@ int cmCTestTestHandler::ProcessHandler() << "The following tests FAILED:" << std::endl); this->StartLogFile("TestsFailed", ofs); - for (SetOfTests::iterator ftit = resultsSet.begin(); - ftit != resultsSet.end(); ++ftit) { - if (ftit->Status != cmCTestTestHandler::COMPLETED && - !cmHasLiteralPrefix(ftit->CompletionStatus, "SKIP_RETURN_CODE=") && - ftit->CompletionStatus != "Disabled") { - ofs << ftit->TestCount << ":" << ftit->Name << std::endl; + for (cmCTestTestResult const& ft : resultsSet) { + if (ft.Status != cmCTestTestHandler::COMPLETED && + !cmHasLiteralPrefix(ft.CompletionStatus, "SKIP_RETURN_CODE=") && + ft.CompletionStatus != "Disabled") { + ofs << ft.TestCount << ":" << ft.Name << std::endl; cmCTestLog(this->CTest, HANDLER_OUTPUT, "\t" - << std::setw(3) << ftit->TestCount << " - " - << ftit->Name << " (" << this->GetTestStatus(&*ftit) - << ")" << std::endl); + << std::setw(3) << ft.TestCount << " - " << ft.Name + << " (" << this->GetTestStatus(ft) << ")" << std::endl); } } } @@ -620,156 +612,88 @@ int cmCTestTestHandler::ProcessHandler() return 0; } -void cmCTestTestHandler::PrintLabelSummary() -{ - cmCTestTestHandler::ListOfTests::iterator it = this->TestList.begin(); - std::map<std::string, double> labelTimes; - std::map<std::string, int> labelCounts; - std::set<std::string> labels; - // initialize maps - std::string::size_type maxlen = 0; - for (; it != this->TestList.end(); ++it) { - cmCTestTestProperties& p = *it; - if (!p.Labels.empty()) { - for (std::vector<std::string>::iterator l = p.Labels.begin(); - l != p.Labels.end(); ++l) { - if ((*l).size() > maxlen) { - maxlen = (*l).size(); - } - labels.insert(*l); - labelTimes[*l] = 0; - labelCounts[*l] = 0; - } - } - } - cmCTestTestHandler::TestResultsVector::iterator ri = - this->TestResults.begin(); - // fill maps - for (; ri != this->TestResults.end(); ++ri) { - cmCTestTestResult& result = *ri; - cmCTestTestProperties& p = *result.Properties; - if (!p.Labels.empty()) { - for (std::vector<std::string>::iterator l = p.Labels.begin(); - l != p.Labels.end(); ++l) { - labelTimes[*l] += result.ExecutionTime; - ++labelCounts[*l]; - } - } - } - // now print times - if (!labels.empty()) { - cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "\nLabel Time Summary:", - this->Quiet); - } - for (std::set<std::string>::const_iterator i = labels.begin(); - i != labels.end(); ++i) { - std::string label = *i; - label.resize(maxlen + 3, ' '); - - char buf[1024]; - sprintf(buf, "%6.2f sec", labelTimes[*i]); - - std::ostringstream labelCountStr; - labelCountStr << "(" << labelCounts[*i] << " test"; - if (labelCounts[*i] > 1) { - labelCountStr << "s"; - } - labelCountStr << ")"; - - cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "\n" - << label << " = " << buf << " " - << labelCountStr.str(), - this->Quiet); - if (this->LogFile) { - *this->LogFile << "\n" << *i << " = " << buf << "\n"; - } - } - if (!labels.empty()) { - if (this->LogFile) { - *this->LogFile << "\n"; - } - cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "\n", this->Quiet); - } -} - -void cmCTestTestHandler::PrintSubprojectSummary() +void cmCTestTestHandler::PrintLabelOrSubprojectSummary(bool doSubProject) { + // collect subproject labels std::vector<std::string> subprojects = this->CTest->GetLabelsForSubprojects(); - - cmCTestTestHandler::ListOfTests::iterator it = this->TestList.begin(); std::map<std::string, double> labelTimes; std::map<std::string, int> labelCounts; std::set<std::string> labels; - // initialize maps std::string::size_type maxlen = 0; - for (; it != this->TestList.end(); ++it) { - cmCTestTestProperties& p = *it; - for (std::vector<std::string>::iterator l = p.Labels.begin(); - l != p.Labels.end(); ++l) { + // initialize maps + for (cmCTestTestProperties& p : this->TestList) { + for (std::string const& l : p.Labels) { + // first check to see if the current label is a subproject label + bool isSubprojectLabel = false; std::vector<std::string>::iterator subproject = - std::find(subprojects.begin(), subprojects.end(), *l); + std::find(subprojects.begin(), subprojects.end(), l); if (subproject != subprojects.end()) { - if ((*l).size() > maxlen) { - maxlen = (*l).size(); + isSubprojectLabel = true; + } + // if we are doing sub projects and this label is one, then use it + // if we are not doing sub projects and the label is not one use it + if ((doSubProject && isSubprojectLabel) || + (!doSubProject && !isSubprojectLabel)) { + if (l.size() > maxlen) { + maxlen = l.size(); } - labels.insert(*l); - labelTimes[*l] = 0; - labelCounts[*l] = 0; + labels.insert(l); + labelTimes[l] = 0; + labelCounts[l] = 0; } } } - cmCTestTestHandler::TestResultsVector::iterator ri = - this->TestResults.begin(); // fill maps - for (; ri != this->TestResults.end(); ++ri) { - cmCTestTestResult& result = *ri; + for (cmCTestTestResult& result : this->TestResults) { cmCTestTestProperties& p = *result.Properties; - for (std::vector<std::string>::iterator l = p.Labels.begin(); - l != p.Labels.end(); ++l) { - std::vector<std::string>::iterator subproject = - std::find(subprojects.begin(), subprojects.end(), *l); - if (subproject != subprojects.end()) { - labelTimes[*l] += result.ExecutionTime; - ++labelCounts[*l]; + for (std::string const& l : p.Labels) { + // only use labels found in labels + if (labels.find(l) != labels.end()) { + labelTimes[l] += result.ExecutionTime * result.Properties->Processors; + ++labelCounts[l]; } } } + // if no labels are found return and print nothing + if (labels.empty()) { + return; + } // now print times - if (!labels.empty()) { + if (doSubProject) { cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "\nSubproject Time Summary:", this->Quiet); + } else { + cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "\nLabel Time Summary:", + this->Quiet); } - for (std::set<std::string>::const_iterator i = labels.begin(); - i != labels.end(); ++i) { - std::string label = *i; + for (std::string const& i : labels) { + std::string label = i; label.resize(maxlen + 3, ' '); char buf[1024]; - sprintf(buf, "%6.2f sec", labelTimes[*i]); + sprintf(buf, "%6.2f sec*proc", labelTimes[i]); std::ostringstream labelCountStr; - labelCountStr << "(" << labelCounts[*i] << " test"; - if (labelCounts[*i] > 1) { + labelCountStr << "(" << labelCounts[i] << " test"; + if (labelCounts[i] > 1) { labelCountStr << "s"; } labelCountStr << ")"; - cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "\n" << label << " = " << buf << " " << labelCountStr.str(), this->Quiet); if (this->LogFile) { - *this->LogFile << "\n" << *i << " = " << buf << "\n"; + *this->LogFile << "\n" << i << " = " << buf << "\n"; } } - if (!labels.empty()) { - if (this->LogFile) { - *this->LogFile << "\n"; - } - cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "\n", this->Quiet); + if (this->LogFile) { + *this->LogFile << "\n"; } + cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "\n", this->Quiet); } + void cmCTestTestHandler::CheckLabelFilterInclude(cmCTestTestProperties& it) { // if not using Labels to filter then return @@ -785,9 +709,8 @@ void cmCTestTestHandler::CheckLabelFilterInclude(cmCTestTestProperties& it) // check to see if the label regular expression matches bool found = false; // assume it does not match // loop over all labels and look for match - for (std::vector<std::string>::iterator l = it.Labels.begin(); - l != it.Labels.end(); ++l) { - if (this->IncludeLabelRegularExpression.find(*l)) { + for (std::string const& l : it.Labels) { + if (this->IncludeLabelRegularExpression.find(l)) { found = true; } } @@ -811,9 +734,8 @@ void cmCTestTestHandler::CheckLabelFilterExclude(cmCTestTestProperties& it) // check to see if the label regular expression matches bool found = false; // assume it does not match // loop over all labels and look for match - for (std::vector<std::string>::iterator l = it.Labels.begin(); - l != it.Labels.end(); ++l) { - if (this->ExcludeLabelRegularExpression.find(*l)) { + for (std::string const& l : it.Labels) { + if (this->ExcludeLabelRegularExpression.find(l)) { found = true; } } @@ -842,10 +764,9 @@ void cmCTestTestHandler::ComputeTestList() cmCTestTestHandler::ListOfTests::size_type tmsize = this->TestList.size(); // how many tests are in based on RegExp? int inREcnt = 0; - cmCTestTestHandler::ListOfTests::iterator it; - for (it = this->TestList.begin(); it != this->TestList.end(); it++) { - this->CheckLabelFilter(*it); - if (it->IsInBasedOnREOptions) { + for (cmCTestTestProperties& tp : this->TestList) { + this->CheckLabelFilter(tp); + if (tp.IsInBasedOnREOptions) { inREcnt++; } } @@ -860,9 +781,9 @@ void cmCTestTestHandler::ComputeTestList() inREcnt = 0; std::string last_directory; ListOfTests finalList; - for (it = this->TestList.begin(); it != this->TestList.end(); it++) { + for (cmCTestTestProperties& tp : this->TestList) { cnt++; - if (it->IsInBasedOnREOptions) { + if (tp.IsInBasedOnREOptions) { inREcnt++; } @@ -871,7 +792,7 @@ void cmCTestTestHandler::ComputeTestList() if ((!this->TestsToRun.empty() && std::find(this->TestsToRun.begin(), this->TestsToRun.end(), cnt) == this->TestsToRun.end()) && - !it->IsInBasedOnREOptions) { + !tp.IsInBasedOnREOptions) { continue; } } else { @@ -879,12 +800,12 @@ void cmCTestTestHandler::ComputeTestList() if ((!this->TestsToRun.empty() && std::find(this->TestsToRun.begin(), this->TestsToRun.end(), inREcnt) == this->TestsToRun.end()) || - !it->IsInBasedOnREOptions) { + !tp.IsInBasedOnREOptions) { continue; } } - it->Index = cnt; // save the index into the test list for this test - finalList.push_back(*it); + tp.Index = cnt; // save the index into the test list for this test + finalList.push_back(tp); } UpdateForFixtures(finalList); @@ -901,10 +822,9 @@ void cmCTestTestHandler::ComputeTestListForRerunFailed() { this->ExpandTestsToRunInformationForRerunFailed(); - cmCTestTestHandler::ListOfTests::iterator it; ListOfTests finalList; int cnt = 0; - for (it = this->TestList.begin(); it != this->TestList.end(); it++) { + for (cmCTestTestProperties& tp : this->TestList) { cnt++; // if this test is not in our list of tests to run, then skip it. @@ -914,8 +834,8 @@ void cmCTestTestHandler::ComputeTestListForRerunFailed() continue; } - it->Index = cnt; - finalList.push_back(*it); + tp.Index = cnt; + finalList.push_back(tp); } UpdateForFixtures(finalList); @@ -969,24 +889,18 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const it != this->TestList.end(); ++it) { const cmCTestTestProperties& p = *it; - const std::set<std::string>& setups = p.FixturesSetup; - for (std::set<std::string>::const_iterator depsIt = setups.begin(); - depsIt != setups.end(); ++depsIt) { - fixtureSetups.insert(std::make_pair(*depsIt, it)); + for (std::string const& deps : p.FixturesSetup) { + fixtureSetups.insert(std::make_pair(deps, it)); } - const std::set<std::string>& cleanups = p.FixturesCleanup; - for (std::set<std::string>::const_iterator depsIt = cleanups.begin(); - depsIt != cleanups.end(); ++depsIt) { - fixtureCleanups.insert(std::make_pair(*depsIt, it)); + for (std::string const& deps : p.FixturesCleanup) { + fixtureCleanups.insert(std::make_pair(deps, it)); } } // Prepare fast lookup of tests already included in our list of tests std::set<std::string> addedTests; - for (ListOfTests::const_iterator it = tests.begin(); it != tests.end(); - ++it) { - const cmCTestTestProperties& p = *it; + for (cmCTestTestProperties const& p : tests) { addedTests.insert(p.Name); } @@ -994,8 +908,8 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const // tests array for tests which require that fixture and tests which are // setups for that fixture. They are needed at the end to populate // dependencies of the cleanup tests in our final list of tests. - std::map<std::string, std::vector<size_t> > fixtureRequirements; - std::map<std::string, std::vector<size_t> > setupFixturesAdded; + std::map<std::string, std::vector<size_t>> fixtureRequirements; + std::map<std::string, std::vector<size_t>> setupFixturesAdded; // Use integer index for iteration because we append to // the tests vector as we go @@ -1020,10 +934,7 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const // Must copy the set of fixtures required because we may invalidate // the tests array by appending to it std::set<std::string> fixtures = tests[i].FixturesRequired; - for (std::set<std::string>::const_iterator fixturesIt = fixtures.begin(); - fixturesIt != fixtures.end(); ++fixturesIt) { - - const std::string& requiredFixtureName = *fixturesIt; + for (std::string const& requiredFixtureName : fixtures) { if (requiredFixtureName.empty()) { continue; } @@ -1122,11 +1033,7 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const } // 2. Record all setup fixtures included in the final list of tests - for (std::set<std::string>::const_iterator fixturesIt = - tests[i].FixturesSetup.begin(); - fixturesIt != tests[i].FixturesSetup.end(); ++fixturesIt) { - - const std::string& setupFixtureName = *fixturesIt; + for (std::string const& setupFixtureName : tests[i].FixturesSetup) { if (setupFixtureName.empty()) { continue; } @@ -1140,23 +1047,18 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const // setup tests for that fixture. The latter is required to handle the // pathological case where setup and cleanup tests are in the test set // but no other test has that fixture as a requirement. - for (ListOfTests::iterator tIt = tests.begin(); tIt != tests.end(); ++tIt) { - cmCTestTestProperties& p = *tIt; + for (cmCTestTestProperties& p : tests) { const std::set<std::string>& cleanups = p.FixturesCleanup; - for (std::set<std::string>::const_iterator fIt = cleanups.begin(); - fIt != cleanups.end(); ++fIt) { - const std::string& fixture = *fIt; - + for (std::string const& fixture : cleanups) { // This cleanup test could be part of the original test list that was // passed in. It is then possible that no other test requires the // fIt fixture, so we have to check for this. - std::map<std::string, std::vector<size_t> >::const_iterator cIt = + std::map<std::string, std::vector<size_t>>::const_iterator cIt = fixtureRequirements.find(fixture); if (cIt != fixtureRequirements.end()) { const std::vector<size_t>& indices = cIt->second; - for (std::vector<size_t>::const_iterator indexIt = indices.begin(); - indexIt != indices.end(); ++indexIt) { - const std::string& reqTestName = tests[*indexIt].Name; + for (size_t index : indices) { + const std::string& reqTestName = tests[index].Name; if (std::find(p.Depends.begin(), p.Depends.end(), reqTestName) == p.Depends.end()) { p.Depends.push_back(reqTestName); @@ -1169,9 +1071,8 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const cIt = setupFixturesAdded.find(fixture); if (cIt != setupFixturesAdded.end()) { const std::vector<size_t>& indices = cIt->second; - for (std::vector<size_t>::const_iterator indexIt = indices.begin(); - indexIt != indices.end(); ++indexIt) { - const std::string& setupTestName = tests[*indexIt].Name; + for (size_t index : indices) { + const std::string& setupTestName = tests[index].Name; if (std::find(p.Depends.begin(), p.Depends.end(), setupTestName) == p.Depends.end()) { p.Depends.push_back(setupTestName); @@ -1190,9 +1091,7 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const void cmCTestTestHandler::UpdateMaxTestNameWidth() { std::string::size_type max = this->CTest->GetMaxTestNameWidth(); - for (cmCTestTestHandler::ListOfTests::iterator it = this->TestList.begin(); - it != this->TestList.end(); it++) { - cmCTestTestProperties& p = *it; + for (cmCTestTestProperties& p : this->TestList) { if (max < p.Name.size()) { max = p.Name.size(); } @@ -1330,9 +1229,7 @@ void cmCTestTestHandler::ProcessDirectory(std::vector<std::string>& passed, srand(static_cast<unsigned>(time(nullptr))); } - for (ListOfTests::iterator it = this->TestList.begin(); - it != this->TestList.end(); ++it) { - cmCTestTestProperties& p = *it; + for (cmCTestTestProperties& p : this->TestList) { cmCTestMultiProcessHandler::TestSet depends; if (randomSchedule) { @@ -1344,19 +1241,17 @@ void cmCTestTestHandler::ProcessDirectory(std::vector<std::string>& passed, } if (!p.Depends.empty()) { - for (std::vector<std::string>::iterator i = p.Depends.begin(); - i != p.Depends.end(); ++i) { - for (ListOfTests::iterator it2 = this->TestList.begin(); - it2 != this->TestList.end(); ++it2) { - if (it2->Name == *i) { - depends.insert(it2->Index); + for (std::string const& i : p.Depends) { + for (cmCTestTestProperties const& it2 : this->TestList) { + if (it2.Name == i) { + depends.insert(it2.Index); break; // break out of test loop as name can only match 1 } } } } - tests[it->Index] = depends; - properties[it->Index] = &*it; + tests[p.Index] = depends; + properties[p.Index] = &p; } parallel->SetTests(tests, properties); parallel->SetPassFailVectors(&passed, &failed); @@ -1394,21 +1289,18 @@ void cmCTestTestHandler::GenerateDartOutput(cmXMLWriter& xml) xml.Element("StartDateTime", this->StartTest); xml.Element("StartTestTime", this->StartTestTime); xml.StartElement("TestList"); - cmCTestTestHandler::TestResultsVector::size_type cc; - for (cc = 0; cc < this->TestResults.size(); cc++) { - cmCTestTestResult* result = &this->TestResults[cc]; - std::string testPath = result->Path + "/" + result->Name; + for (cmCTestTestResult const& result : this->TestResults) { + std::string testPath = result.Path + "/" + result.Name; xml.Element("Test", this->CTest->GetShortPathToFile(testPath.c_str())); } xml.EndElement(); // TestList - for (cc = 0; cc < this->TestResults.size(); cc++) { - cmCTestTestResult* result = &this->TestResults[cc]; + for (cmCTestTestResult& result : this->TestResults) { this->WriteTestResultHeader(xml, result); xml.StartElement("Results"); - if (result->Status != cmCTestTestHandler::NOT_RUN) { - if (result->Status != cmCTestTestHandler::COMPLETED || - result->ReturnValue) { + if (result.Status != cmCTestTestHandler::NOT_RUN) { + if (result.Status != cmCTestTestHandler::COMPLETED || + result.ReturnValue) { xml.StartElement("NamedMeasurement"); xml.Attribute("type", "text/string"); xml.Attribute("name", "Exit Code"); @@ -1418,24 +1310,24 @@ void cmCTestTestHandler::GenerateDartOutput(cmXMLWriter& xml) xml.StartElement("NamedMeasurement"); xml.Attribute("type", "text/string"); xml.Attribute("name", "Exit Value"); - xml.Element("Value", result->ReturnValue); + xml.Element("Value", result.ReturnValue); xml.EndElement(); // NamedMeasurement } - this->GenerateRegressionImages(xml, result->DartString); + this->GenerateRegressionImages(xml, result.DartString); xml.StartElement("NamedMeasurement"); xml.Attribute("type", "numeric/double"); xml.Attribute("name", "Execution Time"); - xml.Element("Value", result->ExecutionTime); + xml.Element("Value", result.ExecutionTime); xml.EndElement(); // NamedMeasurement - if (!result->Reason.empty()) { + if (!result.Reason.empty()) { const char* reasonType = "Pass Reason"; - if (result->Status != cmCTestTestHandler::COMPLETED) { + if (result.Status != cmCTestTestHandler::COMPLETED) { reasonType = "Fail Reason"; } xml.StartElement("NamedMeasurement"); xml.Attribute("type", "text/string"); xml.Attribute("name", reasonType); - xml.Element("Value", result->Reason); + xml.Element("Value", result.Reason); xml.EndElement(); // NamedMeasurement } } @@ -1443,36 +1335,34 @@ void cmCTestTestHandler::GenerateDartOutput(cmXMLWriter& xml) xml.StartElement("NamedMeasurement"); xml.Attribute("type", "numeric/double"); xml.Attribute("name", "Processors"); - xml.Element("Value", result->Properties->Processors); + xml.Element("Value", result.Properties->Processors); xml.EndElement(); // NamedMeasurement xml.StartElement("NamedMeasurement"); xml.Attribute("type", "text/string"); xml.Attribute("name", "Completion Status"); - xml.Element("Value", result->CompletionStatus); + xml.Element("Value", result.CompletionStatus); xml.EndElement(); // NamedMeasurement xml.StartElement("NamedMeasurement"); xml.Attribute("type", "text/string"); xml.Attribute("name", "Command Line"); - xml.Element("Value", result->FullCommandLine); + xml.Element("Value", result.FullCommandLine); xml.EndElement(); // NamedMeasurement - std::map<std::string, std::string>::iterator measureIt; - for (measureIt = result->Properties->Measurements.begin(); - measureIt != result->Properties->Measurements.end(); ++measureIt) { + for (auto const& measure : result.Properties->Measurements) { xml.StartElement("NamedMeasurement"); xml.Attribute("type", "text/string"); - xml.Attribute("name", measureIt->first); - xml.Element("Value", measureIt->second); + xml.Attribute("name", measure.first); + xml.Element("Value", measure.second); xml.EndElement(); // NamedMeasurement } xml.StartElement("Measurement"); xml.StartElement("Value"); - if (result->CompressOutput) { + if (result.CompressOutput) { xml.Attribute("encoding", "base64"); xml.Attribute("compression", "gzip"); } - xml.Content(result->Output); + xml.Content(result.Output); xml.EndElement(); // Value xml.EndElement(); // Measurement xml.EndElement(); // Results @@ -1490,32 +1380,31 @@ void cmCTestTestHandler::GenerateDartOutput(cmXMLWriter& xml) } void cmCTestTestHandler::WriteTestResultHeader(cmXMLWriter& xml, - cmCTestTestResult* result) + cmCTestTestResult const& result) { xml.StartElement("Test"); - if (result->Status == cmCTestTestHandler::COMPLETED) { + if (result.Status == cmCTestTestHandler::COMPLETED) { xml.Attribute("Status", "passed"); - } else if (result->Status == cmCTestTestHandler::NOT_RUN) { + } else if (result.Status == cmCTestTestHandler::NOT_RUN) { xml.Attribute("Status", "notrun"); } else { xml.Attribute("Status", "failed"); } - std::string testPath = result->Path + "/" + result->Name; - xml.Element("Name", result->Name); - xml.Element("Path", this->CTest->GetShortPathToFile(result->Path.c_str())); + std::string testPath = result.Path + "/" + result.Name; + xml.Element("Name", result.Name); + xml.Element("Path", this->CTest->GetShortPathToFile(result.Path.c_str())); xml.Element("FullName", this->CTest->GetShortPathToFile(testPath.c_str())); - xml.Element("FullCommandLine", result->FullCommandLine); + xml.Element("FullCommandLine", result.FullCommandLine); } void cmCTestTestHandler::WriteTestResultFooter(cmXMLWriter& xml, - cmCTestTestResult* result) + cmCTestTestResult const& result) { - if (!result->Properties->Labels.empty()) { + if (!result.Properties->Labels.empty()) { xml.StartElement("Labels"); - std::vector<std::string> const& labels = result->Properties->Labels; - for (std::vector<std::string>::const_iterator li = labels.begin(); - li != labels.end(); ++li) { - xml.Element("Label", *li); + std::vector<std::string> const& labels = result.Properties->Labels; + for (std::string const& label : labels) { + xml.Element("Label", label); } xml.EndElement(); // Labels } @@ -1524,20 +1413,18 @@ void cmCTestTestHandler::WriteTestResultFooter(cmXMLWriter& xml, } void cmCTestTestHandler::AttachFiles(cmXMLWriter& xml, - cmCTestTestResult* result) + cmCTestTestResult& result) { - if (result->Status != cmCTestTestHandler::COMPLETED && - !result->Properties->AttachOnFail.empty()) { - result->Properties->AttachedFiles.insert( - result->Properties->AttachedFiles.end(), - result->Properties->AttachOnFail.begin(), - result->Properties->AttachOnFail.end()); - } - for (std::vector<std::string>::const_iterator file = - result->Properties->AttachedFiles.begin(); - file != result->Properties->AttachedFiles.end(); ++file) { - const std::string& base64 = this->CTest->Base64GzipEncodeFile(*file); - std::string fname = cmSystemTools::GetFilenameName(*file); + if (result.Status != cmCTestTestHandler::COMPLETED && + !result.Properties->AttachOnFail.empty()) { + result.Properties->AttachedFiles.insert( + result.Properties->AttachedFiles.end(), + result.Properties->AttachOnFail.begin(), + result.Properties->AttachOnFail.end()); + } + for (std::string const& file : result.Properties->AttachedFiles) { + const std::string& base64 = this->CTest->Base64GzipEncodeFile(file); + std::string const fname = cmSystemTools::GetFilenameName(file); xml.StartElement("NamedMeasurement"); xml.Attribute("name", "Attached File"); xml.Attribute("encoding", "base64"); @@ -1551,18 +1438,16 @@ void cmCTestTestHandler::AttachFiles(cmXMLWriter& xml, int cmCTestTestHandler::ExecuteCommands(std::vector<std::string>& vec) { - std::vector<std::string>::iterator it; - for (it = vec.begin(); it != vec.end(); ++it) { + for (std::string const& it : vec) { int retVal = 0; cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, - "Run command: " << *it << std::endl, this->Quiet); - if (!cmSystemTools::RunSingleCommand(it->c_str(), nullptr, nullptr, - &retVal, nullptr, - cmSystemTools::OUTPUT_MERGE + "Run command: " << it << std::endl, this->Quiet); + if (!cmSystemTools::RunSingleCommand(it.c_str(), nullptr, nullptr, &retVal, + nullptr, cmSystemTools::OUTPUT_MERGE /*this->Verbose*/) || retVal != 0) { cmCTestLog(this->CTest, ERROR_MESSAGE, - "Problem running command: " << *it << std::endl); + "Problem running command: " << it << std::endl); return 0; } } @@ -1673,11 +1558,9 @@ std::string cmCTestTestHandler::FindExecutable( // if extraPaths are provided and we were not passed a full path, try them, // try any extra paths if (filepath.empty()) { - for (unsigned int i = 0; i < extraPaths.size(); ++i) { - std::string filepathExtra = - cmSystemTools::GetFilenamePath(extraPaths[i]); - std::string filenameExtra = - cmSystemTools::GetFilenameName(extraPaths[i]); + for (std::string const& extraPath : extraPaths) { + std::string filepathExtra = cmSystemTools::GetFilenamePath(extraPath); + std::string filenameExtra = cmSystemTools::GetFilenameName(extraPath); cmCTestTestHandler::AddConfigurations(ctest, attempted, attemptedConfigs, filepathExtra, filenameExtra); } @@ -1712,9 +1595,9 @@ std::string cmCTestTestHandler::FindExecutable( // if everything else failed, check the users path, but only if a full path // wasn't specified if (fullPath.empty() && filepath.empty()) { - std::string path = cmSystemTools::FindProgram(filename.c_str()); - if (path != "") { - resultingConfig = ""; + std::string const path = cmSystemTools::FindProgram(filename.c_str()); + if (!path.empty()) { + resultingConfig.clear(); return path; } } @@ -1722,9 +1605,8 @@ std::string cmCTestTestHandler::FindExecutable( cmCTestLog(ctest, HANDLER_OUTPUT, "Could not find executable " << testCommand << "\n" << "Looked in the following places:\n"); - for (std::vector<std::string>::iterator i = failed.begin(); - i != failed.end(); ++i) { - cmCTestLog(ctest, HANDLER_OUTPUT, *i << "\n"); + for (std::string const& f : failed) { + cmCTestLog(ctest, HANDLER_OUTPUT, f << "\n"); } } @@ -1754,9 +1636,9 @@ void cmCTestTestHandler::GetListOfTests() cm.SetHomeOutputDirectory(""); cm.GetCurrentSnapshot().SetDefaultDefinitions(); cmGlobalGenerator gg(&cm); - CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot())); - mf->AddDefinition("CTEST_CONFIGURATION_TYPE", - this->CTest->GetConfigType().c_str()); + cmMakefile mf(&gg, cm.GetCurrentSnapshot()); + mf.AddDefinition("CTEST_CONFIGURATION_TYPE", + this->CTest->GetConfigType().c_str()); // Add handler for ADD_TEST cmCTestAddTestCommand* newCom1 = new cmCTestAddTestCommand; @@ -1796,7 +1678,7 @@ void cmCTestTestHandler::GetListOfTests() return; } - if (!mf->ReadListFile(testFilename)) { + if (!mf.ReadListFile(testFilename)) { return; } if (cmSystemTools::GetErrorOccuredFlag()) { @@ -1818,19 +1700,19 @@ void cmCTestTestHandler::UseExcludeRegExp() this->UseExcludeRegExpFirst = !this->UseIncludeRegExpFlag; } -const char* cmCTestTestHandler::GetTestStatus(const cmCTestTestResult* result) +const char* cmCTestTestHandler::GetTestStatus(cmCTestTestResult const& result) { static const char* statuses[] = { "Not Run", "Timeout", "SEGFAULT", "ILLEGAL", "INTERRUPT", "NUMERICAL", "OTHER_FAULT", "Failed", "BAD_COMMAND", "Completed" }; - int status = result->Status; + int status = result.Status; if (status < cmCTestTestHandler::NOT_RUN || status > cmCTestTestHandler::COMPLETED) { return "No Status"; } if (status == cmCTestTestHandler::OTHER_FAULT) { - return result->ExceptionStatus.c_str(); + return result.ExceptionStatus.c_str(); } return statuses[status]; } @@ -1920,7 +1802,7 @@ void cmCTestTestHandler::ExpandTestsToRunInformationForRerunFailed() if (fileNameSubstring != pattern) { continue; } - if (logName == "") { + if (logName.empty()) { logName = fileName; } else { // if multiple matching logs were found we use the most recently @@ -2214,125 +2096,117 @@ bool cmCTestTestHandler::SetTestsProperties( break; } std::string val = *it; - std::vector<std::string>::const_iterator tit; - for (tit = tests.begin(); tit != tests.end(); ++tit) { - cmCTestTestHandler::ListOfTests::iterator rtit; - for (rtit = this->TestList.begin(); rtit != this->TestList.end(); - ++rtit) { - if (*tit == rtit->Name) { + for (std::string const& t : tests) { + for (cmCTestTestProperties& rt : this->TestList) { + if (t == rt.Name) { if (key == "WILL_FAIL") { - rtit->WillFail = cmSystemTools::IsOn(val.c_str()); + rt.WillFail = cmSystemTools::IsOn(val.c_str()); } if (key == "DISABLED") { - rtit->Disabled = cmSystemTools::IsOn(val.c_str()); + rt.Disabled = cmSystemTools::IsOn(val.c_str()); } if (key == "ATTACHED_FILES") { - cmSystemTools::ExpandListArgument(val, rtit->AttachedFiles); + cmSystemTools::ExpandListArgument(val, rt.AttachedFiles); } if (key == "ATTACHED_FILES_ON_FAIL") { - cmSystemTools::ExpandListArgument(val, rtit->AttachOnFail); + cmSystemTools::ExpandListArgument(val, rt.AttachOnFail); } if (key == "RESOURCE_LOCK") { std::vector<std::string> lval; cmSystemTools::ExpandListArgument(val, lval); - rtit->LockedResources.insert(lval.begin(), lval.end()); + rt.LockedResources.insert(lval.begin(), lval.end()); } if (key == "FIXTURES_SETUP") { std::vector<std::string> lval; cmSystemTools::ExpandListArgument(val, lval); - rtit->FixturesSetup.insert(lval.begin(), lval.end()); + rt.FixturesSetup.insert(lval.begin(), lval.end()); } if (key == "FIXTURES_CLEANUP") { std::vector<std::string> lval; cmSystemTools::ExpandListArgument(val, lval); - rtit->FixturesCleanup.insert(lval.begin(), lval.end()); + rt.FixturesCleanup.insert(lval.begin(), lval.end()); } if (key == "FIXTURES_REQUIRED") { std::vector<std::string> lval; cmSystemTools::ExpandListArgument(val, lval); - rtit->FixturesRequired.insert(lval.begin(), lval.end()); + rt.FixturesRequired.insert(lval.begin(), lval.end()); } if (key == "TIMEOUT") { - rtit->Timeout = atof(val.c_str()); - rtit->ExplicitTimeout = true; + rt.Timeout = atof(val.c_str()); + rt.ExplicitTimeout = true; } if (key == "COST") { - rtit->Cost = static_cast<float>(atof(val.c_str())); + rt.Cost = static_cast<float>(atof(val.c_str())); } if (key == "REQUIRED_FILES") { - cmSystemTools::ExpandListArgument(val, rtit->RequiredFiles); + cmSystemTools::ExpandListArgument(val, rt.RequiredFiles); } if (key == "RUN_SERIAL") { - rtit->RunSerial = cmSystemTools::IsOn(val.c_str()); + rt.RunSerial = cmSystemTools::IsOn(val.c_str()); } if (key == "FAIL_REGULAR_EXPRESSION") { std::vector<std::string> lval; cmSystemTools::ExpandListArgument(val, lval); - std::vector<std::string>::iterator crit; - for (crit = lval.begin(); crit != lval.end(); ++crit) { - rtit->ErrorRegularExpressions.push_back( + for (std::string const& cr : lval) { + rt.ErrorRegularExpressions.push_back( std::pair<cmsys::RegularExpression, std::string>( - cmsys::RegularExpression(crit->c_str()), - std::string(*crit))); + cmsys::RegularExpression(cr.c_str()), std::string(cr))); } } if (key == "PROCESSORS") { - rtit->Processors = atoi(val.c_str()); - if (rtit->Processors < 1) { - rtit->Processors = 1; + rt.Processors = atoi(val.c_str()); + if (rt.Processors < 1) { + rt.Processors = 1; } } if (key == "SKIP_RETURN_CODE") { - rtit->SkipReturnCode = atoi(val.c_str()); - if (rtit->SkipReturnCode < 0 || rtit->SkipReturnCode > 255) { - rtit->SkipReturnCode = -1; + rt.SkipReturnCode = atoi(val.c_str()); + if (rt.SkipReturnCode < 0 || rt.SkipReturnCode > 255) { + rt.SkipReturnCode = -1; } } if (key == "DEPENDS") { - cmSystemTools::ExpandListArgument(val, rtit->Depends); + cmSystemTools::ExpandListArgument(val, rt.Depends); } if (key == "ENVIRONMENT") { - cmSystemTools::ExpandListArgument(val, rtit->Environment); + cmSystemTools::ExpandListArgument(val, rt.Environment); } if (key == "LABELS") { std::vector<std::string> Labels; cmSystemTools::ExpandListArgument(val, Labels); - rtit->Labels.insert(rtit->Labels.end(), Labels.begin(), - Labels.end()); + rt.Labels.insert(rt.Labels.end(), Labels.begin(), Labels.end()); // sort the array - std::sort(rtit->Labels.begin(), rtit->Labels.end()); + std::sort(rt.Labels.begin(), rt.Labels.end()); // remove duplicates std::vector<std::string>::iterator new_end = - std::unique(rtit->Labels.begin(), rtit->Labels.end()); - rtit->Labels.erase(new_end, rtit->Labels.end()); + std::unique(rt.Labels.begin(), rt.Labels.end()); + rt.Labels.erase(new_end, rt.Labels.end()); } if (key == "MEASUREMENT") { size_t pos = val.find_first_of('='); if (pos != std::string::npos) { std::string mKey = val.substr(0, pos); const char* mVal = val.c_str() + pos + 1; - rtit->Measurements[mKey] = mVal; + rt.Measurements[mKey] = mVal; } else { - rtit->Measurements[val] = "1"; + rt.Measurements[val] = "1"; } } if (key == "PASS_REGULAR_EXPRESSION") { std::vector<std::string> lval; cmSystemTools::ExpandListArgument(val, lval); - std::vector<std::string>::iterator crit; - for (crit = lval.begin(); crit != lval.end(); ++crit) { - rtit->RequiredRegularExpressions.push_back( + for (std::string const& cr : lval) { + rt.RequiredRegularExpressions.push_back( std::pair<cmsys::RegularExpression, std::string>( - cmsys::RegularExpression(crit->c_str()), - std::string(*crit))); + cmsys::RegularExpression(cr.c_str()), std::string(cr))); } } if (key == "WORKING_DIRECTORY") { - rtit->Directory = val; + rt.Directory = val; } if (key == "TIMEOUT_AFTER_MATCH") { std::vector<std::string> propArgs; @@ -2342,15 +2216,13 @@ bool cmCTestTestHandler::SetTestsProperties( "TIMEOUT_AFTER_MATCH expects two arguments, found " << propArgs.size() << std::endl); } else { - rtit->AlternateTimeout = atof(propArgs[0].c_str()); + rt.AlternateTimeout = atof(propArgs[0].c_str()); std::vector<std::string> lval; cmSystemTools::ExpandListArgument(propArgs[1], lval); - std::vector<std::string>::iterator crit; - for (crit = lval.begin(); crit != lval.end(); ++crit) { - rtit->TimeoutRegularExpressions.push_back( + for (std::string const& cr : lval) { + rt.TimeoutRegularExpressions.push_back( std::pair<cmsys::RegularExpression, std::string>( - cmsys::RegularExpression(crit->c_str()), - std::string(*crit))); + cmsys::RegularExpression(cr.c_str()), std::string(cr))); } } } @@ -2386,22 +2258,21 @@ bool cmCTestTestHandler::SetDirectoryProperties( break; } std::string val = *it; - cmCTestTestHandler::ListOfTests::iterator rtit; - for (rtit = this->TestList.begin(); rtit != this->TestList.end(); ++rtit) { + for (cmCTestTestProperties& rt : this->TestList) { std::string cwd = cmSystemTools::GetCurrentWorkingDirectory(); - if (cwd == rtit->Directory) { + if (cwd == rt.Directory) { if (key == "LABELS") { std::vector<std::string> DirectoryLabels; cmSystemTools::ExpandListArgument(val, DirectoryLabels); - rtit->Labels.insert(rtit->Labels.end(), DirectoryLabels.begin(), - DirectoryLabels.end()); + rt.Labels.insert(rt.Labels.end(), DirectoryLabels.begin(), + DirectoryLabels.end()); // sort the array - std::sort(rtit->Labels.begin(), rtit->Labels.end()); + std::sort(rt.Labels.begin(), rt.Labels.end()); // remove duplicates std::vector<std::string>::iterator new_end = - std::unique(rtit->Labels.begin(), rtit->Labels.end()); - rtit->Labels.erase(new_end, rtit->Labels.end()); + std::unique(rt.Labels.begin(), rt.Labels.end()); + rt.Labels.erase(new_end, rt.Labels.end()); } } } diff --git a/Source/CTest/cmCTestTestHandler.h b/Source/CTest/cmCTestTestHandler.h index d8627b1..394d20e 100644 --- a/Source/CTest/cmCTestTestHandler.h +++ b/Source/CTest/cmCTestTestHandler.h @@ -36,7 +36,7 @@ public: /** * The main entry point for this class */ - int ProcessHandler() CM_OVERRIDE; + int ProcessHandler() override; /** * When both -R and -I are used should te resulting test list be the @@ -54,7 +54,7 @@ public: /** * This method is called when reading CTest custom file */ - void PopulateCustomVectors(cmMakefile* mf) CM_OVERRIDE; + void PopulateCustomVectors(cmMakefile* mf) override; ///! Control the use of the regular expresisons, call these methods to turn /// them on @@ -95,7 +95,7 @@ public: */ bool SetDirectoryProperties(const std::vector<std::string>& args); - void Initialize() CM_OVERRIDE; + void Initialize() override; // NOTE: This struct is Saved/Restored // in cmCTestTestHandler, if you add to this class @@ -110,11 +110,11 @@ public: std::vector<std::string> Depends; std::vector<std::string> AttachedFiles; std::vector<std::string> AttachOnFail; - std::vector<std::pair<cmsys::RegularExpression, std::string> > + std::vector<std::pair<cmsys::RegularExpression, std::string>> ErrorRegularExpressions; - std::vector<std::pair<cmsys::RegularExpression, std::string> > + std::vector<std::pair<cmsys::RegularExpression, std::string>> RequiredRegularExpressions; - std::vector<std::pair<cmsys::RegularExpression, std::string> > + std::vector<std::pair<cmsys::RegularExpression, std::string>> TimeoutRegularExpressions; std::map<std::string, std::string> Measurements; bool IsInBasedOnREOptions; @@ -188,10 +188,12 @@ protected: virtual void GenerateTestCommand(std::vector<std::string>& args, int test); int ExecuteCommands(std::vector<std::string>& vec); - void WriteTestResultHeader(cmXMLWriter& xml, cmCTestTestResult* result); - void WriteTestResultFooter(cmXMLWriter& xml, cmCTestTestResult* result); + void WriteTestResultHeader(cmXMLWriter& xml, + cmCTestTestResult const& result); + void WriteTestResultFooter(cmXMLWriter& xml, + cmCTestTestResult const& result); // Write attached test files into the xml - void AttachFiles(cmXMLWriter& xml, cmCTestTestResult* result); + void AttachFiles(cmXMLWriter& xml, cmCTestTestResult& result); //! Clean test output to specified length bool CleanTestOutput(std::string& output, size_t length); @@ -232,8 +234,7 @@ private: */ virtual void GenerateDartOutput(cmXMLWriter& xml); - void PrintLabelSummary(); - void PrintSubprojectSummary(); + void PrintLabelOrSubprojectSummary(bool isSubProject); /** * Run the tests for a directory and any subdirectories @@ -270,7 +271,7 @@ private: */ std::string FindTheExecutable(const char* exe); - const char* GetTestStatus(const cmCTestTestResult*); + const char* GetTestStatus(cmCTestTestResult const&); void ExpandTestsToRunInformation(size_t numPossibleTests); void ExpandTestsToRunInformationForRerunFailed(); diff --git a/Source/CTest/cmCTestUpdateCommand.h b/Source/CTest/cmCTestUpdateCommand.h index ac8e85c..3b2f3e1 100644 --- a/Source/CTest/cmCTestUpdateCommand.h +++ b/Source/CTest/cmCTestUpdateCommand.h @@ -25,7 +25,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmCTestUpdateCommand* ni = new cmCTestUpdateCommand; ni->CTest = this->CTest; @@ -36,10 +36,10 @@ public: /** * The name of the command as specified in CMakeList.txt. */ - std::string GetName() const CM_OVERRIDE { return "ctest_update"; } + std::string GetName() const override { return "ctest_update"; } protected: - cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE; + cmCTestGenericHandler* InitializeHandler() override; }; #endif diff --git a/Source/CTest/cmCTestUpdateHandler.cxx b/Source/CTest/cmCTestUpdateHandler.cxx index 0504f90..786ed5e 100644 --- a/Source/CTest/cmCTestUpdateHandler.cxx +++ b/Source/CTest/cmCTestUpdateHandler.cxx @@ -2,6 +2,7 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmCTestUpdateHandler.h" +#include "cmAlgorithms.h" #include "cmCLocaleEnvironmentScope.h" #include "cmCTest.h" #include "cmCTestBZR.h" @@ -16,7 +17,7 @@ #include "cmVersion.h" #include "cmXMLWriter.h" -#include "cm_auto_ptr.hxx" +#include <memory> // IWYU pragma: keep #include <sstream> static const char* cmCTestUpdateHandlerUpdateStrings[] = { @@ -39,7 +40,7 @@ cmCTestUpdateHandler::cmCTestUpdateHandler() void cmCTestUpdateHandler::Initialize() { this->Superclass::Initialize(); - this->UpdateCommand = ""; + this->UpdateCommand.clear(); this->UpdateType = e_CVS; } @@ -134,28 +135,28 @@ int cmCTestUpdateHandler::ProcessHandler() , this->Quiet); // Create an object to interact with the VCS tool. - CM_AUTO_PTR<cmCTestVC> vc; + std::unique_ptr<cmCTestVC> vc; switch (this->UpdateType) { case e_CVS: - vc.reset(new cmCTestCVS(this->CTest, ofs)); + vc = cm::make_unique<cmCTestCVS>(this->CTest, ofs); break; case e_SVN: - vc.reset(new cmCTestSVN(this->CTest, ofs)); + vc = cm::make_unique<cmCTestSVN>(this->CTest, ofs); break; case e_BZR: - vc.reset(new cmCTestBZR(this->CTest, ofs)); + vc = cm::make_unique<cmCTestBZR>(this->CTest, ofs); break; case e_GIT: - vc.reset(new cmCTestGIT(this->CTest, ofs)); + vc = cm::make_unique<cmCTestGIT>(this->CTest, ofs); break; case e_HG: - vc.reset(new cmCTestHG(this->CTest, ofs)); + vc = cm::make_unique<cmCTestHG>(this->CTest, ofs); break; case e_P4: - vc.reset(new cmCTestP4(this->CTest, ofs)); + vc = cm::make_unique<cmCTestP4>(this->CTest, ofs); break; default: - vc.reset(new cmCTestVC(this->CTest, ofs)); + vc = cm::make_unique<cmCTestVC>(this->CTest, ofs); break; } vc->SetCommandLineTool(this->UpdateCommand); diff --git a/Source/CTest/cmCTestUpdateHandler.h b/Source/CTest/cmCTestUpdateHandler.h index 5e7237c..0f51d3f 100644 --- a/Source/CTest/cmCTestUpdateHandler.h +++ b/Source/CTest/cmCTestUpdateHandler.h @@ -23,7 +23,7 @@ public: /* * The main entry point for this class */ - int ProcessHandler() CM_OVERRIDE; + int ProcessHandler() override; cmCTestUpdateHandler(); @@ -42,7 +42,7 @@ public: /** * Initialize handler */ - void Initialize() CM_OVERRIDE; + void Initialize() override; private: // Some structures needed for update diff --git a/Source/CTest/cmCTestUploadCommand.h b/Source/CTest/cmCTestUploadCommand.h index e8e882f..61bf1cc 100644 --- a/Source/CTest/cmCTestUploadCommand.h +++ b/Source/CTest/cmCTestUploadCommand.h @@ -27,7 +27,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmCTestUploadCommand* ni = new cmCTestUploadCommand; ni->CTest = this->CTest; @@ -38,15 +38,15 @@ public: /** * The name of the command as specified in CMakeList.txt. */ - std::string GetName() const CM_OVERRIDE { return "ctest_upload"; } + std::string GetName() const override { return "ctest_upload"; } typedef cmCTestHandlerCommand Superclass; protected: - cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE; + cmCTestGenericHandler* InitializeHandler() override; - bool CheckArgumentKeyword(std::string const& arg) CM_OVERRIDE; - bool CheckArgumentValue(std::string const& arg) CM_OVERRIDE; + bool CheckArgumentKeyword(std::string const& arg) override; + bool CheckArgumentValue(std::string const& arg) override; enum { diff --git a/Source/CTest/cmCTestUploadHandler.cxx b/Source/CTest/cmCTestUploadHandler.cxx index 05a3984..59a5de4 100644 --- a/Source/CTest/cmCTestUploadHandler.cxx +++ b/Source/CTest/cmCTestUploadHandler.cxx @@ -7,7 +7,6 @@ #include "cmXMLWriter.h" #include <ostream> -#include <set> #include <string> cmCTestUploadHandler::cmCTestUploadHandler() @@ -37,7 +36,6 @@ int cmCTestUploadHandler::ProcessHandler() } std::string buildname = cmCTest::SafeBuildIdField(this->CTest->GetCTestConfiguration("BuildName")); - cmCTest::SetOfStrings::const_iterator it; cmXMLWriter xml(ofs); xml.StartDocument(); @@ -55,14 +53,14 @@ int cmCTestUploadHandler::ProcessHandler() this->CTest->AddSiteProperties(xml); xml.StartElement("Upload"); - for (it = this->Files.begin(); it != this->Files.end(); it++) { + for (std::string const& file : this->Files) { cmCTestOptionalLog(this->CTest, OUTPUT, - "\tUpload file: " << *it << std::endl, this->Quiet); + "\tUpload file: " << file << std::endl, this->Quiet); xml.StartElement("File"); - xml.Attribute("filename", *it); + xml.Attribute("filename", file); xml.StartElement("Content"); xml.Attribute("encoding", "base64"); - xml.Content(this->CTest->Base64EncodeFile(*it)); + xml.Content(this->CTest->Base64EncodeFile(file)); xml.EndElement(); // Content xml.EndElement(); // File } diff --git a/Source/CTest/cmCTestUploadHandler.h b/Source/CTest/cmCTestUploadHandler.h index 3dc9c10..ff50574 100644 --- a/Source/CTest/cmCTestUploadHandler.h +++ b/Source/CTest/cmCTestUploadHandler.h @@ -20,14 +20,14 @@ public: typedef cmCTestGenericHandler Superclass; cmCTestUploadHandler(); - ~cmCTestUploadHandler() CM_OVERRIDE {} + ~cmCTestUploadHandler() override {} /* * The main entry point for this class */ - int ProcessHandler() CM_OVERRIDE; + int ProcessHandler() override; - void Initialize() CM_OVERRIDE; + void Initialize() override; /** Specify a set of files to submit. */ void SetFiles(cmCTest::SetOfStrings const& files); diff --git a/Source/CTest/cmCTestVC.cxx b/Source/CTest/cmCTestVC.cxx index 186d2d4..7e09ef0 100644 --- a/Source/CTest/cmCTestVC.cxx +++ b/Source/CTest/cmCTestVC.cxx @@ -56,9 +56,8 @@ bool cmCTestVC::InitialCheckout(const char* command) // Construct the initial checkout command line. std::vector<std::string> args = cmSystemTools::ParseArguments(command); std::vector<char const*> vc_co; - for (std::vector<std::string>::const_iterator ai = args.begin(); - ai != args.end(); ++ai) { - vc_co.push_back(ai->c_str()); + for (std::string const& arg : args) { + vc_co.push_back(arg.c_str()); } vc_co.push_back(nullptr); diff --git a/Source/CTest/cmParseBlanketJSCoverage.cxx b/Source/CTest/cmParseBlanketJSCoverage.cxx index 83a7b75..308e6f7 100644 --- a/Source/CTest/cmParseBlanketJSCoverage.cxx +++ b/Source/CTest/cmParseBlanketJSCoverage.cxx @@ -112,17 +112,15 @@ cmParseBlanketJSCoverage::cmParseBlanketJSCoverage( bool cmParseBlanketJSCoverage::LoadCoverageData(std::vector<std::string> files) { - size_t i = 0; - std::string path; cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Found " << files.size() << " Files" << std::endl, this->Coverage.Quiet); - for (i = 0; i < files.size(); i++) { + for (std::string const& file : files) { cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, - "Reading JSON File " << files[i] << std::endl, + "Reading JSON File " << file << std::endl, this->Coverage.Quiet); - if (!this->ReadJSONFile(files[i])) { + if (!this->ReadJSONFile(file)) { return false; } } diff --git a/Source/CTest/cmParseCacheCoverage.cxx b/Source/CTest/cmParseCacheCoverage.cxx index 629010c..4cd6588 100644 --- a/Source/CTest/cmParseCacheCoverage.cxx +++ b/Source/CTest/cmParseCacheCoverage.cxx @@ -53,10 +53,8 @@ void cmParseCacheCoverage::RemoveUnCoveredFiles() while (ci != this->Coverage.TotalCoverage.end()) { cmCTestCoverageHandlerContainer::SingleFileCoverageVector& v = ci->second; bool nothing = true; - for (cmCTestCoverageHandlerContainer::SingleFileCoverageVector::iterator - i = v.begin(); - i != v.end(); ++i) { - if (*i > 0) { + for (int i : v) { + if (i > 0) { nothing = false; break; } @@ -148,7 +146,7 @@ bool cmParseCacheCoverage::ReadCMCovFile(const char* file) cmCTestLog(this->CTest, ERROR_MESSAGE, "Could not find mumps file for routine: " << routine << "\n"); - filepath = ""; + filepath.clear(); continue; // move to next line } } @@ -156,8 +154,8 @@ bool cmParseCacheCoverage::ReadCMCovFile(const char* file) else { // Totals in arg 0 marks the end of a routine if (separateLine[0].substr(0, 6) == "Totals") { - routine = ""; // at the end of this routine - filepath = ""; + routine.clear(); // at the end of this routine + filepath.clear(); continue; // move to next line } } diff --git a/Source/CTest/cmParseCacheCoverage.h b/Source/CTest/cmParseCacheCoverage.h index 7b0442a..081f5fa 100644 --- a/Source/CTest/cmParseCacheCoverage.h +++ b/Source/CTest/cmParseCacheCoverage.h @@ -26,7 +26,7 @@ public: protected: // implement virtual from parent - bool LoadCoverageData(const char* dir) CM_OVERRIDE; + bool LoadCoverageData(const char* dir) override; // remove files with no coverage void RemoveUnCoveredFiles(); // Read a single mcov file diff --git a/Source/CTest/cmParseCoberturaCoverage.cxx b/Source/CTest/cmParseCoberturaCoverage.cxx index 4a16a48..61ce7d4 100644 --- a/Source/CTest/cmParseCoberturaCoverage.cxx +++ b/Source/CTest/cmParseCoberturaCoverage.cxx @@ -21,13 +21,13 @@ public: this->SkipThisClass = false; this->FilePaths.push_back(this->Coverage.SourceDir); this->FilePaths.push_back(this->Coverage.BinaryDir); - this->CurFileName = ""; + this->CurFileName.clear(); } - ~XMLParser() CM_OVERRIDE {} + ~XMLParser() override {} protected: - void EndElement(const std::string& name) CM_OVERRIDE + void EndElement(const std::string& name) override { if (name == "source") { this->InSource = false; @@ -38,7 +38,7 @@ protected: } } - void CharacterDataHandler(const char* data, int length) CM_OVERRIDE + void CharacterDataHandler(const char* data, int length) override { std::string tmp; tmp.insert(0, data, length); @@ -50,7 +50,7 @@ protected: } } - void StartElement(const std::string& name, const char** atts) CM_OVERRIDE + void StartElement(const std::string& name, const char** atts) override { std::string FoundSource; std::string finalpath; @@ -67,22 +67,22 @@ protected: << std::endl, this->Coverage.Quiet); std::string filename = atts[tagCount + 1]; - this->CurFileName = ""; + this->CurFileName.clear(); // Check if this is an absolute path that falls within our // source or binary directories. - for (size_t i = 0; i < FilePaths.size(); i++) { - if (filename.find(FilePaths[i]) == 0) { + for (std::string const& filePath : FilePaths) { + if (filename.find(filePath) == 0) { this->CurFileName = filename; break; } } - if (this->CurFileName == "") { + if (this->CurFileName.empty()) { // Check if this is a path that is relative to our source or // binary directories. - for (size_t i = 0; i < FilePaths.size(); i++) { - finalpath = FilePaths[i] + "/" + filename; + for (std::string const& filePath : FilePaths) { + finalpath = filePath + "/" + filename; if (cmSystemTools::FileExists(finalpath.c_str())) { this->CurFileName = finalpath; break; @@ -91,7 +91,7 @@ protected: } cmsys::ifstream fin(this->CurFileName.c_str()); - if (this->CurFileName == "" || !fin) { + if (this->CurFileName.empty() || !fin) { this->CurFileName = this->Coverage.BinaryDir + "/" + atts[tagCount + 1]; fin.open(this->CurFileName.c_str()); diff --git a/Source/CTest/cmParseDelphiCoverage.cxx b/Source/CTest/cmParseDelphiCoverage.cxx index 4b781a6..6d82cb2 100644 --- a/Source/CTest/cmParseDelphiCoverage.cxx +++ b/Source/CTest/cmParseDelphiCoverage.cxx @@ -71,7 +71,8 @@ public: } } // Based up what was found, add a line to the coverageVector - if (!beginSet.empty() && line != "" && !blockComFlag && !lineComFlag) { + if (!beginSet.empty() && !line.empty() && !blockComFlag && + !lineComFlag) { coverageVector.push_back(0); } else { coverageVector.push_back(-1); diff --git a/Source/CTest/cmParseGTMCoverage.cxx b/Source/CTest/cmParseGTMCoverage.cxx index e4ee699..9948ede 100644 --- a/Source/CTest/cmParseGTMCoverage.cxx +++ b/Source/CTest/cmParseGTMCoverage.cxx @@ -182,7 +182,7 @@ bool cmParseGTMCoverage::ParseMCOVLine(std::string const& line, // save the argument into the argument vector args.push_back(arg); // start on a new argument - arg = ""; + arg.clear(); // if we are at the end of the ), then finish while loop if (cur == ')') { done = true; @@ -233,8 +233,8 @@ bool cmParseGTMCoverage::ParseMCOVLine(std::string const& line, // To avoid double counting of line 0 of each entry point, // Don't count the lines that do not give an explicit line // number. - routine = ""; - function = ""; + routine.clear(); + function.clear(); } else { // this is the format for this line // ^COVERAGE("%RSEL","SRC",count) diff --git a/Source/CTest/cmParseGTMCoverage.h b/Source/CTest/cmParseGTMCoverage.h index 81766f9..13afbbc 100644 --- a/Source/CTest/cmParseGTMCoverage.h +++ b/Source/CTest/cmParseGTMCoverage.h @@ -25,7 +25,7 @@ public: protected: // implement virtual from parent - bool LoadCoverageData(const char* dir) CM_OVERRIDE; + bool LoadCoverageData(const char* dir) override; // Read a single mcov file bool ReadMCovFile(const char* f); // find out what line in a mumps file (filepath) the given entry point diff --git a/Source/CTest/cmParseJacocoCoverage.cxx b/Source/CTest/cmParseJacocoCoverage.cxx index 6d884ef..7acb5ca 100644 --- a/Source/CTest/cmParseJacocoCoverage.cxx +++ b/Source/CTest/cmParseJacocoCoverage.cxx @@ -18,25 +18,25 @@ public: : CTest(ctest) , Coverage(cont) { - this->FilePath = ""; - this->PackagePath = ""; - this->PackageName = ""; + this->FilePath.clear(); + this->PackagePath.clear(); + this->PackageName.clear(); } - ~XMLParser() CM_OVERRIDE {} + ~XMLParser() override {} protected: - void EndElement(const std::string& /*name*/) CM_OVERRIDE {} + void EndElement(const std::string& /*name*/) override {} - void StartElement(const std::string& name, const char** atts) CM_OVERRIDE + void StartElement(const std::string& name, const char** atts) override { if (name == "package") { this->PackageName = atts[1]; - this->PackagePath = ""; + this->PackagePath.clear(); } else if (name == "sourcefile") { std::string fileName = atts[1]; - if (this->PackagePath == "") { + if (this->PackagePath.empty()) { if (!this->FindPackagePath(fileName)) { cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot find file: " << this->PackageName << "/" << fileName << std::endl); @@ -119,9 +119,8 @@ protected: } // Check if any of the locations found match our package. - for (std::vector<std::string>::const_iterator fi = files.begin(); - fi != files.end(); ++fi) { - std::string dir = cmsys::SystemTools::GetParentDirectory(*fi); + for (std::string const& f : files) { + std::string dir = cmsys::SystemTools::GetParentDirectory(f); if (cmsys::SystemTools::StringEndsWith(dir, this->PackageName.c_str())) { cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Found package directory for " << fileName << ": " diff --git a/Source/CTest/cmParseMumpsCoverage.cxx b/Source/CTest/cmParseMumpsCoverage.cxx index 8cb1170..1419743 100644 --- a/Source/CTest/cmParseMumpsCoverage.cxx +++ b/Source/CTest/cmParseMumpsCoverage.cxx @@ -9,7 +9,6 @@ #include <map> #include <string> #include <utility> -#include <vector> cmParseMumpsCoverage::cmParseMumpsCoverage( cmCTestCoverageHandlerContainer& cont, cmCTest* ctest) @@ -112,14 +111,12 @@ bool cmParseMumpsCoverage::LoadPackages(const char* d) std::string pat = d; pat += "/*.m"; glob.FindFiles(pat); - std::vector<std::string>& files = glob.GetFiles(); - std::vector<std::string>::iterator fileIt; - for (fileIt = files.begin(); fileIt != files.end(); ++fileIt) { - std::string name = cmSystemTools::GetFilenameName(*fileIt); - this->RoutineToDirectory[name.substr(0, name.size() - 2)] = *fileIt; + for (std::string& file : glob.GetFiles()) { + std::string name = cmSystemTools::GetFilenameName(file); + this->RoutineToDirectory[name.substr(0, name.size() - 2)] = file; // initialze each file, this is left out until CDash is fixed // to handle large numbers of files - this->InitializeMumpsFile(*fileIt); + this->InitializeMumpsFile(file); } return true; } diff --git a/Source/CTest/cmProcess.cxx b/Source/CTest/cmProcess.cxx index 5ada25d..f3c191b 100644 --- a/Source/CTest/cmProcess.cxx +++ b/Source/CTest/cmProcess.cxx @@ -40,9 +40,8 @@ bool cmProcess::StartProcess() // put the command as arg0 this->ProcessArgs.push_back(this->Command.c_str()); // now put the command arguments in - for (std::vector<std::string>::iterator i = this->Arguments.begin(); - i != this->Arguments.end(); ++i) { - this->ProcessArgs.push_back(i->c_str()); + for (std::string const& arg : this->Arguments) { + this->ProcessArgs.push_back(arg.c_str()); } this->ProcessArgs.push_back(nullptr); // null terminate the list this->Process = cmsysProcess_New(); diff --git a/Source/Checks/cm_cxx_features.cmake b/Source/Checks/cm_cxx_features.cmake index 7f2b8a0..2c39cbe 100644 --- a/Source/Checks/cm_cxx_features.cmake +++ b/Source/Checks/cm_cxx_features.cmake @@ -14,8 +14,11 @@ function(cm_check_cxx_feature name) CMAKE_FLAGS ${maybe_cxx_standard} OUTPUT_VARIABLE OUTPUT ) + set(check_output "${OUTPUT}") # Filter out MSBuild output that looks like a warning. - string(REGEX REPLACE " +0 Warning\\(s\\)" "" check_output "${OUTPUT}") + string(REGEX REPLACE " +0 Warning\\(s\\)" "" check_output "${check_output}") + # Filter out warnings caused by user flags. + string(REGEX REPLACE "[^\n]*warning:[^\n]*-Winvalid-command-line-argument[^\n]*" "" check_output "${check_output}") # If using the feature causes warnings, treat it as broken/unavailable. if(check_output MATCHES "[Ww]arning") set(CMake_HAVE_CXX_${FEATURE} OFF CACHE INTERNAL "TRY_COMPILE" FORCE) @@ -51,5 +54,4 @@ cm_check_cxx_feature(make_unique) if(CMake_HAVE_CXX_MAKE_UNIQUE) set(CMake_HAVE_CXX_UNIQUE_PTR 1) endif() -cm_check_cxx_feature(override) cm_check_cxx_feature(unique_ptr) diff --git a/Source/Checks/cm_cxx_override.cxx b/Source/Checks/cm_cxx_override.cxx deleted file mode 100644 index 5a33fbb..0000000 --- a/Source/Checks/cm_cxx_override.cxx +++ /dev/null @@ -1,24 +0,0 @@ -struct Foo -{ - Foo() {} - virtual ~Foo() {} - virtual int test() const = 0; -}; - -struct Bar : Foo -{ - Bar() {} - ~Bar() override {} - int test() const override { return 0; } -}; - -int test(Foo const& foo) -{ - return foo.test(); -} - -int main() -{ - Bar const bar; - return test(bar); -} diff --git a/Source/CursesDialog/cmCursesBoolWidget.h b/Source/CursesDialog/cmCursesBoolWidget.h index bd565cd..cdb9478 100644 --- a/Source/CursesDialog/cmCursesBoolWidget.h +++ b/Source/CursesDialog/cmCursesBoolWidget.h @@ -21,7 +21,7 @@ public: // Handle user input. Called by the container of this widget // when this widget has focus. Returns true if the input was // handled. - bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE; + bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) override; // Description: // Set/Get the value (on/off). diff --git a/Source/CursesDialog/cmCursesCacheEntryComposite.cxx b/Source/CursesDialog/cmCursesCacheEntryComposite.cxx index 8596281..e7ed097 100644 --- a/Source/CursesDialog/cmCursesCacheEntryComposite.cxx +++ b/Source/CursesDialog/cmCursesCacheEntryComposite.cxx @@ -72,9 +72,8 @@ cmCursesCacheEntryComposite::cmCursesCacheEntryComposite( this->Entry = ow; std::vector<std::string> options; cmSystemTools::ExpandListArgument(stringsProp, options); - for (std::vector<std::string>::iterator si = options.begin(); - si != options.end(); ++si) { - ow->AddOption(*si); + for (auto const& opt : options) { + ow->AddOption(opt); } ow->SetOption(value); } else { diff --git a/Source/CursesDialog/cmCursesDummyWidget.h b/Source/CursesDialog/cmCursesDummyWidget.h index b0c270c..c509ae7 100644 --- a/Source/CursesDialog/cmCursesDummyWidget.h +++ b/Source/CursesDialog/cmCursesDummyWidget.h @@ -21,7 +21,7 @@ public: // Handle user input. Called by the container of this widget // when this widget has focus. Returns true if the input was // handled. - bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE; + bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) override; }; #endif // cmCursesDummyWidget_h diff --git a/Source/CursesDialog/cmCursesLabelWidget.h b/Source/CursesDialog/cmCursesLabelWidget.h index 79ae241..aab559b 100644 --- a/Source/CursesDialog/cmCursesLabelWidget.h +++ b/Source/CursesDialog/cmCursesLabelWidget.h @@ -19,13 +19,13 @@ class cmCursesLabelWidget : public cmCursesWidget public: cmCursesLabelWidget(int width, int height, int left, int top, const std::string& name); - ~cmCursesLabelWidget() CM_OVERRIDE; + ~cmCursesLabelWidget() override; // Description: // Handle user input. Called by the container of this widget // when this widget has focus. Returns true if the input was // handled - bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE; + bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) override; }; #endif // cmCursesLabelWidget_h diff --git a/Source/CursesDialog/cmCursesLongMessageForm.h b/Source/CursesDialog/cmCursesLongMessageForm.h index 099c722..2bcc15a 100644 --- a/Source/CursesDialog/cmCursesLongMessageForm.h +++ b/Source/CursesDialog/cmCursesLongMessageForm.h @@ -18,16 +18,16 @@ class cmCursesLongMessageForm : public cmCursesForm public: cmCursesLongMessageForm(std::vector<std::string> const& messages, const char* title); - ~cmCursesLongMessageForm() CM_OVERRIDE; + ~cmCursesLongMessageForm() override; // Description: // Handle user input. - void HandleInput() CM_OVERRIDE; + void HandleInput() override; // Description: // Display form. Use a window of size width x height, starting // at top, left. - void Render(int left, int top, int width, int height) CM_OVERRIDE; + void Render(int left, int top, int width, int height) override; // Description: // This method should normally called only by the form. @@ -37,7 +37,7 @@ public: // Description: // This method should normally called only by the form. // The only exception is during a resize. - void UpdateStatusBar() CM_OVERRIDE; + void UpdateStatusBar() override; protected: std::string Messages; diff --git a/Source/CursesDialog/cmCursesMainForm.cxx b/Source/CursesDialog/cmCursesMainForm.cxx index f79e72a..dbd024d 100644 --- a/Source/CursesDialog/cmCursesMainForm.cxx +++ b/Source/CursesDialog/cmCursesMainForm.cxx @@ -17,6 +17,7 @@ #include "cmVersion.h" #include "cmake.h" +#include <algorithm> #include <stdio.h> #include <string.h> @@ -353,11 +354,9 @@ void cmCursesMainForm::PrintKeys(int process /* = 0 */) char secondLine[512] = ""; char thirdLine[512] = ""; if (process) { - const char* clearLine = - " "; - strcpy(firstLine, clearLine); - strcpy(secondLine, clearLine); - strcpy(thirdLine, clearLine); + memset(firstLine, ' ', 68); + memset(secondLine, ' ', 68); + memset(thirdLine, ' ', 68); } else { if (this->OkToGenerate) { sprintf(firstLine, @@ -380,7 +379,7 @@ void cmCursesMainForm::PrintKeys(int process /* = 0 */) char fmt[512] = "Press [enter] to edit option Press [d] to delete an entry"; if (process) { - strcpy(fmt, " "); + memset(fmt, ' ', 27); } printw(fmt_s, fmt); curses_move(y - 3, 0); @@ -456,41 +455,27 @@ void cmCursesMainForm::UpdateStatusBar(const char* message) // Join the key, help string and pad with spaces // (or truncate) as necessary char bar[cmCursesMainForm::MAX_WIDTH]; - size_t i, curFieldLen = strlen(curField); + size_t curFieldLen = strlen(curField); size_t helpLen = strlen(help); - size_t width; - if (x < cmCursesMainForm::MAX_WIDTH) { - width = x; - } else { - width = cmCursesMainForm::MAX_WIDTH; - } + size_t width = std::min<size_t>(x, cmCursesMainForm::MAX_WIDTH); if (message) { curField = message; curFieldLen = strlen(message); + strncpy(bar, curField, width); if (curFieldLen < width) { - strcpy(bar, curField); - for (i = curFieldLen; i < width; ++i) { - bar[i] = ' '; - } - } else { - strncpy(bar, curField, width); + memset(bar + curFieldLen, ' ', width - curFieldLen); } } else { - if (curFieldLen >= width) { - strncpy(bar, curField, width); - } else { - strcpy(bar, curField); + strncpy(bar, curField, width); + if (curFieldLen < width) { bar[curFieldLen] = ':'; bar[curFieldLen + 1] = ' '; - if (curFieldLen + helpLen + 2 >= width) { - strncpy(bar + curFieldLen + 2, help, width - curFieldLen - 2); - } else { - strcpy(bar + curFieldLen + 2, help); - for (i = curFieldLen + helpLen + 2; i < width; ++i) { - bar[i] = ' '; - } + strncpy(bar + curFieldLen + 2, help, width - curFieldLen - 2); + if (curFieldLen + helpLen + 2 < width) { + memset(bar + curFieldLen + helpLen + 2, ' ', + width - curFieldLen + helpLen + 2); } } } @@ -503,9 +488,7 @@ void cmCursesMainForm::UpdateStatusBar(const char* message) char vertmp[128]; sprintf(vertmp, "CMake Version %s", cmVersion::GetCMakeVersion()); size_t sideSpace = (width - strlen(vertmp)); - for (i = 0; i < sideSpace; i++) { - version[i] = ' '; - } + memset(version, ' ', sideSpace); sprintf(version + sideSpace, "%s", vertmp); version[width] = '\0'; diff --git a/Source/CursesDialog/cmCursesMainForm.h b/Source/CursesDialog/cmCursesMainForm.h index 96dd5c0..7f5b3ca 100644 --- a/Source/CursesDialog/cmCursesMainForm.h +++ b/Source/CursesDialog/cmCursesMainForm.h @@ -27,7 +27,7 @@ class cmCursesMainForm : public cmCursesForm public: cmCursesMainForm(std::vector<std::string> const& args, int initwidth); - ~cmCursesMainForm() CM_OVERRIDE; + ~cmCursesMainForm() override; /** * Set the widgets which represent the cache entries. @@ -37,13 +37,13 @@ public: /** * Handle user input. */ - void HandleInput() CM_OVERRIDE; + void HandleInput() override; /** * Display form. Use a window of size width x height, starting * at top, left. */ - void Render(int left, int top, int width, int height) CM_OVERRIDE; + void Render(int left, int top, int width, int height) override; /** * Returns true if an entry with the given key is in the @@ -64,7 +64,7 @@ public: * exception is during a resize. The optional argument specifies the * string to be displayed in the status bar. */ - void UpdateStatusBar() CM_OVERRIDE { this->UpdateStatusBar(nullptr); } + void UpdateStatusBar() override { this->UpdateStatusBar(nullptr); } virtual void UpdateStatusBar(const char* message); /** @@ -80,7 +80,7 @@ public: * During a CMake run, an error handle should add errors * to be displayed afterwards. */ - void AddError(const char* message, const char* title) CM_OVERRIDE; + void AddError(const char* message, const char* title) override; /** * Used to do a configure. If argument is specified, it does only the check diff --git a/Source/CursesDialog/cmCursesOptionsWidget.cxx b/Source/CursesDialog/cmCursesOptionsWidget.cxx index d26a98f..a8c4933 100644 --- a/Source/CursesDialog/cmCursesOptionsWidget.cxx +++ b/Source/CursesDialog/cmCursesOptionsWidget.cxx @@ -75,9 +75,8 @@ void cmCursesOptionsWidget::SetOption(const std::string& value) this->CurrentOption = 0; // default to 0 index this->SetValue(value); int index = 0; - for (std::vector<std::string>::iterator i = this->Options.begin(); - i != this->Options.end(); ++i) { - if (*i == value) { + for (auto const& opt : this->Options) { + if (opt == value) { this->CurrentOption = index; } index++; diff --git a/Source/CursesDialog/cmCursesOptionsWidget.h b/Source/CursesDialog/cmCursesOptionsWidget.h index 86a6946..3e50e2d 100644 --- a/Source/CursesDialog/cmCursesOptionsWidget.h +++ b/Source/CursesDialog/cmCursesOptionsWidget.h @@ -24,7 +24,7 @@ public: // Handle user input. Called by the container of this widget // when this widget has focus. Returns true if the input was // handled. - bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE; + bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) override; void SetOption(const std::string&); void AddOption(std::string const&); void NextOption(); diff --git a/Source/CursesDialog/cmCursesPathWidget.h b/Source/CursesDialog/cmCursesPathWidget.h index 6a72402..bfa0ea3 100644 --- a/Source/CursesDialog/cmCursesPathWidget.h +++ b/Source/CursesDialog/cmCursesPathWidget.h @@ -23,9 +23,9 @@ public: * This method is called when different keys are pressed. The * subclass can have a special implementation handler for this. */ - void OnTab(cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE; - void OnReturn(cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE; - void OnType(int& key, cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE; + void OnTab(cmCursesMainForm* fm, WINDOW* w) override; + void OnReturn(cmCursesMainForm* fm, WINDOW* w) override; + void OnType(int& key, cmCursesMainForm* fm, WINDOW* w) override; protected: std::string LastString; diff --git a/Source/CursesDialog/cmCursesStringWidget.cxx b/Source/CursesDialog/cmCursesStringWidget.cxx index 8cb9c1f..5e2a329 100644 --- a/Source/CursesDialog/cmCursesStringWidget.cxx +++ b/Source/CursesDialog/cmCursesStringWidget.cxx @@ -188,9 +188,7 @@ bool cmCursesStringWidget::PrintKeys() char fmt_s[] = "%s"; char firstLine[512]; // Clean the toolbar - for (int i = 0; i < 512; i++) { - firstLine[i] = ' '; - } + memset(firstLine, ' ', sizeof(firstLine)); firstLine[511] = '\0'; curses_move(y - 4, 0); printw(fmt_s, firstLine); diff --git a/Source/CursesDialog/cmCursesStringWidget.h b/Source/CursesDialog/cmCursesStringWidget.h index 5787098..90310f6 100644 --- a/Source/CursesDialog/cmCursesStringWidget.h +++ b/Source/CursesDialog/cmCursesStringWidget.h @@ -30,14 +30,14 @@ public: * when this widget has focus. Returns true if the input was * handled. */ - bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE; + bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) override; /** * Set/Get the string. */ void SetString(const std::string& value); const char* GetString(); - const char* GetValue() CM_OVERRIDE; + const char* GetValue() override; /** * Set/Get InEdit flag. Can be used to tell the widget to leave @@ -59,7 +59,7 @@ public: * in the toolbar and return true. Otherwise, return false * and the parent widget will print. */ - bool PrintKeys() CM_OVERRIDE; + bool PrintKeys() override; protected: // true if the widget is in edit mode diff --git a/Source/LexerParser/cmListFileLexer.c b/Source/LexerParser/cmListFileLexer.c index 636a6fb..c6f524c 100644 --- a/Source/LexerParser/cmListFileLexer.c +++ b/Source/LexerParser/cmListFileLexer.c @@ -576,16 +576,16 @@ struct yy_trans_info flex_int32_t yy_verify; flex_int32_t yy_nxt; }; -static const flex_int16_t yy_accept[77] = +static const flex_int16_t yy_accept[81] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 25, 13, 22, 1, 16, 3, 13, 5, 6, 7, - 15, 23, 17, 19, 20, 21, 10, 11, 8, 12, - 9, 4, 13, 0, 13, 0, 22, 0, 0, 7, - 13, 0, 13, 0, 2, 0, 13, 17, 0, 18, - 10, 8, 4, 0, 14, 0, 0, 0, 0, 14, - 0, 0, 14, 0, 0, 0, 2, 14, 0, 0, - 0, 0, 0, 0, 0, 0 + 15, 23, 23, 17, 19, 20, 21, 17, 10, 11, + 8, 10, 12, 9, 24, 4, 13, 0, 13, 0, + 22, 0, 0, 7, 13, 0, 13, 0, 2, 0, + 13, 17, 0, 18, 10, 8, 4, 0, 14, 0, + 0, 0, 0, 14, 0, 0, 14, 0, 0, 0, + 2, 14, 0, 0, 0, 0, 0, 0, 0, 0 } ; static const YY_CHAR yy_ec[256] = @@ -620,104 +620,122 @@ static const YY_CHAR yy_ec[256] = 1, 1, 1, 1, 1 } ; -static const YY_CHAR yy_meta[16] = +static const YY_CHAR yy_meta[17] = { 0, 1, 1, 2, 3, 4, 3, 1, 3, 5, 6, - 1, 6, 1, 1, 7 + 1, 6, 1, 1, 7, 8 } ; -static const flex_int16_t yy_base[95] = +static const flex_int16_t yy_base[99] = { 0, - 0, 0, 13, 25, 14, 16, 17, 18, 90, 88, - 88, 39, 20, 237, 237, 74, 78, 237, 237, 13, - 54, 0, 71, 237, 237, 31, 0, 237, 73, 237, - 237, 0, 0, 65, 75, 0, 33, 30, 72, 0, - 0, 75, 70, 0, 74, 0, 0, 62, 70, 237, - 0, 63, 0, 85, 99, 65, 111, 62, 34, 0, - 54, 116, 0, 54, 127, 51, 237, 50, 0, 48, - 47, 39, 33, 29, 17, 237, 136, 143, 150, 157, - 164, 171, 178, 184, 191, 198, 201, 207, 214, 217, - 219, 225, 228, 230 + 0, 0, 14, 28, 42, 56, 70, 84, 18, 19, + 69, 100, 16, 323, 323, 55, 59, 323, 323, 13, + 115, 0, 323, 52, 323, 323, 21, 51, 0, 323, + 53, 0, 323, 323, 323, 0, 0, 126, 55, 0, + 25, 25, 53, 0, 0, 136, 53, 0, 57, 0, + 0, 42, 50, 323, 0, 43, 0, 146, 160, 45, + 172, 43, 26, 0, 42, 184, 0, 42, 195, 40, + 323, 40, 0, 38, 37, 34, 32, 31, 23, 323, + 211, 219, 227, 235, 243, 251, 259, 267, 274, 281, + 285, 291, 298, 302, 304, 310, 314, 316 } ; -static const flex_int16_t yy_def[95] = +static const flex_int16_t yy_def[99] = { 0, - 76, 1, 77, 77, 78, 78, 79, 79, 80, 80, - 76, 76, 76, 76, 76, 76, 12, 76, 76, 12, - 76, 81, 82, 76, 76, 82, 83, 76, 76, 76, - 76, 84, 12, 85, 12, 86, 76, 76, 87, 20, - 12, 88, 12, 21, 76, 89, 12, 82, 82, 76, - 83, 76, 84, 85, 76, 54, 85, 90, 76, 55, - 87, 88, 55, 62, 88, 91, 76, 55, 92, 93, - 90, 94, 91, 93, 94, 0, 76, 76, 76, 76, - 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, - 76, 76, 76, 76 + 80, 1, 81, 81, 82, 82, 83, 83, 84, 84, + 80, 80, 80, 80, 80, 80, 12, 80, 80, 12, + 80, 85, 80, 86, 80, 80, 86, 86, 87, 80, + 80, 87, 80, 80, 80, 88, 12, 89, 12, 90, + 80, 80, 91, 20, 12, 92, 12, 21, 80, 93, + 12, 86, 86, 80, 87, 80, 88, 89, 80, 58, + 89, 94, 80, 59, 91, 92, 59, 66, 92, 95, + 80, 59, 96, 97, 94, 98, 95, 97, 98, 0, + 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, + 80, 80, 80, 80, 80, 80, 80, 80 } ; -static const flex_int16_t yy_nxt[253] = +static const flex_int16_t yy_nxt[340] = { 0, 12, 13, 14, 13, 15, 16, 17, 18, 19, 12, - 12, 20, 21, 22, 12, 24, 28, 25, 28, 28, - 28, 37, 40, 37, 40, 62, 26, 24, 29, 25, - 29, 31, 31, 50, 37, 48, 37, 54, 26, 33, - 59, 63, 45, 34, 59, 35, 45, 62, 33, 33, - 33, 33, 36, 33, 41, 55, 54, 58, 42, 63, - 43, 72, 60, 41, 44, 41, 45, 46, 41, 55, - 55, 56, 70, 52, 48, 49, 67, 66, 57, 63, - 60, 64, 58, 52, 49, 39, 38, 76, 65, 55, - 14, 56, 14, 76, 76, 76, 76, 76, 57, 55, - - 76, 76, 76, 34, 76, 68, 76, 76, 55, 55, - 55, 55, 69, 55, 54, 76, 54, 76, 54, 54, - 63, 76, 64, 76, 76, 76, 76, 76, 76, 65, - 62, 76, 62, 76, 62, 62, 23, 23, 23, 23, - 23, 23, 23, 27, 27, 27, 27, 27, 27, 27, - 30, 30, 30, 30, 30, 30, 30, 32, 32, 32, - 32, 32, 32, 32, 47, 76, 47, 47, 47, 47, - 47, 48, 76, 48, 76, 48, 48, 48, 51, 76, - 51, 51, 51, 51, 53, 76, 53, 53, 53, 53, - 53, 54, 76, 76, 54, 76, 54, 54, 33, 76, - - 33, 33, 33, 33, 33, 61, 61, 62, 76, 76, - 62, 76, 62, 62, 41, 76, 41, 41, 41, 41, - 41, 71, 71, 73, 73, 55, 76, 55, 55, 55, - 55, 55, 74, 74, 75, 75, 11, 76, 76, 76, - 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, - 76, 76 + 12, 20, 21, 22, 12, 23, 25, 41, 26, 41, + 14, 14, 44, 54, 44, 52, 41, 27, 41, 28, + 25, 66, 26, 35, 35, 63, 63, 49, 49, 58, + 67, 27, 66, 28, 30, 59, 58, 62, 67, 76, + 64, 59, 74, 56, 52, 53, 31, 32, 30, 71, + 70, 64, 62, 56, 53, 53, 43, 42, 80, 80, + 31, 32, 30, 80, 80, 80, 80, 80, 80, 80, + 80, 80, 80, 80, 34, 35, 30, 80, 80, 80, + 80, 80, 80, 80, 80, 80, 80, 80, 34, 35, + + 37, 80, 80, 80, 38, 80, 39, 80, 80, 37, + 37, 37, 37, 40, 37, 45, 80, 80, 80, 46, + 80, 47, 80, 80, 45, 48, 45, 49, 50, 45, + 59, 80, 60, 80, 80, 80, 80, 80, 80, 61, + 67, 80, 68, 80, 80, 80, 80, 80, 80, 69, + 59, 80, 60, 80, 80, 80, 80, 80, 80, 61, + 59, 80, 80, 80, 38, 80, 72, 80, 80, 59, + 59, 59, 59, 73, 59, 58, 80, 58, 80, 58, + 58, 80, 80, 80, 80, 80, 80, 58, 67, 80, + 68, 80, 80, 80, 80, 80, 80, 69, 66, 80, + + 66, 80, 66, 66, 80, 80, 80, 80, 80, 80, + 66, 24, 24, 24, 24, 24, 24, 24, 24, 29, + 29, 29, 29, 29, 29, 29, 29, 33, 33, 33, + 33, 33, 33, 33, 33, 36, 36, 36, 36, 36, + 36, 36, 36, 51, 80, 51, 51, 51, 51, 51, + 51, 52, 80, 52, 80, 52, 52, 52, 52, 55, + 80, 55, 55, 55, 55, 80, 55, 57, 80, 57, + 57, 57, 57, 57, 58, 80, 80, 58, 80, 58, + 58, 37, 80, 37, 37, 37, 37, 37, 37, 65, + 65, 66, 80, 80, 66, 80, 66, 66, 45, 80, + + 45, 45, 45, 45, 45, 45, 75, 75, 77, 77, + 59, 80, 59, 59, 59, 59, 59, 59, 78, 78, + 79, 79, 11, 80, 80, 80, 80, 80, 80, 80, + 80, 80, 80, 80, 80, 80, 80, 80, 80 } ; -static const flex_int16_t yy_chk[253] = +static const flex_int16_t yy_chk[340] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 3, 5, 3, 6, 7, - 8, 13, 20, 13, 20, 75, 3, 4, 5, 4, - 6, 7, 8, 26, 37, 26, 37, 74, 4, 12, - 38, 73, 38, 12, 59, 12, 59, 72, 12, 12, - 12, 12, 12, 12, 21, 71, 70, 68, 21, 66, - 21, 64, 61, 21, 21, 21, 21, 21, 21, 34, - 58, 34, 56, 52, 49, 48, 45, 43, 34, 42, - 39, 42, 35, 29, 23, 17, 16, 11, 42, 54, - 10, 54, 9, 0, 0, 0, 0, 0, 54, 55, - - 0, 0, 0, 55, 0, 55, 0, 0, 55, 55, - 55, 55, 55, 55, 57, 0, 57, 0, 57, 57, - 62, 0, 62, 0, 0, 0, 0, 0, 0, 62, - 65, 0, 65, 0, 65, 65, 77, 77, 77, 77, - 77, 77, 77, 78, 78, 78, 78, 78, 78, 78, - 79, 79, 79, 79, 79, 79, 79, 80, 80, 80, - 80, 80, 80, 80, 81, 0, 81, 81, 81, 81, - 81, 82, 0, 82, 0, 82, 82, 82, 83, 0, - 83, 83, 83, 83, 84, 0, 84, 84, 84, 84, - 84, 85, 0, 0, 85, 0, 85, 85, 86, 0, - - 86, 86, 86, 86, 86, 87, 87, 88, 0, 0, - 88, 0, 88, 88, 89, 0, 89, 89, 89, 89, - 89, 90, 90, 91, 91, 92, 0, 92, 92, 92, - 92, 92, 93, 93, 94, 94, 76, 76, 76, 76, - 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, - 76, 76 + 1, 1, 1, 1, 1, 1, 3, 13, 3, 13, + 9, 10, 20, 27, 20, 27, 41, 3, 41, 3, + 4, 79, 4, 9, 10, 42, 63, 42, 63, 78, + 77, 4, 76, 4, 5, 75, 74, 72, 70, 68, + 65, 62, 60, 56, 53, 52, 5, 5, 6, 49, + 47, 43, 39, 31, 28, 24, 17, 16, 11, 0, + 6, 6, 7, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 7, 7, 8, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, + + 12, 0, 0, 0, 12, 0, 12, 0, 0, 12, + 12, 12, 12, 12, 12, 21, 0, 0, 0, 21, + 0, 21, 0, 0, 21, 21, 21, 21, 21, 21, + 38, 0, 38, 0, 0, 0, 0, 0, 0, 38, + 46, 0, 46, 0, 0, 0, 0, 0, 0, 46, + 58, 0, 58, 0, 0, 0, 0, 0, 0, 58, + 59, 0, 0, 0, 59, 0, 59, 0, 0, 59, + 59, 59, 59, 59, 59, 61, 0, 61, 0, 61, + 61, 0, 0, 0, 0, 0, 0, 61, 66, 0, + 66, 0, 0, 0, 0, 0, 0, 66, 69, 0, + + 69, 0, 69, 69, 0, 0, 0, 0, 0, 0, + 69, 81, 81, 81, 81, 81, 81, 81, 81, 82, + 82, 82, 82, 82, 82, 82, 82, 83, 83, 83, + 83, 83, 83, 83, 83, 84, 84, 84, 84, 84, + 84, 84, 84, 85, 0, 85, 85, 85, 85, 85, + 85, 86, 0, 86, 0, 86, 86, 86, 86, 87, + 0, 87, 87, 87, 87, 0, 87, 88, 0, 88, + 88, 88, 88, 88, 89, 0, 0, 89, 0, 89, + 89, 90, 0, 90, 90, 90, 90, 90, 90, 91, + 91, 92, 0, 0, 92, 0, 92, 92, 93, 0, + + 93, 93, 93, 93, 93, 93, 94, 94, 95, 95, + 96, 0, 96, 96, 96, 96, 96, 96, 97, 97, + 98, 98, 80, 80, 80, 80, 80, 80, 80, 80, + 80, 80, 80, 80, 80, 80, 80, 80, 80 } ; /* Table of booleans, true if rule could match eol. */ @@ -1075,13 +1093,13 @@ yy_match: while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 77 ) + if ( yy_current_state >= 81 ) yy_c = yy_meta[yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; ++yy_cp; } - while ( yy_base[yy_current_state] != 237 ); + while ( yy_base[yy_current_state] != 323 ); yy_find_action: yy_act = yy_accept[yy_current_state]; @@ -1647,7 +1665,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner) for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { - YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); + YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 16); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; @@ -1656,7 +1674,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner) while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 77 ) + if ( yy_current_state >= 81 ) yy_c = yy_meta[yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; @@ -1676,7 +1694,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner) struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ char *yy_cp = yyg->yy_c_buf_p; - YY_CHAR yy_c = 1; + YY_CHAR yy_c = 16; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; @@ -1685,11 +1703,11 @@ static int yy_get_next_buffer (yyscan_t yyscanner) while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 77 ) + if ( yy_current_state >= 81 ) yy_c = yy_meta[yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; - yy_is_jam = (yy_current_state == 76); + yy_is_jam = (yy_current_state == 80); (void)yyg; return yy_is_jam ? 0 : yy_current_state; diff --git a/Source/LexerParser/cmListFileLexer.in.l b/Source/LexerParser/cmListFileLexer.in.l index 6ec8da4..f2fd538 100644 --- a/Source/LexerParser/cmListFileLexer.in.l +++ b/Source/LexerParser/cmListFileLexer.in.l @@ -74,7 +74,7 @@ static void cmListFileLexerDestroy(cmListFileLexer* lexer); %x COMMENT MAKEVAR \$\([A-Za-z0-9_]*\) -UNQUOTED ([^ \t\r\n\(\)#\\\"[=]|\\.) +UNQUOTED ([^ \0\t\r\n\(\)#\\\"[=]|\\.) LEGACY {MAKEVAR}|{UNQUOTED}|\"({MAKEVAR}|{UNQUOTED}|[ \t[=])*\" %% @@ -113,7 +113,7 @@ LEGACY {MAKEVAR}|{UNQUOTED}|\"({MAKEVAR}|{UNQUOTED}|[ \t[=])*\" BEGIN(COMMENT); } -<COMMENT>.* { +<COMMENT>[^\0\n]* { lexer->column += yyleng; } @@ -168,7 +168,7 @@ LEGACY {MAKEVAR}|{UNQUOTED}|\"({MAKEVAR}|{UNQUOTED}|[ \t[=])*\" BEGIN(BRACKET); } -<BRACKET,BRACKETEND>. { +<BRACKET,BRACKETEND>[^\0\n] { cmListFileLexerAppend(lexer, yytext, yyleng); lexer->column += yyleng; BEGIN(BRACKET); @@ -231,7 +231,7 @@ LEGACY {MAKEVAR}|{UNQUOTED}|\"({MAKEVAR}|{UNQUOTED}|[ \t[=])*\" return 1; } -<STRING>. { +<STRING>[^\0\n] { cmListFileLexerAppend(lexer, yytext, yyleng); lexer->column += yyleng; } diff --git a/Source/QtDialog/CMakeSetup.cxx b/Source/QtDialog/CMakeSetup.cxx index 9f881e2..ca0b015 100644 --- a/Source/QtDialog/CMakeSetup.cxx +++ b/Source/QtDialog/CMakeSetup.cxx @@ -92,6 +92,10 @@ int main(int argc, char** argv) cmAddPluginPath(); #endif +#if QT_VERSION >= 0x050600 + QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); +#endif + QApplication app(argc, argv); setlocale(LC_NUMERIC, "C"); diff --git a/Source/QtDialog/QCMakeCacheView.cxx b/Source/QtDialog/QCMakeCacheView.cxx index c6b007d..1b3fb15 100644 --- a/Source/QtDialog/QCMakeCacheView.cxx +++ b/Source/QtDialog/QCMakeCacheView.cxx @@ -23,7 +23,7 @@ public: } protected: - bool filterAcceptsRow(int row, const QModelIndex& p) const CM_OVERRIDE + bool filterAcceptsRow(int row, const QModelIndex& p) const override { QStringList strs; const QAbstractItemModel* m = this->sourceModel(); @@ -77,7 +77,7 @@ public: protected: bool ShowAdvanced; - bool filterAcceptsRow(int row, const QModelIndex& p) const CM_OVERRIDE + bool filterAcceptsRow(int row, const QModelIndex& p) const override { const QAbstractItemModel* m = this->sourceModel(); QModelIndex idx = m->index(row, 0, p); diff --git a/Source/bindexplib.cxx b/Source/bindexplib.cxx index e96226a..2eb47f3 100644 --- a/Source/bindexplib.cxx +++ b/Source/bindexplib.cxx @@ -218,7 +218,7 @@ public: * The name of the Function entry points */ if (pSymbolTable->N.Name.Short != 0) { - symbol = ""; + symbol.clear(); symbol.insert(0, (const char*)pSymbolTable->N.ShortName, 8); } else { symbol = stringTable + pSymbolTable->N.Name.Long; @@ -394,12 +394,10 @@ bool bindexplib::AddDefinitionFile(const char* filename) void bindexplib::WriteFile(FILE* file) { fprintf(file, "EXPORTS \n"); - for (std::set<std::string>::const_iterator i = this->DataSymbols.begin(); - i != this->DataSymbols.end(); ++i) { - fprintf(file, "\t%s \t DATA\n", i->c_str()); + for (std::string const& ds : this->DataSymbols) { + fprintf(file, "\t%s \t DATA\n", ds.c_str()); } - for (std::set<std::string>::const_iterator i = this->Symbols.begin(); - i != this->Symbols.end(); ++i) { - fprintf(file, "\t%s\n", i->c_str()); + for (std::string const& s : this->Symbols) { + fprintf(file, "\t%s\n", s.c_str()); } } diff --git a/Source/cmAddCompileOptionsCommand.cxx b/Source/cmAddCompileOptionsCommand.cxx index 21a8012..c37fd9a 100644 --- a/Source/cmAddCompileOptionsCommand.cxx +++ b/Source/cmAddCompileOptionsCommand.cxx @@ -13,9 +13,8 @@ bool cmAddCompileOptionsCommand::InitialPass( return true; } - for (std::vector<std::string>::const_iterator i = args.begin(); - i != args.end(); ++i) { - this->Makefile->AddCompileOption(i->c_str()); + for (std::string const& i : args) { + this->Makefile->AddCompileOption(i.c_str()); } return true; } diff --git a/Source/cmAddCompileOptionsCommand.h b/Source/cmAddCompileOptionsCommand.h index 7eac314..3d53d09 100644 --- a/Source/cmAddCompileOptionsCommand.h +++ b/Source/cmAddCompileOptionsCommand.h @@ -18,14 +18,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmAddCompileOptionsCommand; } + cmCommand* Clone() override { return new cmAddCompileOptionsCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmAddCustomCommandCommand.cxx b/Source/cmAddCustomCommandCommand.cxx index bd054e8..7fed52d 100644 --- a/Source/cmAddCustomCommandCommand.cxx +++ b/Source/cmAddCustomCommandCommand.cxx @@ -68,9 +68,7 @@ bool cmAddCustomCommandCommand::InitialPass( tdoing doing = doing_nothing; - for (unsigned int j = 0; j < args.size(); ++j) { - std::string const& copy = args[j]; - + for (std::string const& copy : args) { if (copy == "SOURCE") { doing = doing_source; } else if (copy == "COMMAND") { @@ -355,12 +353,11 @@ bool cmAddCustomCommandCommand::InitialPass( bool cmAddCustomCommandCommand::CheckOutputs( const std::vector<std::string>& outputs) { - for (std::vector<std::string>::const_iterator o = outputs.begin(); - o != outputs.end(); ++o) { + for (std::string const& o : outputs) { // Make sure the file will not be generated into the source // directory during an out of source build. - if (!this->Makefile->CanIWriteThisFile(o->c_str())) { - std::string e = "attempted to have a file \"" + *o + + if (!this->Makefile->CanIWriteThisFile(o.c_str())) { + std::string e = "attempted to have a file \"" + o + "\" in a source directory as an output of custom command."; this->SetError(e); cmSystemTools::SetFatalErrorOccured(); @@ -368,10 +365,10 @@ bool cmAddCustomCommandCommand::CheckOutputs( } // Make sure the output file name has no invalid characters. - std::string::size_type pos = o->find_first_of("#<>"); + std::string::size_type pos = o.find_first_of("#<>"); if (pos != std::string::npos) { std::ostringstream msg; - msg << "called with OUTPUT containing a \"" << (*o)[pos] + msg << "called with OUTPUT containing a \"" << o[pos] << "\". This character is not allowed."; this->SetError(msg.str()); return false; diff --git a/Source/cmAddCustomCommandCommand.h b/Source/cmAddCustomCommandCommand.h index 95c58d9..6af4f10 100644 --- a/Source/cmAddCustomCommandCommand.h +++ b/Source/cmAddCustomCommandCommand.h @@ -24,14 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmAddCustomCommandCommand; } + cmCommand* Clone() override { return new cmAddCustomCommandCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; protected: bool CheckOutputs(const std::vector<std::string>& outputs); diff --git a/Source/cmAddCustomTargetCommand.h b/Source/cmAddCustomTargetCommand.h index 8d9d09f..1a55116 100644 --- a/Source/cmAddCustomTargetCommand.h +++ b/Source/cmAddCustomTargetCommand.h @@ -25,14 +25,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmAddCustomTargetCommand; } + cmCommand* Clone() override { return new cmAddCustomTargetCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmAddDefinitionsCommand.cxx b/Source/cmAddDefinitionsCommand.cxx index 9e0607c..261fb5b 100644 --- a/Source/cmAddDefinitionsCommand.cxx +++ b/Source/cmAddDefinitionsCommand.cxx @@ -15,9 +15,8 @@ bool cmAddDefinitionsCommand::InitialPass(std::vector<std::string> const& args, return true; } - for (std::vector<std::string>::const_iterator i = args.begin(); - i != args.end(); ++i) { - this->Makefile->AddDefineFlag(i->c_str()); + for (std::string const& i : args) { + this->Makefile->AddDefineFlag(i.c_str()); } return true; } diff --git a/Source/cmAddDefinitionsCommand.h b/Source/cmAddDefinitionsCommand.h index a58d430..7b75638 100644 --- a/Source/cmAddDefinitionsCommand.h +++ b/Source/cmAddDefinitionsCommand.h @@ -24,14 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmAddDefinitionsCommand; } + cmCommand* Clone() override { return new cmAddDefinitionsCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmAddDependenciesCommand.h b/Source/cmAddDependenciesCommand.h index 10f3c57..e10df71 100644 --- a/Source/cmAddDependenciesCommand.h +++ b/Source/cmAddDependenciesCommand.h @@ -23,14 +23,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmAddDependenciesCommand; } + cmCommand* Clone() override { return new cmAddDependenciesCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmAddExecutableCommand.h b/Source/cmAddExecutableCommand.h index 570b35f..bdf607d 100644 --- a/Source/cmAddExecutableCommand.h +++ b/Source/cmAddExecutableCommand.h @@ -24,14 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmAddExecutableCommand; } + cmCommand* Clone() override { return new cmAddExecutableCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmAddLibraryCommand.h b/Source/cmAddLibraryCommand.h index 1656312..aa21261 100644 --- a/Source/cmAddLibraryCommand.h +++ b/Source/cmAddLibraryCommand.h @@ -24,14 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmAddLibraryCommand; } + cmCommand* Clone() override { return new cmAddLibraryCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmAddSubDirectoryCommand.h b/Source/cmAddSubDirectoryCommand.h index a6c92a8..0ea4423 100644 --- a/Source/cmAddSubDirectoryCommand.h +++ b/Source/cmAddSubDirectoryCommand.h @@ -25,14 +25,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmAddSubDirectoryCommand; } + cmCommand* Clone() override { return new cmAddSubDirectoryCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmAddTestCommand.h b/Source/cmAddTestCommand.h index a296904..bea3f3d 100644 --- a/Source/cmAddTestCommand.h +++ b/Source/cmAddTestCommand.h @@ -23,14 +23,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmAddTestCommand; } + cmCommand* Clone() override { return new cmAddTestCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: bool HandleNameMode(std::vector<std::string> const& args); diff --git a/Source/cmAlgorithms.h b/Source/cmAlgorithms.h index a4f66a9..69d0ed6 100644 --- a/Source/cmAlgorithms.h +++ b/Source/cmAlgorithms.h @@ -120,7 +120,7 @@ struct cmIsPair }; template <typename K, typename V> -struct cmIsPair<std::pair<K, V> > +struct cmIsPair<std::pair<K, V>> { enum { @@ -370,8 +370,7 @@ std::string cmWrap(char prefix, Range const& r, char suffix, template <typename Range, typename T> typename Range::const_iterator cmFindNot(Range const& r, T const& t) { - return std::find_if(r.begin(), r.end(), - std::bind1st(std::not_equal_to<T>(), t)); + return std::find_if(r.begin(), r.end(), [&t](T const& i) { return i != t; }); } template <typename Range> diff --git a/Source/cmAuxSourceDirectoryCommand.h b/Source/cmAuxSourceDirectoryCommand.h index ea22855..3742e3e 100644 --- a/Source/cmAuxSourceDirectoryCommand.h +++ b/Source/cmAuxSourceDirectoryCommand.h @@ -27,14 +27,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmAuxSourceDirectoryCommand; } + cmCommand* Clone() override { return new cmAuxSourceDirectoryCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmBreakCommand.h b/Source/cmBreakCommand.h index c0a5e11..3b18567 100644 --- a/Source/cmBreakCommand.h +++ b/Source/cmBreakCommand.h @@ -23,14 +23,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmBreakCommand; } + cmCommand* Clone() override { return new cmBreakCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmBuildCommand.h b/Source/cmBuildCommand.h index 17e9636..e0529a4 100644 --- a/Source/cmBuildCommand.h +++ b/Source/cmBuildCommand.h @@ -23,14 +23,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmBuildCommand; } + cmCommand* Clone() override { return new cmBuildCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; /** * The primary command signature with optional, KEYWORD-based args. diff --git a/Source/cmBuildNameCommand.cxx b/Source/cmBuildNameCommand.cxx index 9d2c0c6..5f54338 100644 --- a/Source/cmBuildNameCommand.cxx +++ b/Source/cmBuildNameCommand.cxx @@ -36,7 +36,7 @@ bool cmBuildNameCommand::InitialPass(std::vector<std::string> const& args, std::string buildname = "WinNT"; if (this->Makefile->GetDefinition("UNIX")) { - buildname = ""; + buildname.clear(); cmSystemTools::RunSingleCommand("uname -a", &buildname, &buildname); if (!buildname.empty()) { std::string RegExp = "([^ ]*) [^ ]* ([^ ]*) "; diff --git a/Source/cmBuildNameCommand.h b/Source/cmBuildNameCommand.h index e3d2f2a..4bb72d1 100644 --- a/Source/cmBuildNameCommand.h +++ b/Source/cmBuildNameCommand.h @@ -15,9 +15,9 @@ class cmExecutionStatus; class cmBuildNameCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE { return new cmBuildNameCommand; } + cmCommand* Clone() override { return new cmBuildNameCommand; } bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmCLocaleEnvironmentScope.cxx b/Source/cmCLocaleEnvironmentScope.cxx index 28e8f2e..737e3ea 100644 --- a/Source/cmCLocaleEnvironmentScope.cxx +++ b/Source/cmCLocaleEnvironmentScope.cxx @@ -45,10 +45,9 @@ void cmCLocaleEnvironmentScope::SetEnv(std::string const& key, cmCLocaleEnvironmentScope::~cmCLocaleEnvironmentScope() { - for (backup_map_t::const_iterator i = this->EnvironmentBackup.begin(); - i != this->EnvironmentBackup.end(); ++i) { + for (auto const& envb : this->EnvironmentBackup) { std::ostringstream tmp; - tmp << i->first << "=" << i->second; + tmp << envb.first << "=" << envb.second; cmSystemTools::PutEnv(tmp.str()); } } diff --git a/Source/cmCMakeHostSystemInformationCommand.h b/Source/cmCMakeHostSystemInformationCommand.h index b3c05d4..bfff8f1 100644 --- a/Source/cmCMakeHostSystemInformationCommand.h +++ b/Source/cmCMakeHostSystemInformationCommand.h @@ -28,7 +28,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { return new cmCMakeHostSystemInformationCommand; } @@ -38,7 +38,7 @@ public: * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: bool GetValue(cmsys::SystemInformation& info, std::string const& key, diff --git a/Source/cmCMakeMinimumRequired.cxx b/Source/cmCMakeMinimumRequired.cxx index 942688c..bcc41fc 100644 --- a/Source/cmCMakeMinimumRequired.cxx +++ b/Source/cmCMakeMinimumRequired.cxx @@ -19,10 +19,10 @@ bool cmCMakeMinimumRequired::InitialPass(std::vector<std::string> const& args, // Process arguments. std::string version_string; bool doing_version = false; - for (unsigned int i = 0; i < args.size(); ++i) { - if (args[i] == "VERSION") { + for (std::string const& arg : args) { + if (arg == "VERSION") { doing_version = true; - } else if (args[i] == "FATAL_ERROR") { + } else if (arg == "FATAL_ERROR") { if (doing_version) { this->SetError("called with no value for VERSION."); return false; @@ -30,9 +30,9 @@ bool cmCMakeMinimumRequired::InitialPass(std::vector<std::string> const& args, doing_version = false; } else if (doing_version) { doing_version = false; - version_string = args[i]; + version_string = arg; } else { - this->UnknownArguments.push_back(args[i]); + this->UnknownArguments.push_back(arg); } } if (doing_version) { diff --git a/Source/cmCMakeMinimumRequired.h b/Source/cmCMakeMinimumRequired.h index 4a979de..18d9460 100644 --- a/Source/cmCMakeMinimumRequired.h +++ b/Source/cmCMakeMinimumRequired.h @@ -23,14 +23,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmCMakeMinimumRequired; } + cmCommand* Clone() override { return new cmCMakeMinimumRequired; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: std::vector<std::string> UnknownArguments; diff --git a/Source/cmCMakePolicyCommand.h b/Source/cmCMakePolicyCommand.h index f9c51c3..b18576c 100644 --- a/Source/cmCMakePolicyCommand.h +++ b/Source/cmCMakePolicyCommand.h @@ -24,14 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmCMakePolicyCommand; } + cmCommand* Clone() override { return new cmCMakePolicyCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: bool HandleSetMode(std::vector<std::string> const& args); diff --git a/Source/cmCPackPropertiesGenerator.cxx b/Source/cmCPackPropertiesGenerator.cxx index 57a8b38..a33b824 100644 --- a/Source/cmCPackPropertiesGenerator.cxx +++ b/Source/cmCPackPropertiesGenerator.cxx @@ -6,7 +6,6 @@ #include <map> #include <ostream> -#include <utility> cmCPackPropertiesGenerator::cmCPackPropertiesGenerator( cmLocalGenerator* lg, cmInstalledFile const& installedFile, @@ -27,19 +26,17 @@ void cmCPackPropertiesGenerator::GenerateScriptForConfig( cmInstalledFile::PropertyMapType const& properties = this->InstalledFile.GetProperties(); - for (cmInstalledFile::PropertyMapType::const_iterator i = properties.begin(); - i != properties.end(); ++i) { - std::string const& name = i->first; - cmInstalledFile::Property const& property = i->second; + for (cmInstalledFile::PropertyMapType::value_type const& i : properties) { + std::string const& name = i.first; + cmInstalledFile::Property const& property = i.second; os << indent << "set_property(INSTALL " << cmOutputConverter::EscapeForCMake(expandedFileName) << " PROPERTY " << cmOutputConverter::EscapeForCMake(name); - for (cmInstalledFile::ExpressionVectorType::const_iterator j = - property.ValueExpressions.begin(); - j != property.ValueExpressions.end(); ++j) { - std::string value = (*j)->Evaluate(this->LG, config); + for (cmInstalledFile::ExpressionVectorType::value_type const& j : + property.ValueExpressions) { + std::string value = j->Evaluate(this->LG, config); os << " " << cmOutputConverter::EscapeForCMake(value); } diff --git a/Source/cmCPackPropertiesGenerator.h b/Source/cmCPackPropertiesGenerator.h index c5885f2..e580e04 100644 --- a/Source/cmCPackPropertiesGenerator.h +++ b/Source/cmCPackPropertiesGenerator.h @@ -29,7 +29,7 @@ public: protected: void GenerateScriptForConfig(std::ostream& os, const std::string& config, - Indent indent) CM_OVERRIDE; + Indent indent) override; cmLocalGenerator* LG; cmInstalledFile const& InstalledFile; diff --git a/Source/cmCPluginAPI.cxx b/Source/cmCPluginAPI.cxx index e0b1711..e1e11af 100644 --- a/Source/cmCPluginAPI.cxx +++ b/Source/cmCPluginAPI.cxx @@ -405,14 +405,8 @@ char CCONV* cmExpandVariablesInString(void* arg, const char* source, { cmMakefile* mf = static_cast<cmMakefile*>(arg); std::string barf = source; - std::string result = mf->ExpandVariablesInString( - barf, (escapeQuotes ? true : false), (atOnly ? true : false)); - char* res = static_cast<char*>(malloc(result.size() + 1)); - if (!result.empty()) { - strcpy(res, result.c_str()); - } - res[result.size()] = '\0'; - return res; + std::string result = mf->ExpandVariablesInString(barf, escapeQuotes, atOnly); + return strdup(result.c_str()); } int CCONV cmExecuteCommand(void* arg, const char* name, int numArgs, @@ -460,9 +454,7 @@ void CCONV cmFreeArguments(int argc, char** argv) for (i = 0; i < argc; ++i) { free(argv[i]); } - if (argv) { - free(argv); - } + free(argv); } int CCONV cmGetTotalArgumentSize(int argc, char** argv) @@ -504,8 +496,8 @@ public: typedef derived::value_type value_type; ~cmCPluginAPISourceFileMap() { - for (iterator i = this->begin(); i != this->end(); ++i) { - delete i->second; + for (auto const& i : *this) { + delete i.second; } } }; @@ -513,13 +505,12 @@ cmCPluginAPISourceFileMap cmCPluginAPISourceFiles; void* CCONV cmCreateSourceFile(void) { - return (void*)new cmCPluginAPISourceFile; + return new cmCPluginAPISourceFile; } void* CCONV cmCreateNewSourceFile(void*) { - cmCPluginAPISourceFile* sf = new cmCPluginAPISourceFile; - return (void*)sf; + return new cmCPluginAPISourceFile; } void CCONV cmDestroySourceFile(void* arg) @@ -552,7 +543,7 @@ void CCONV* cmGetSource(void* arg, const char* name) cmCPluginAPISourceFileMap::value_type entry(rsf, sf); i = cmCPluginAPISourceFiles.insert(entry).first; } - return (void*)i->second; + return i->second; } return nullptr; } @@ -568,9 +559,8 @@ void* CCONV cmAddSource(void* arg, void* arg2) // Create the real cmSourceFile instance and copy over saved information. cmSourceFile* rsf = mf->GetOrCreateSource(osf->FullPath); rsf->GetProperties() = osf->Properties; - for (std::vector<std::string>::iterator i = osf->Depends.begin(); - i != osf->Depends.end(); ++i) { - rsf->AddDepend(*i); + for (std::string const& d : osf->Depends) { + rsf->AddDepend(d); } // Create the proxy for the real source file. @@ -582,7 +572,7 @@ void* CCONV cmAddSource(void* arg, void* arg2) // Store the proxy in the map so it can be re-used and deleted later. cmCPluginAPISourceFiles[rsf] = sf; - return (void*)sf; + return sf; } const char* CCONV cmSourceFileGetSourceName(void* arg) @@ -763,25 +753,19 @@ void CCONV cmSourceFileSetName2(void* arg, const char* name, const char* dir, char* CCONV cmGetFilenameWithoutExtension(const char* name) { std::string sres = cmSystemTools::GetFilenameWithoutExtension(name); - char* result = (char*)malloc(sres.size() + 1); - strcpy(result, sres.c_str()); - return result; + return strdup(sres.c_str()); } char* CCONV cmGetFilenamePath(const char* name) { std::string sres = cmSystemTools::GetFilenamePath(name); - char* result = (char*)malloc(sres.size() + 1); - strcpy(result, sres.c_str()); - return result; + return strdup(sres.c_str()); } char* CCONV cmCapitalized(const char* name) { std::string sres = cmSystemTools::Capitalized(name); - char* result = (char*)malloc(sres.size() + 1); - strcpy(result, sres.c_str()); - return result; + return strdup(sres.c_str()); } void CCONV cmCopyFileIfDifferent(const char* name1, const char* name2) diff --git a/Source/cmCTest.cxx b/Source/cmCTest.cxx index 66b8f07..e248219 100644 --- a/Source/cmCTest.cxx +++ b/Source/cmCTest.cxx @@ -15,6 +15,7 @@ #include <ctype.h> #include <iostream> #include <map> +#include <memory> // IWYU pragma: keep #include <sstream> #include <stdio.h> #include <stdlib.h> @@ -50,7 +51,6 @@ #include "cmVersion.h" #include "cmVersionConfig.h" #include "cmXMLWriter.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" #if defined(__BEOS__) || defined(__HAIKU__) @@ -147,7 +147,7 @@ std::string cmCTest::CurrentTime() std::string cmCTest::GetCostDataFile() { std::string fname = this->GetCTestConfiguration("CostDataFile"); - if (fname == "") { + if (fname.empty()) { fname = this->GetBinaryDir() + "/Testing/Temporary/CTestCostData.txt"; } return fname; @@ -222,8 +222,7 @@ std::string cmCTest::MakeURLSafe(const std::string& str) { std::ostringstream ost; char buffer[10]; - for (std::string::size_type pos = 0; pos < str.size(); pos++) { - unsigned char ch = str[pos]; + for (unsigned char ch : str) { if ((ch > 126 || ch < 32 || ch == '&' || ch == '%' || ch == '+' || ch == '=' || ch == '@') && ch != 9) { @@ -282,9 +281,9 @@ cmCTest::cmCTest() this->GlobalTimeout = 0; this->LastStopTimeout = 24 * 60 * 60; this->CompressXMLFiles = false; - this->CTestConfigFile = ""; - this->ScheduleType = ""; - this->StopTime = ""; + this->CTestConfigFile.clear(); + this->ScheduleType.clear(); + this->StopTime.clear(); this->NextDayStopTime = false; this->OutputLogFile = nullptr; this->OutputLogFileLastTag = -1; @@ -331,10 +330,8 @@ cmCTest::cmCTest() this->TestingHandlers["submit"] = new cmCTestSubmitHandler; this->TestingHandlers["upload"] = new cmCTestUploadHandler; - cmCTest::t_TestingHandlers::iterator it; - for (it = this->TestingHandlers.begin(); it != this->TestingHandlers.end(); - ++it) { - it->second->SetCTestInstance(this); + for (auto& handler : this->TestingHandlers) { + handler.second->SetCTestInstance(this); } // Make sure we can capture the build tool output. @@ -424,9 +421,8 @@ int cmCTest::Initialize(const char* binary_dir, cmCTestStartCommand* command) cm.SetHomeOutputDirectory(""); cm.GetCurrentSnapshot().SetDefaultDefinitions(); cmGlobalGenerator gg(&cm); - CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot())); - if (!this->ReadCustomConfigurationFileTree(this->BinaryDir.c_str(), - mf.get())) { + cmMakefile mf(&gg, cm.GetCurrentSnapshot()); + if (!this->ReadCustomConfigurationFileTree(this->BinaryDir.c_str(), &mf)) { cmCTestOptionalLog( this, DEBUG, "Cannot find custom configuration file tree" << std::endl, quiet); @@ -480,7 +476,7 @@ int cmCTest::Initialize(const char* binary_dir, cmCTestStartCommand* command) &min); if (year != lctime->tm_year + 1900 || mon != lctime->tm_mon + 1 || day != lctime->tm_mday) { - tag = ""; + tag.clear(); } std::string tagmode; if (cmSystemTools::GetLineFromStream(tfin, tagmode)) { @@ -973,17 +969,18 @@ int cmCTest::RunMakeCommand(const char* command, std::string& output, } std::vector<const char*> argv; - for (std::vector<std::string>::const_iterator a = args.begin(); - a != args.end(); ++a) { - argv.push_back(a->c_str()); + for (std::string const& a : args) { + argv.push_back(a.c_str()); } argv.push_back(nullptr); - output = ""; + output.clear(); cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, "Run command:"); - std::vector<const char*>::iterator ait; - for (ait = argv.begin(); ait != argv.end() && *ait; ++ait) { - cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, " \"" << *ait << "\""); + for (char const* arg : argv) { + if (!arg) { + break; + } + cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, " \"" << arg << "\""); } cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, std::endl); @@ -1009,9 +1006,9 @@ int cmCTest::RunMakeCommand(const char* command, std::string& output, << " " << std::flush); while (cmsysProcess_WaitForData(cp, &data, &length, nullptr)) { processOutput.DecodeText(data, length, strdata); - for (size_t cc = 0; cc < strdata.size(); ++cc) { - if (strdata[cc] == 0) { - strdata[cc] = '\n'; + for (char& cc : strdata) { + if (cc == 0) { + cc = '\n'; } } output.append(strdata); @@ -1107,27 +1104,27 @@ int cmCTest::RunTest(std::vector<const char*> argv, std::string* output, inst.SetStreams(&oss, &oss); std::vector<std::string> args; - for (unsigned int i = 0; i < argv.size(); ++i) { - if (argv[i]) { + for (char const* i : argv) { + if (i) { // make sure we pass the timeout in for any build and test // invocations. Since --build-generator is required this is a // good place to check for it, and to add the arguments in - if (strcmp(argv[i], "--build-generator") == 0 && timeout > 0) { + if (strcmp(i, "--build-generator") == 0 && timeout > 0) { args.push_back("--test-timeout"); std::ostringstream msg; msg << timeout; args.push_back(msg.str()); } - args.push_back(argv[i]); + args.push_back(i); } } if (log) { *log << "* Run internal CTest" << std::endl; } - CM_AUTO_PTR<cmSystemTools::SaveRestoreEnvironment> saveEnv; + std::unique_ptr<cmSystemTools::SaveRestoreEnvironment> saveEnv; if (modifyEnv) { - saveEnv.reset(new cmSystemTools::SaveRestoreEnvironment); + saveEnv = cm::make_unique<cmSystemTools::SaveRestoreEnvironment>(); cmSystemTools::AppendEnv(*environment); } @@ -1149,12 +1146,12 @@ int cmCTest::RunTest(std::vector<const char*> argv, std::string* output, } std::vector<char> tempOutput; if (output) { - *output = ""; + output->clear(); } - CM_AUTO_PTR<cmSystemTools::SaveRestoreEnvironment> saveEnv; + std::unique_ptr<cmSystemTools::SaveRestoreEnvironment> saveEnv; if (modifyEnv) { - saveEnv.reset(new cmSystemTools::SaveRestoreEnvironment); + saveEnv = cm::make_unique<cmSystemTools::SaveRestoreEnvironment>(); cmSystemTools::AppendEnv(*environment); } @@ -1237,7 +1234,7 @@ std::string cmCTest::SafeBuildIdField(const std::string& value) { std::string safevalue(value); - if (safevalue != "") { + if (!safevalue.empty()) { // Disallow non-filename and non-space whitespace characters. // If they occur, replace them with "" // @@ -1256,7 +1253,7 @@ std::string cmCTest::SafeBuildIdField(const std::string& value) } } - if (safevalue == "") { + if (safevalue.empty()) { safevalue = "(empty)"; } @@ -1348,9 +1345,8 @@ void cmCTest::AddSiteProperties(cmXMLWriter& xml) std::string l = labels; std::vector<std::string> args; cmSystemTools::ExpandListArgument(l, args); - for (std::vector<std::string>::iterator i = args.begin(); - i != args.end(); ++i) { - xml.Element("Label", *i); + for (std::string const& i : args) { + xml.Element("Label", i); } xml.EndElement(); } @@ -1368,12 +1364,10 @@ void cmCTest::AddSiteProperties(cmXMLWriter& xml) void cmCTest::GenerateSubprojectsOutput(cmXMLWriter& xml) { - std::vector<std::string> subprojects = this->GetLabelsForSubprojects(); - std::vector<std::string>::const_iterator i; - for (i = subprojects.begin(); i != subprojects.end(); ++i) { + for (std::string const& subproj : this->GetLabelsForSubprojects()) { xml.StartElement("Subproject"); - xml.Attribute("name", *i); - xml.Element("Label", *i); + xml.Attribute("name", subproj); + xml.Element("Label", subproj); xml.EndElement(); // Subproject } } @@ -1406,7 +1400,6 @@ int cmCTest::GenerateCTestNotesOutput(cmXMLWriter& xml, { std::string buildname = cmCTest::SafeBuildIdField(this->GetCTestConfiguration("BuildName")); - cmCTest::VectorOfStrings::const_iterator it; xml.StartDocument(); xml.ProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" " @@ -1422,15 +1415,15 @@ int cmCTest::GenerateCTestNotesOutput(cmXMLWriter& xml, this->AddSiteProperties(xml); xml.StartElement("Notes"); - for (it = files.begin(); it != files.end(); it++) { - cmCTestLog(this, OUTPUT, "\tAdd file: " << *it << std::endl); + for (cmsys::String const& file : files) { + cmCTestLog(this, OUTPUT, "\tAdd file: " << file << std::endl); std::string note_time = this->CurrentTime(); xml.StartElement("Note"); - xml.Attribute("Name", *it); + xml.Attribute("Name", file); xml.Element("Time", cmSystemTools::GetTime()); xml.Element("DateTime", note_time); xml.StartElement("Text"); - cmsys::ifstream ifs(it->c_str()); + cmsys::ifstream ifs(file.c_str()); if (ifs) { std::string line; while (cmSystemTools::GetLineFromStream(ifs, line)) { @@ -1439,9 +1432,9 @@ int cmCTest::GenerateCTestNotesOutput(cmXMLWriter& xml, } ifs.close(); } else { - xml.Content("Problem reading file: " + *it + "\n"); + xml.Content("Problem reading file: " + file + "\n"); cmCTestLog(this, ERROR_MESSAGE, "Problem reading file: " - << *it << " while creating notes" << std::endl); + << file << " while creating notes" << std::endl); } xml.EndElement(); // Text xml.EndElement(); // Note @@ -1523,14 +1516,13 @@ std::string cmCTest::Base64EncodeFile(std::string const& file) bool cmCTest::SubmitExtraFiles(const VectorOfStrings& files) { - VectorOfStrings::const_iterator it; - for (it = files.begin(); it != files.end(); ++it) { - if (!cmSystemTools::FileExists(it->c_str())) { + for (cmsys::String const& file : files) { + if (!cmSystemTools::FileExists(file.c_str())) { cmCTestLog(this, ERROR_MESSAGE, "Cannot find extra file: " - << *it << " to submit." << std::endl;); + << file << " to submit." << std::endl;); return false; } - this->AddSubmitFile(PartExtraFiles, it->c_str()); + this->AddSubmitFile(PartExtraFiles, file.c_str()); } return true; } @@ -2104,10 +2096,8 @@ int cmCTest::Run(std::vector<std::string>& args, std::string* output) // pass the argument to all the handlers as well, but i may no longer be // set to what it was originally so I'm not sure this is working as // intended - cmCTest::t_TestingHandlers::iterator it; - for (it = this->TestingHandlers.begin(); it != this->TestingHandlers.end(); - ++it) { - if (!it->second->ProcessCommandLineArguments(arg, i, args)) { + for (auto& handler : this->TestingHandlers) { + if (!handler.second->ProcessCommandLineArguments(arg, i, args)) { cmCTestLog(this, ERROR_MESSAGE, "Problem parsing command line arguments within a handler"); return 0; @@ -2204,11 +2194,9 @@ int cmCTest::ExecuteTests() if (this->ExtraVerbose) { cmCTestLog(this, OUTPUT, "* Extra verbosity turned on" << std::endl); } - cmCTest::t_TestingHandlers::iterator it; - for (it = this->TestingHandlers.begin(); it != this->TestingHandlers.end(); - ++it) { - it->second->SetVerbose(this->ExtraVerbose); - it->second->SetSubmitIndex(this->SubmitIndex); + for (auto& handler : this->TestingHandlers) { + handler.second->SetVerbose(this->ExtraVerbose); + handler.second->SetSubmitIndex(this->SubmitIndex); } this->GetHandler("script")->SetVerbose(this->Verbose); res = this->GetHandler("script")->ProcessHandler(); @@ -2222,11 +2210,9 @@ int cmCTest::ExecuteTests() // and Verbose is always on in this case this->ExtraVerbose = this->Verbose; this->Verbose = true; - cmCTest::t_TestingHandlers::iterator it; - for (it = this->TestingHandlers.begin(); it != this->TestingHandlers.end(); - ++it) { - it->second->SetVerbose(this->Verbose); - it->second->SetSubmitIndex(this->SubmitIndex); + for (auto& handler : this->TestingHandlers) { + handler.second->SetVerbose(this->Verbose); + handler.second->SetSubmitIndex(this->SubmitIndex); } std::string cwd = cmSystemTools::GetCurrentWorkingDirectory(); if (!this->Initialize(cwd.c_str(), nullptr)) { @@ -2327,13 +2313,11 @@ int cmCTest::ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf) } if (found) { - cmCTest::t_TestingHandlers::iterator it; - for (it = this->TestingHandlers.begin(); it != this->TestingHandlers.end(); - ++it) { - cmCTestLog(this, DEBUG, - "* Read custom CTest configuration vectors for handler: " - << it->first << " (" << it->second << ")" << std::endl); - it->second->PopulateCustomVectors(mf); + for (auto& handler : this->TestingHandlers) { + cmCTestLog( + this, DEBUG, "* Read custom CTest configuration vectors for handler: " + << handler.first << " (" << handler.second << ")" << std::endl); + handler.second->PopulateCustomVectors(mf); } } @@ -2352,9 +2336,8 @@ void cmCTest::PopulateCustomVector(cmMakefile* mf, const std::string& def, vec.clear(); cmSystemTools::ExpandListArgument(dval, vec); - for (std::vector<std::string>::const_iterator it = vec.begin(); - it != vec.end(); ++it) { - cmCTestLog(this, DEBUG, " -- " << *it << std::endl); + for (std::string const& it : vec) { + cmCTestLog(this, DEBUG, " -- " << it << std::endl); } } @@ -2529,7 +2512,7 @@ const char* cmCTest::GetSpecificTrack() void cmCTest::SetSpecificTrack(const char* track) { if (!track) { - this->SpecificTrack = ""; + this->SpecificTrack.clear(); return; } this->SpecificTrack = track; @@ -2581,25 +2564,18 @@ bool cmCTest::SetCTestConfigurationFromCMakeVariable( return true; } -bool cmCTest::RunCommand(const char* command, std::string* stdOut, - std::string* stdErr, int* retVal, const char* dir, - double timeout, Encoding encoding) +bool cmCTest::RunCommand(std::vector<std::string> const& args, + std::string* stdOut, std::string* stdErr, int* retVal, + const char* dir, double timeout, Encoding encoding) { - std::vector<std::string> args = cmSystemTools::ParseArguments(command); - - if (args.empty()) { - return false; - } - std::vector<const char*> argv; - for (std::vector<std::string>::const_iterator a = args.begin(); - a != args.end(); ++a) { - argv.push_back(a->c_str()); + for (std::string const& a : args) { + argv.push_back(a.c_str()); } argv.push_back(nullptr); - *stdOut = ""; - *stdErr = ""; + stdOut->clear(); + stdErr->clear(); cmsysProcess* cp = cmsysProcess_New(); cmsysProcess_SetCommand(cp, &*argv.begin()); diff --git a/Source/cmCTest.h b/Source/cmCTest.h index 66e6a26..dbd67dc 100644 --- a/Source/cmCTest.h +++ b/Source/cmCTest.h @@ -245,13 +245,8 @@ public: * exit code will be stored. If the retVal is not specified and * the program exits with a code other than 0, then the this * function will return false. - * - * If the command has spaces in the path the caller MUST call - * cmSystemTools::ConvertToRunCommandPath on the command before passing - * it into this function or it will not work. The command must be correctly - * escaped for this to with spaces. */ - bool RunCommand(const char* command, std::string* stdOut, + bool RunCommand(std::vector<std::string> const& args, std::string* stdOut, std::string* stdErr, int* retVal = nullptr, const char* dir = nullptr, double timeout = 0.0, Encoding encoding = cmProcessOutput::Auto); diff --git a/Source/cmCacheManager.cxx b/Source/cmCacheManager.cxx index d599275..44095ec 100644 --- a/Source/cmCacheManager.cxx +++ b/Source/cmCacheManager.cxx @@ -297,10 +297,8 @@ bool cmCacheManager::SaveCache(const std::string& path) fout << "########################\n"; fout << "\n"; - for (std::map<std::string, CacheEntry>::const_iterator i = - this->Cache.begin(); - i != this->Cache.end(); ++i) { - const CacheEntry& ce = (*i).second; + for (auto const& i : this->Cache) { + CacheEntry const& ce = i.second; cmStateEnums::CacheEntryType t = ce.Type; if (!ce.Initialized) { /* @@ -315,7 +313,7 @@ bool cmCacheManager::SaveCache(const std::string& path) } else { cmCacheManager::OutputHelpString(fout, "Missing description"); } - this->OutputKey(fout, i->first); + this->OutputKey(fout, i.first); fout << ":" << cmState::CacheEntryTypeToString(t) << "="; this->OutputValue(fout, ce.Value); fout << "\n\n"; @@ -462,11 +460,9 @@ void cmCacheManager::PrintCache(std::ostream& out) const { out << "=================================================" << std::endl; out << "CMakeCache Contents:" << std::endl; - for (std::map<std::string, CacheEntry>::const_iterator i = - this->Cache.begin(); - i != this->Cache.end(); ++i) { - if ((*i).second.Type != cmStateEnums::INTERNAL) { - out << (*i).first << " = " << (*i).second.Value << std::endl; + for (auto const& i : this->Cache) { + if (i.second.Type != cmStateEnums::INTERNAL) { + out << i.first << " = " << i.second.Value << std::endl; } } out << "\n\n"; @@ -484,7 +480,7 @@ void cmCacheManager::AddCacheEntry(const std::string& key, const char* value, e.Value = value; e.Initialized = true; } else { - e.Value = ""; + e.Value.clear(); } e.Type = type; // make sure we only use unix style paths @@ -494,11 +490,10 @@ void cmCacheManager::AddCacheEntry(const std::string& key, const char* value, cmSystemTools::ExpandListArgument(e.Value, paths); const char* sep = ""; e.Value = ""; - for (std::vector<std::string>::iterator i = paths.begin(); - i != paths.end(); ++i) { - cmSystemTools::ConvertToUnixSlashes(*i); + for (std::string& i : paths) { + cmSystemTools::ConvertToUnixSlashes(i); e.Value += sep; - e.Value += *i; + e.Value += i; sep = ";"; } } else { @@ -548,7 +543,7 @@ void cmCacheManager::CacheIterator::SetValue(const char* value) entry->Value = value; entry->Initialized = true; } else { - entry->Value = ""; + entry->Value.clear(); } } diff --git a/Source/cmCommandArgumentParserHelper.cxx b/Source/cmCommandArgumentParserHelper.cxx index 4764620..6ae58d6 100644 --- a/Source/cmCommandArgumentParserHelper.cxx +++ b/Source/cmCommandArgumentParserHelper.cxx @@ -234,7 +234,7 @@ int cmCommandArgumentParserHelper::ParseString(const char* str, int verb) this->InputBufferPos = 0; this->CurrentLine = 0; - this->Result = ""; + this->Result.clear(); yyscan_t yyscanner; cmCommandArgument_yylex_init(&yyscanner); @@ -258,8 +258,8 @@ int cmCommandArgumentParserHelper::ParseString(const char* str, int verb) void cmCommandArgumentParserHelper::CleanupParser() { std::vector<char*>::iterator sit; - for (sit = this->Variables.begin(); sit != this->Variables.end(); ++sit) { - delete[] * sit; + for (char* var : this->Variables) { + delete[] var; } this->Variables.erase(this->Variables.begin(), this->Variables.end()); } @@ -298,7 +298,7 @@ void cmCommandArgumentParserHelper::SetMakefile(const cmMakefile* mf) void cmCommandArgumentParserHelper::SetResult(const char* value) { if (!value) { - this->Result = ""; + this->Result.clear(); return; } this->Result = value; diff --git a/Source/cmCommandArgumentsHelper.cxx b/Source/cmCommandArgumentsHelper.cxx index 36d4da4..968b17c 100644 --- a/Source/cmCommandArgumentsHelper.cxx +++ b/Source/cmCommandArgumentsHelper.cxx @@ -61,11 +61,9 @@ bool cmCommandArgument::KeyMatches(const std::string& key) const void cmCommandArgument::ApplyOwnGroup() { if (this->Group != nullptr) { - for (std::vector<cmCommandArgument*>::const_iterator it = - this->Group->ContainedArguments.begin(); - it != this->Group->ContainedArguments.end(); ++it) { - if (*it != this) { - this->ArgumentsBefore.insert(*it); + for (cmCommandArgument* cargs : this->Group->ContainedArguments) { + if (cargs != this) { + this->ArgumentsBefore.insert(cargs); } } } @@ -135,7 +133,7 @@ bool cmCAString::DoConsume(const std::string& arg, unsigned int index) void cmCAString::DoReset() { - this->String = ""; + this->String.clear(); } cmCAEnabler::cmCAEnabler(cmCommandArgumentsHelper* args, const char* key, @@ -180,19 +178,15 @@ void cmCADisabler::DoReset() void cmCommandArgumentGroup::Follows(const cmCommandArgument* arg) { - for (std::vector<cmCommandArgument*>::iterator it = - this->ContainedArguments.begin(); - it != this->ContainedArguments.end(); ++it) { - (*it)->Follows(arg); + for (cmCommandArgument* ca : this->ContainedArguments) { + ca->Follows(arg); } } void cmCommandArgumentGroup::FollowsGroup(const cmCommandArgumentGroup* group) { - for (std::vector<cmCommandArgument*>::iterator it = - this->ContainedArguments.begin(); - it != this->ContainedArguments.end(); ++it) { - (*it)->FollowsGroup(group); + for (cmCommandArgument* ca : this->ContainedArguments) { + ca->FollowsGroup(group); } } @@ -203,37 +197,31 @@ void cmCommandArgumentsHelper::Parse(const std::vector<std::string>* args, return; } - for (std::vector<cmCommandArgument*>::iterator argIt = - this->Arguments.begin(); - argIt != this->Arguments.end(); ++argIt) { - (*argIt)->ApplyOwnGroup(); - (*argIt)->Reset(); + for (cmCommandArgument* ca : this->Arguments) { + ca->ApplyOwnGroup(); + ca->Reset(); } cmCommandArgument* activeArgument = nullptr; const cmCommandArgument* previousArgument = nullptr; - for (std::vector<std::string>::const_iterator it = args->begin(); - it != args->end(); ++it) { - for (std::vector<cmCommandArgument*>::iterator argIt = - this->Arguments.begin(); - argIt != this->Arguments.end(); ++argIt) { - if ((*argIt)->KeyMatches(*it) && - ((*argIt)->MayFollow(previousArgument))) { - activeArgument = *argIt; + for (std::string const& it : *args) { + for (cmCommandArgument* ca : this->Arguments) { + if (ca->KeyMatches(it) && (ca->MayFollow(previousArgument))) { + activeArgument = ca; activeArgument->Activate(); break; } } if (activeArgument) { - bool argDone = activeArgument->Consume(*it); + bool argDone = activeArgument->Consume(it); previousArgument = activeArgument; if (argDone) { activeArgument = nullptr; } } else { if (unconsumedArgs != nullptr) { - unconsumedArgs->push_back(*it); + unconsumedArgs->push_back(it); } } } diff --git a/Source/cmCommandArgumentsHelper.h b/Source/cmCommandArgumentsHelper.h index 56d88e9..d3f102c 100644 --- a/Source/cmCommandArgumentsHelper.h +++ b/Source/cmCommandArgumentsHelper.h @@ -103,8 +103,8 @@ private: unsigned int DataStart; const char* Ignore; cmCAStringVector(); - bool DoConsume(const std::string& arg, unsigned int index) CM_OVERRIDE; - void DoReset() CM_OVERRIDE; + bool DoConsume(const std::string& arg, unsigned int index) override; + void DoReset() override; }; /** cmCAString is to be used for arguments which consist of one value, @@ -121,8 +121,8 @@ public: private: std::string String; unsigned int DataStart; - bool DoConsume(const std::string& arg, unsigned int index) CM_OVERRIDE; - void DoReset() CM_OVERRIDE; + bool DoConsume(const std::string& arg, unsigned int index) override; + void DoReset() override; cmCAString(); }; @@ -138,8 +138,8 @@ public: bool IsEnabled() const { return this->Enabled; } private: bool Enabled; - bool DoConsume(const std::string& arg, unsigned int index) CM_OVERRIDE; - void DoReset() CM_OVERRIDE; + bool DoConsume(const std::string& arg, unsigned int index) override; + void DoReset() override; cmCAEnabler(); }; @@ -155,8 +155,8 @@ public: bool IsEnabled() const { return this->Enabled; } private: bool Enabled; - bool DoConsume(const std::string& arg, unsigned int index) CM_OVERRIDE; - void DoReset() CM_OVERRIDE; + bool DoConsume(const std::string& arg, unsigned int index) override; + void DoReset() override; cmCADisabler(); }; diff --git a/Source/cmCommonTargetGenerator.cxx b/Source/cmCommonTargetGenerator.cxx index a70839e..bd4077f 100644 --- a/Source/cmCommonTargetGenerator.cxx +++ b/Source/cmCommonTargetGenerator.cxx @@ -147,10 +147,8 @@ std::vector<std::string> cmCommonTargetGenerator::GetLinkedTargetDirectories() if (cmComputeLinkInformation* cli = this->GeneratorTarget->GetLinkInformation(this->ConfigName)) { cmComputeLinkInformation::ItemVector const& items = cli->GetItems(); - for (cmComputeLinkInformation::ItemVector::const_iterator i = - items.begin(); - i != items.end(); ++i) { - cmGeneratorTarget const* linkee = i->Target; + for (auto const& item : items) { + cmGeneratorTarget const* linkee = item.Target; if (linkee && !linkee->IsImported() // We can ignore the INTERFACE_LIBRARY items because // Target->GetLinkInformation already processed their @@ -196,12 +194,11 @@ std::string cmCommonTargetGenerator::GetManifests() this->GeneratorTarget->GetManifests(manifest_srcs, this->ConfigName); std::vector<std::string> manifests; - for (std::vector<cmSourceFile const*>::iterator mi = manifest_srcs.begin(); - mi != manifest_srcs.end(); ++mi) { + for (cmSourceFile const* manifest_src : manifest_srcs) { manifests.push_back(this->LocalCommonGenerator->ConvertToOutputFormat( this->LocalCommonGenerator->ConvertToRelativePath( this->LocalCommonGenerator->GetWorkingDirectory(), - (*mi)->GetFullPath()), + manifest_src->GetFullPath()), cmOutputConverter::SHELL)); } diff --git a/Source/cmComputeComponentGraph.cxx b/Source/cmComputeComponentGraph.cxx index a02d885..9ec98ae 100644 --- a/Source/cmComputeComponentGraph.cxx +++ b/Source/cmComputeComponentGraph.cxx @@ -57,8 +57,8 @@ void cmComputeComponentGraph::TarjanVisit(int i) // Follow outgoing edges. EdgeList const& nl = this->InputGraph[i]; - for (EdgeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) { - int j = *ni; + for (cmGraphEdge const& ni : nl) { + int j = ni; // Ignore edges to nodes that have been reached by a previous DFS // walk. Since we did not reach the current node from that walk @@ -119,14 +119,14 @@ void cmComputeComponentGraph::TransferEdges() for (int i = 0; i < n; ++i) { int i_component = this->TarjanComponents[i]; EdgeList const& nl = this->InputGraph[i]; - for (EdgeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) { - int j = *ni; + for (cmGraphEdge const& ni : nl) { + int j = ni; int j_component = this->TarjanComponents[j]; if (i_component != j_component) { // We do not attempt to combine duplicate edges, but instead // store the inter-component edges with suitable multiplicity. this->ComponentGraph[i_component].push_back( - cmGraphEdge(j_component, ni->IsStrong())); + cmGraphEdge(j_component, ni.IsStrong())); } } } diff --git a/Source/cmComputeLinkDepends.cxx b/Source/cmComputeLinkDepends.cxx index 2277bbe..d9efc2e 100644 --- a/Source/cmComputeLinkDepends.cxx +++ b/Source/cmComputeLinkDepends.cxx @@ -357,10 +357,8 @@ void cmComputeLinkDepends::FollowLinkEntry(BFSEntry qe) this->FollowSharedDeps(depender_index, iface); // Support for CMP0003. - for (std::vector<cmLinkItem>::const_iterator oi = - iface->WrongConfigLibraries.begin(); - oi != iface->WrongConfigLibraries.end(); ++oi) { - this->CheckWrongConfigItem(*oi); + for (cmLinkItem const& oi : iface->WrongConfigLibraries) { + this->CheckWrongConfigItem(oi); } } } else { @@ -385,10 +383,9 @@ void cmComputeLinkDepends::FollowSharedDeps(int depender_index, void cmComputeLinkDepends::QueueSharedDependencies( int depender_index, std::vector<cmLinkItem> const& deps) { - for (std::vector<cmLinkItem>::const_iterator li = deps.begin(); - li != deps.end(); ++li) { + for (cmLinkItem const& li : deps) { SharedDepEntry qe; - qe.Item = *li; + qe.Item = li; qe.DependerIndex = depender_index; this->SharedDepQueue.push(qe); } @@ -445,25 +442,24 @@ void cmComputeLinkDepends::AddVarLinkEntries(int depender_index, std::vector<cmLinkItem> actual_libs; cmTargetLinkLibraryType llt = GENERAL_LibraryType; bool haveLLT = false; - for (std::vector<std::string>::const_iterator di = deplist.begin(); - di != deplist.end(); ++di) { - if (*di == "debug") { + for (std::string const& d : deplist) { + if (d == "debug") { llt = DEBUG_LibraryType; haveLLT = true; - } else if (*di == "optimized") { + } else if (d == "optimized") { llt = OPTIMIZED_LibraryType; haveLLT = true; - } else if (*di == "general") { + } else if (d == "general") { llt = GENERAL_LibraryType; haveLLT = true; - } else if (!di->empty()) { + } else if (!d.empty()) { // If no explicit link type was given prior to this entry then // check if the entry has its own link type variable. This is // needed for compatibility with dependency files generated by // the export_library_dependencies command from CMake 2.4 and // lower. if (!haveLLT) { - std::string var = *di; + std::string var = d; var += "_LINK_TYPE"; if (const char* val = this->Makefile->GetDefinition(var)) { if (strcmp(val, "debug") == 0) { @@ -476,10 +472,10 @@ void cmComputeLinkDepends::AddVarLinkEntries(int depender_index, // If the library is meant for this link type then use it. if (llt == GENERAL_LibraryType || llt == this->LinkType) { - cmLinkItem item(*di, this->FindTargetToLink(depender_index, *di)); + cmLinkItem item(d, this->FindTargetToLink(depender_index, d)); actual_libs.push_back(item); } else if (this->OldLinkDirMode) { - cmLinkItem item(*di, this->FindTargetToLink(depender_index, *di)); + cmLinkItem item(d, this->FindTargetToLink(depender_index, d)); this->CheckWrongConfigItem(item); } @@ -499,10 +495,8 @@ void cmComputeLinkDepends::AddDirectLinkEntries() cmLinkImplementation const* impl = this->Target->GetLinkImplementation(this->Config); this->AddLinkEntries(-1, impl->Libraries); - for (std::vector<cmLinkItem>::const_iterator wi = - impl->WrongConfigLibraries.begin(); - wi != impl->WrongConfigLibraries.end(); ++wi) { - this->CheckWrongConfigItem(*wi); + for (cmLinkItem const& wi : impl->WrongConfigLibraries) { + this->CheckWrongConfigItem(wi); } } @@ -514,17 +508,16 @@ void cmComputeLinkDepends::AddLinkEntries(int depender_index, std::map<int, DependSet> dependSets; // Loop over the libraries linked directly by the depender. - for (typename std::vector<T>::const_iterator li = libs.begin(); - li != libs.end(); ++li) { + for (T const& l : libs) { // Skip entries that will resolve to the target getting linked or // are empty. - cmLinkItem const& item = *li; + cmLinkItem const& item = l; if (item == this->Target->GetName() || item.empty()) { continue; } // Add a link entry for this item. - int dependee_index = this->AddLinkEntry(*li); + int dependee_index = this->AddLinkEntry(l); // The dependee must come after the depender. if (depender_index >= 0) { @@ -535,16 +528,15 @@ void cmComputeLinkDepends::AddLinkEntries(int depender_index, } // Update the inferred dependencies for earlier items. - for (std::map<int, DependSet>::iterator dsi = dependSets.begin(); - dsi != dependSets.end(); ++dsi) { + for (auto& dependSet : dependSets) { // Add this item to the inferred dependencies of other items. // Target items are never inferred dependees because unknown // items are outside libraries that should not be depending on // targets. if (!this->EntryList[dependee_index].Target && !this->EntryList[dependee_index].IsFlag && - dependee_index != dsi->first) { - dsi->second.insert(dependee_index); + dependee_index != dependSet.first) { + dependSet.second.insert(dependee_index); } } @@ -556,9 +548,8 @@ void cmComputeLinkDepends::AddLinkEntries(int depender_index, } // Store the inferred dependency sets discovered for this list. - for (std::map<int, DependSet>::iterator dsi = dependSets.begin(); - dsi != dependSets.end(); ++dsi) { - this->InferredDependSets[dsi->first]->push_back(dsi->second); + for (auto const& dependSet : dependSets) { + this->InferredDependSets[dependSet.first]->push_back(dependSet.second); } } @@ -608,14 +599,14 @@ void cmComputeLinkDepends::InferDependencies() void cmComputeLinkDepends::CleanConstraintGraph() { - for (Graph::iterator i = this->EntryConstraintGraph.begin(); - i != this->EntryConstraintGraph.end(); ++i) { + for (cmGraphEdgeList& edgeList : this->EntryConstraintGraph) { // Sort the outgoing edges for each graph node so that the // original order will be preserved as much as possible. - std::sort(i->begin(), i->end()); + std::sort(edgeList.begin(), edgeList.end()); // Make the edge list unique. - i->erase(std::unique(i->begin(), i->end()), i->end()); + edgeList.erase(std::unique(edgeList.begin(), edgeList.end()), + edgeList.end()); } } @@ -660,9 +651,8 @@ void cmComputeLinkDepends::OrderLinkEntires() } // Start with the original link line. - for (std::vector<int>::const_iterator i = this->OriginalEntries.begin(); - i != this->OriginalEntries.end(); ++i) { - this->VisitEntry(*i); + for (int originalEntry : this->OriginalEntries) { + this->VisitEntry(originalEntry); } // Now explore anything left pending. Since the component graph is @@ -684,13 +674,12 @@ void cmComputeLinkDepends::DisplayComponents() for (unsigned int c = 0; c < components.size(); ++c) { fprintf(stderr, "Component (%u):\n", c); NodeList const& nl = components[c]; - for (NodeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) { - int i = *ni; + for (int i : nl) { fprintf(stderr, " item %d [%s]\n", i, this->EntryList[i].Item.c_str()); } EdgeList const& ol = this->CCG->GetComponentGraphEdges(c); - for (EdgeList::const_iterator oi = ol.begin(); oi != ol.end(); ++oi) { - int i = *oi; + for (cmGraphEdge const& oi : ol) { + int i = oi; fprintf(stderr, " followed by Component (%d)\n", i); } fprintf(stderr, " topo order index %d\n", this->ComponentOrder[c]); @@ -771,10 +760,10 @@ void cmComputeLinkDepends::VisitEntry(int index) // are now pending. if (completed) { EdgeList const& ol = this->CCG->GetComponentGraphEdges(component); - for (EdgeList::const_iterator oi = ol.begin(); oi != ol.end(); ++oi) { + for (cmGraphEdge const& oi : ol) { // This entire component is now pending no matter whether it has // been partially seen already. - this->MakePendingComponent(*oi); + this->MakePendingComponent(oi); } } } @@ -816,8 +805,8 @@ cmComputeLinkDepends::MakePendingComponent(unsigned int component) int cmComputeLinkDepends::ComputeComponentCount(NodeList const& nl) { unsigned int count = 2; - for (NodeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) { - if (cmGeneratorTarget const* target = this->EntryList[*ni].Target) { + for (int ni : nl) { + if (cmGeneratorTarget const* target = this->EntryList[ni].Target) { if (cmLinkInterface const* iface = target->GetLinkInterface(this->Config, this->Target)) { if (iface->Multiplicity > count) { @@ -832,13 +821,11 @@ int cmComputeLinkDepends::ComputeComponentCount(NodeList const& nl) void cmComputeLinkDepends::DisplayFinalEntries() { fprintf(stderr, "target [%s] links to:\n", this->Target->GetName().c_str()); - for (std::vector<LinkEntry>::const_iterator lei = - this->FinalLinkEntries.begin(); - lei != this->FinalLinkEntries.end(); ++lei) { - if (lei->Target) { - fprintf(stderr, " target [%s]\n", lei->Target->GetName().c_str()); + for (LinkEntry const& lei : this->FinalLinkEntries) { + if (lei.Target) { + fprintf(stderr, " target [%s]\n", lei.Target->GetName().c_str()); } else { - fprintf(stderr, " item [%s]\n", lei->Item.c_str()); + fprintf(stderr, " item [%s]\n", lei.Item.c_str()); } } fprintf(stderr, "\n"); diff --git a/Source/cmComputeLinkInformation.cxx b/Source/cmComputeLinkInformation.cxx index f348a7e..fb13a58 100644 --- a/Source/cmComputeLinkInformation.cxx +++ b/Source/cmComputeLinkInformation.cxx @@ -468,13 +468,11 @@ bool cmComputeLinkInformation::Compute() cmComputeLinkDepends::EntryVector const& linkEntries = cld.Compute(); // Add the link line items. - for (cmComputeLinkDepends::EntryVector::const_iterator lei = - linkEntries.begin(); - lei != linkEntries.end(); ++lei) { - if (lei->IsSharedDep) { - this->AddSharedDepItem(lei->Item, lei->Target); + for (cmComputeLinkDepends::LinkEntry const& linkEntry : linkEntries) { + if (linkEntry.IsSharedDep) { + this->AddSharedDepItem(linkEntry.Item, linkEntry.Target); } else { - this->AddItem(lei->Item, lei->Target); + this->AddItem(linkEntry.Item, linkEntry.Target); } } @@ -494,10 +492,7 @@ bool cmComputeLinkInformation::Compute() // directories. std::set<cmGeneratorTarget const*> const& wrongItems = cld.GetOldWrongConfigItems(); - for (std::set<cmGeneratorTarget const*>::const_iterator i = - wrongItems.begin(); - i != wrongItems.end(); ++i) { - cmGeneratorTarget const* tgt = *i; + for (cmGeneratorTarget const* tgt : wrongItems) { bool implib = (this->UseImportLibrary && (tgt->GetType() == cmStateEnums::SHARED_LIBRARY)); cmStateEnums::ArtifactType artifact = implib @@ -540,11 +535,10 @@ void cmComputeLinkInformation::AddImplicitLinkInfo() // The link closure lists all languages whose implicit info is needed. cmGeneratorTarget::LinkClosure const* lc = this->Target->GetLinkClosure(this->Config); - for (std::vector<std::string>::const_iterator li = lc->Languages.begin(); - li != lc->Languages.end(); ++li) { + for (std::string const& li : lc->Languages) { // Skip those of the linker language. They are implicit. - if (*li != this->LinkLanguage) { - this->AddImplicitLinkInfo(*li); + if (li != this->LinkLanguage) { + this->AddImplicitLinkInfo(li); } } } @@ -559,10 +553,9 @@ void cmComputeLinkInformation::AddImplicitLinkInfo(std::string const& lang) if (const char* libs = this->Makefile->GetDefinition(libVar)) { std::vector<std::string> libsVec; cmSystemTools::ExpandListArgument(libs, libsVec); - for (std::vector<std::string>::const_iterator i = libsVec.begin(); - i != libsVec.end(); ++i) { - if (this->ImplicitLinkLibs.find(*i) == this->ImplicitLinkLibs.end()) { - this->AddItem(*i, nullptr); + for (std::string const& i : libsVec) { + if (this->ImplicitLinkLibs.find(i) == this->ImplicitLinkLibs.end()) { + this->AddItem(i, nullptr); } } } @@ -811,18 +804,16 @@ void cmComputeLinkInformation::ComputeItemParserInfo() mf->GetDefinition("CMAKE_EXTRA_LINK_EXTENSIONS")) { std::vector<std::string> linkSuffixVec; cmSystemTools::ExpandListArgument(linkSuffixes, linkSuffixVec); - for (std::vector<std::string>::iterator i = linkSuffixVec.begin(); - i != linkSuffixVec.end(); ++i) { - this->AddLinkExtension(i->c_str(), LinkUnknown); + for (std::string const& i : linkSuffixVec) { + this->AddLinkExtension(i.c_str(), LinkUnknown); } } if (const char* sharedSuffixes = mf->GetDefinition("CMAKE_EXTRA_SHARED_LIBRARY_SUFFIXES")) { std::vector<std::string> sharedSuffixVec; cmSystemTools::ExpandListArgument(sharedSuffixes, sharedSuffixVec); - for (std::vector<std::string>::iterator i = sharedSuffixVec.begin(); - i != sharedSuffixVec.end(); ++i) { - this->AddLinkExtension(i->c_str(), LinkShared); + for (std::string const& i : sharedSuffixVec) { + this->AddLinkExtension(i.c_str(), LinkShared); } } @@ -840,9 +831,8 @@ void cmComputeLinkInformation::ComputeItemParserInfo() // be the library name. Match index 3 will be the library // extension. reg = "^("; - for (std::set<std::string>::iterator p = this->LinkPrefixes.begin(); - p != this->LinkPrefixes.end(); ++p) { - reg += *p; + for (std::string const& p : this->LinkPrefixes) { + reg += p; reg += "|"; } reg += ")"; @@ -906,8 +896,7 @@ std::string cmComputeLinkInformation::CreateExtensionRegex( // Build a list of extension choices. std::string libext = "("; const char* sep = ""; - for (std::vector<std::string>::const_iterator i = exts.begin(); - i != exts.end(); ++i) { + for (std::string const& i : exts) { // Separate this choice from the previous one. libext += sep; sep = "|"; @@ -915,9 +904,9 @@ std::string cmComputeLinkInformation::CreateExtensionRegex( // Store this extension choice with the "." escaped. libext += "\\"; #if defined(_WIN32) && !defined(__CYGWIN__) - libext += this->NoCaseExpression(i->c_str()); + libext += this->NoCaseExpression(i.c_str()); #else - libext += *i; + libext += i; #endif } @@ -1457,10 +1446,8 @@ bool cmComputeLinkInformation::FinishLinkerSearchDirectories() } // Add the link directories for full path items. - for (std::vector<std::string>::const_iterator i = - this->OldLinkDirItems.begin(); - i != this->OldLinkDirItems.end(); ++i) { - this->OrderLinkerSearchPath->AddLinkLibrary(*i); + for (std::string const& i : this->OldLinkDirItems) { + this->OrderLinkerSearchPath->AddLinkLibrary(i); } return true; } @@ -1489,19 +1476,17 @@ void cmComputeLinkInformation::PrintLinkPolicyDiagnosis(std::ostream& os) std::string::size_type max_size = 76; std::string line; const char* sep = " "; - for (std::vector<std::string>::const_iterator i = - this->OldUserFlagItems.begin(); - i != this->OldUserFlagItems.end(); ++i) { + for (std::string const& i : this->OldUserFlagItems) { // If the addition of another item will exceed the limit then // output the current line and reset it. Note that the separator // is either " " or ", " which is always 2 characters. - if (!line.empty() && (line.size() + i->size() + 2) > max_size) { + if (!line.empty() && (line.size() + i.size() + 2) > max_size) { os << line << "\n"; sep = " "; - line = ""; + line.clear(); } line += sep; - line += *i; + line += i; // Convert to the other separator. sep = ", "; } @@ -1513,11 +1498,9 @@ void cmComputeLinkInformation::PrintLinkPolicyDiagnosis(std::ostream& os) // List the paths old behavior is adding. os << "and other libraries with known full path:\n"; std::set<std::string> emitted; - for (std::vector<std::string>::const_iterator i = - this->OldLinkDirItems.begin(); - i != this->OldLinkDirItems.end(); ++i) { - if (emitted.insert(cmSystemTools::GetFilenamePath(*i)).second) { - os << " " << *i << "\n"; + for (std::string const& i : this->OldLinkDirItems) { + if (emitted.insert(cmSystemTools::GetFilenamePath(i)).second) { + os << " " << i << "\n"; } } @@ -1544,9 +1527,8 @@ void cmComputeLinkInformation::LoadImplicitLinkInfo() // and add them to the set if (const char* libraryArch = this->Makefile->GetDefinition("CMAKE_LIBRARY_ARCHITECTURE")) { - for (std::vector<std::string>::const_iterator i = implicitDirVec.begin(); - i != implicitDirVec.end(); ++i) { - this->ImplicitLinkDirs.insert(*i + "/" + libraryArch); + for (std::string const& i : implicitDirVec) { + this->ImplicitLinkDirs.insert(i + "/" + libraryArch); } } @@ -1573,11 +1555,9 @@ void cmComputeLinkInformation::LoadImplicitLinkInfo() } // Store implicit link libraries. - for (std::vector<std::string>::const_iterator i = implicitLibVec.begin(); - i != implicitLibVec.end(); ++i) { + for (std::string const& item : implicitLibVec) { // Items starting in '-' but not '-l' are flags, not libraries, // and should not be filtered by this implicit list. - std::string const& item = *i; if (item[0] != '-' || item[1] == 'l') { this->ImplicitLinkLibs.insert(item); } @@ -1694,10 +1674,9 @@ static void cmCLI_ExpandListUnique(const char* str, { std::vector<std::string> tmp; cmSystemTools::ExpandListArgument(str, tmp); - for (std::vector<std::string>::iterator i = tmp.begin(); i != tmp.end(); - ++i) { - if (emitted.insert(*i).second) { - out.push_back(*i); + for (std::string const& i : tmp) { + if (emitted.insert(i).second) { + out.push_back(i); } } } @@ -1750,12 +1729,11 @@ void cmComputeLinkInformation::GetRPath(std::vector<std::string>& runtimeDirs, this->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX"); cmSystemTools::ConvertToUnixSlashes(rootPath); std::vector<std::string> const& rdirs = this->GetRuntimeSearchPath(); - for (std::vector<std::string>::const_iterator ri = rdirs.begin(); - ri != rdirs.end(); ++ri) { + for (std::string const& ri : rdirs) { // Put this directory in the rpath if using build-tree rpath // support or if using the link path as an rpath. if (use_build_rpath) { - std::string d = *ri; + std::string d = ri; if (!rootPath.empty() && d.find(rootPath) == 0) { d = d.substr(rootPath.size()); } else if (stagePath && *stagePath && d.find(stagePath) == 0) { @@ -1773,11 +1751,11 @@ void cmComputeLinkInformation::GetRPath(std::vector<std::string>& runtimeDirs, const char* topSourceDir = this->CMakeInstance->GetHomeDirectory(); const char* topBinaryDir = this->CMakeInstance->GetHomeOutputDirectory(); - if (!cmSystemTools::ComparePath(*ri, topSourceDir) && - !cmSystemTools::ComparePath(*ri, topBinaryDir) && - !cmSystemTools::IsSubDirectory(*ri, topSourceDir) && - !cmSystemTools::IsSubDirectory(*ri, topBinaryDir)) { - std::string d = *ri; + if (!cmSystemTools::ComparePath(ri, topSourceDir) && + !cmSystemTools::ComparePath(ri, topBinaryDir) && + !cmSystemTools::IsSubDirectory(ri, topSourceDir) && + !cmSystemTools::IsSubDirectory(ri, topBinaryDir)) { + std::string d = ri; if (!rootPath.empty() && d.find(rootPath) == 0) { d = d.substr(rootPath.size()); } else if (stagePath && *stagePath && d.find(stagePath) == 0) { @@ -1800,12 +1778,11 @@ void cmComputeLinkInformation::GetRPath(std::vector<std::string>& runtimeDirs, { cmGeneratorTarget::LinkClosure const* lc = this->Target->GetLinkClosure(this->Config); - for (std::vector<std::string>::const_iterator li = lc->Languages.begin(); - li != lc->Languages.end(); ++li) { + for (std::string const& li : lc->Languages) { std::string useVar = - "CMAKE_" + *li + "_USE_IMPLICIT_LINK_DIRECTORIES_IN_RUNTIME_PATH"; + "CMAKE_" + li + "_USE_IMPLICIT_LINK_DIRECTORIES_IN_RUNTIME_PATH"; if (this->Makefile->IsOn(useVar)) { - std::string dirVar = "CMAKE_" + *li + "_IMPLICIT_LINK_DIRECTORIES"; + std::string dirVar = "CMAKE_" + li + "_IMPLICIT_LINK_DIRECTORIES"; if (const char* dirs = this->Makefile->GetDefinition(dirVar)) { cmCLI_ExpandListUnique(dirs, runtimeDirs, emitted); } diff --git a/Source/cmComputeTargetDepends.cxx b/Source/cmComputeTargetDepends.cxx index ff0052b..963c2df 100644 --- a/Source/cmComputeTargetDepends.cxx +++ b/Source/cmComputeTargetDepends.cxx @@ -148,10 +148,10 @@ void cmComputeTargetDepends::GetTargetDirectDepends(cmGeneratorTarget const* t, // Get its final dependencies. EdgeList const& nl = this->FinalGraph[i]; - for (EdgeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) { - cmGeneratorTarget const* dep = this->Targets[*ni]; + for (cmGraphEdge const& ni : nl) { + cmGeneratorTarget const* dep = this->Targets[ni]; cmTargetDependSet::iterator di = deps.insert(dep).first; - di->SetType(ni->IsStrong()); + di->SetType(ni.IsStrong()); } } @@ -160,15 +160,13 @@ void cmComputeTargetDepends::CollectTargets() // Collect all targets from all generators. std::vector<cmLocalGenerator*> const& lgens = this->GlobalGenerator->GetLocalGenerators(); - for (unsigned int i = 0; i < lgens.size(); ++i) { + for (cmLocalGenerator* lgen : lgens) { const std::vector<cmGeneratorTarget*>& targets = - lgens[i]->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator ti = targets.begin(); - ti != targets.end(); ++ti) { - cmGeneratorTarget* gt = *ti; + lgen->GetGeneratorTargets(); + for (cmGeneratorTarget const* ti : targets) { int index = static_cast<int>(this->Targets.size()); - this->TargetIndex[gt] = index; - this->Targets.push_back(gt); + this->TargetIndex[ti] = index; + this->Targets.push_back(ti); } } } @@ -204,14 +202,11 @@ void cmComputeTargetDepends::CollectTargetDepends(int depender_index) if (configs.empty()) { configs.push_back(""); } - for (std::vector<std::string>::const_iterator it = configs.begin(); - it != configs.end(); ++it) { + for (std::string const& it : configs) { std::vector<cmSourceFile const*> objectFiles; - depender->GetExternalObjects(objectFiles, *it); - for (std::vector<cmSourceFile const*>::const_iterator oi = - objectFiles.begin(); - oi != objectFiles.end(); ++oi) { - std::string objLib = (*oi)->GetObjectLibrary(); + depender->GetExternalObjects(objectFiles, it); + for (cmSourceFile const* o : objectFiles) { + std::string objLib = o->GetObjectLibrary(); if (!objLib.empty() && emitted.insert(objLib).second) { if (depender->GetType() != cmStateEnums::EXECUTABLE && depender->GetType() != cmStateEnums::STATIC_LIBRARY && @@ -228,17 +223,15 @@ void cmComputeTargetDepends::CollectTargetDepends(int depender_index) } } - cmLinkImplementation const* impl = depender->GetLinkImplementation(*it); + cmLinkImplementation const* impl = depender->GetLinkImplementation(it); // A target should not depend on itself. emitted.insert(depender->GetName()); - for (std::vector<cmLinkImplItem>::const_iterator lib = - impl->Libraries.begin(); - lib != impl->Libraries.end(); ++lib) { + for (cmLinkImplItem const& lib : impl->Libraries) { // Don't emit the same library twice for this target. - if (emitted.insert(*lib).second) { - this->AddTargetDepend(depender_index, *lib, true); - this->AddInterfaceDepends(depender_index, *lib, *it, emitted); + if (emitted.insert(lib).second) { + this->AddTargetDepend(depender_index, lib, true); + this->AddInterfaceDepends(depender_index, lib, it, emitted); } } } @@ -250,11 +243,10 @@ void cmComputeTargetDepends::CollectTargetDepends(int depender_index) std::set<std::string> emitted; // A target should not depend on itself. emitted.insert(depender->GetName()); - for (std::set<cmLinkItem>::const_iterator util = tutils.begin(); - util != tutils.end(); ++util) { + for (cmLinkItem const& litem : tutils) { // Don't emit the same utility twice for this target. - if (emitted.insert(*util).second) { - this->AddTargetDepend(depender_index, *util, false); + if (emitted.insert(litem).second) { + this->AddTargetDepend(depender_index, litem, false); } } } @@ -267,13 +259,11 @@ void cmComputeTargetDepends::AddInterfaceDepends( cmGeneratorTarget const* depender = this->Targets[depender_index]; if (cmLinkInterface const* iface = dependee->GetLinkInterface(config, depender)) { - for (std::vector<cmLinkItem>::const_iterator lib = - iface->Libraries.begin(); - lib != iface->Libraries.end(); ++lib) { + for (cmLinkItem const& lib : iface->Libraries) { // Don't emit the same library twice for this target. - if (emitted.insert(*lib).second) { - this->AddTargetDepend(depender_index, *lib, true); - this->AddInterfaceDepends(depender_index, *lib, config, emitted); + if (emitted.insert(lib).second) { + this->AddTargetDepend(depender_index, lib, true); + this->AddInterfaceDepends(depender_index, lib, config, emitted); } } } @@ -365,9 +355,8 @@ void cmComputeTargetDepends::AddTargetDepend(int depender_index, // Skip IMPORTED and INTERFACE targets but follow their utility // dependencies. std::set<cmLinkItem> const& utils = dependee->GetUtilityItems(); - for (std::set<cmLinkItem>::const_iterator i = utils.begin(); - i != utils.end(); ++i) { - if (cmGeneratorTarget const* transitive_dependee = i->Target) { + for (cmLinkItem const& i : utils) { + if (cmGeneratorTarget const* transitive_dependee = i.Target) { this->AddTargetDepend(depender_index, transitive_dependee, false); } } @@ -395,11 +384,11 @@ void cmComputeTargetDepends::DisplayGraph(Graph const& graph, cmGeneratorTarget const* depender = this->Targets[depender_index]; fprintf(stderr, "target %d is [%s]\n", depender_index, depender->GetName().c_str()); - for (EdgeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) { - int dependee_index = *ni; + for (cmGraphEdge const& ni : nl) { + int dependee_index = ni; cmGeneratorTarget const* dependee = this->Targets[dependee_index]; fprintf(stderr, " depends on target %d [%s] (%s)\n", dependee_index, - dependee->GetName().c_str(), ni->IsStrong() ? "strong" : "weak"); + dependee->GetName().c_str(), ni.IsStrong() ? "strong" : "weak"); } } fprintf(stderr, "\n"); @@ -414,8 +403,7 @@ void cmComputeTargetDepends::DisplayComponents( for (int c = 0; c < n; ++c) { NodeList const& nl = components[c]; fprintf(stderr, "Component (%d):\n", c); - for (NodeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) { - int i = *ni; + for (int i : nl) { fprintf(stderr, " contains target %d [%s]\n", i, this->Targets[i]->GetName().c_str()); } @@ -446,8 +434,8 @@ bool cmComputeTargetDepends::CheckComponents( } // Make sure the component is all STATIC_LIBRARY targets. - for (NodeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) { - if (this->Targets[*ni]->GetType() != cmStateEnums::STATIC_LIBRARY) { + for (int ni : nl) { + if (this->Targets[ni]->GetType() != cmStateEnums::STATIC_LIBRARY) { this->ComplainAboutBadComponent(ccg, c); return false; } @@ -466,9 +454,8 @@ void cmComputeTargetDepends::ComplainAboutBadComponent( std::vector<NodeList> const& components = ccg.GetComponents(); std::vector<int> const& cmap = ccg.GetComponentMap(); NodeList const& cl = components[c]; - for (NodeList::const_iterator ci = cl.begin(); ci != cl.end(); ++ci) { + for (int i : cl) { // Get the depender. - int i = *ci; cmGeneratorTarget const* depender = this->Targets[i]; // Describe the depender. @@ -477,12 +464,12 @@ void cmComputeTargetDepends::ComplainAboutBadComponent( // List its dependencies that are inside the component. EdgeList const& nl = this->InitialGraph[i]; - for (EdgeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) { - int j = *ni; + for (cmGraphEdge const& ni : nl) { + int j = ni; if (cmap[j] == c) { cmGeneratorTarget const* dependee = this->Targets[j]; e << " depends on \"" << dependee->GetName() << "\"" - << " (" << (ni->IsStrong() ? "strong" : "weak") << ")\n"; + << " (" << (ni.IsStrong() ? "strong" : "weak") << ")\n"; } } } @@ -514,9 +501,9 @@ bool cmComputeTargetDepends::IntraComponent(std::vector<int> const& cmap, if (emitted.insert(i).second) { // Honor strong intra-component edges in the final order. EdgeList const& el = this->InitialGraph[i]; - for (EdgeList::const_iterator ei = el.begin(); ei != el.end(); ++ei) { - int j = *ei; - if (cmap[j] == c && ei->IsStrong()) { + for (cmGraphEdge const& edge : el) { + int j = edge; + if (cmap[j] == c && edge.IsStrong()) { this->FinalGraph[i].push_back(cmGraphEdge(j, true)); if (!this->IntraComponent(cmap, c, j, head, emitted, visited)) { return false; @@ -573,11 +560,11 @@ bool cmComputeTargetDepends::ComputeFinalDepends( ++depender_component) { int depender_component_tail = this->ComponentTail[depender_component]; EdgeList const& nl = cgraph[depender_component]; - for (EdgeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) { - int dependee_component = *ni; + for (cmGraphEdge const& ni : nl) { + int dependee_component = ni; int dependee_component_head = this->ComponentHead[dependee_component]; this->FinalGraph[depender_component_tail].push_back( - cmGraphEdge(dependee_component_head, ni->IsStrong())); + cmGraphEdge(dependee_component_head, ni.IsStrong())); } } return true; diff --git a/Source/cmConditionEvaluator.cxx b/Source/cmConditionEvaluator.cxx index f4d48d2..90b3f6d 100644 --- a/Source/cmConditionEvaluator.cxx +++ b/Source/cmConditionEvaluator.cxx @@ -83,7 +83,7 @@ bool cmConditionEvaluator::IsTrue( const std::vector<cmExpandedCommandArgument>& args, std::string& errorString, cmake::MessageType& status) { - errorString = ""; + errorString.clear(); // handle empty invocation if (args.empty()) { diff --git a/Source/cmConfigure.cmake.h.in b/Source/cmConfigure.cmake.h.in index e91471c..9d11fff 100644 --- a/Source/cmConfigure.cmake.h.in +++ b/Source/cmConfigure.cmake.h.in @@ -25,7 +25,6 @@ #cmakedefine CMake_HAVE_CXX_GNU_FALLTHROUGH #cmakedefine CMake_HAVE_CXX_ATTRIBUTE_FALLTHROUGH #cmakedefine CMake_HAVE_CXX_MAKE_UNIQUE -#cmakedefine CMake_HAVE_CXX_OVERRIDE #cmakedefine CMake_HAVE_CXX_UNIQUE_PTR #define CMAKE_BIN_DIR "/@CMAKE_BIN_DIR@" #define CMAKE_DATA_DIR "/@CMAKE_DATA_DIR@" @@ -46,12 +45,6 @@ #define CM_FALLTHROUGH #endif -#ifdef CMake_HAVE_CXX_OVERRIDE -#define CM_OVERRIDE override -#else -#define CM_OVERRIDE -#endif - #define CM_DISABLE_COPY(Class) \ Class(Class const&) CM_EQ_DELETE; \ Class& operator=(Class const&) CM_EQ_DELETE; diff --git a/Source/cmConfigureFileCommand.h b/Source/cmConfigureFileCommand.h index 54ca0bf..cff934b 100644 --- a/Source/cmConfigureFileCommand.h +++ b/Source/cmConfigureFileCommand.h @@ -16,14 +16,14 @@ class cmExecutionStatus; class cmConfigureFileCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE { return new cmConfigureFileCommand; } + cmCommand* Clone() override { return new cmConfigureFileCommand; } /** * This is called when the command is first encountered in * the input file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: int ConfigureFile(); diff --git a/Source/cmConnection.cxx b/Source/cmConnection.cxx index f3fc1ef..f482412 100644 --- a/Source/cmConnection.cxx +++ b/Source/cmConnection.cxx @@ -38,11 +38,6 @@ void cmEventBasedConnection::on_read(uv_stream_t* stream, ssize_t nread, delete[](buf->base); } -void cmEventBasedConnection::on_close_delete(uv_handle_t* handle) -{ - delete handle; -} - void cmEventBasedConnection::on_close(uv_handle_t* /*handle*/) { } @@ -72,9 +67,19 @@ bool cmEventBasedConnection::IsOpen() const return this->WriteStream != nullptr; } -void cmEventBasedConnection::WriteData(const std::string& data) +void cmEventBasedConnection::WriteData(const std::string& _data) { +#ifndef NDEBUG + auto curr_thread_id = uv_thread_self(); + assert(this->Server); + assert(uv_thread_equal(&curr_thread_id, &this->Server->ServeThreadId)); +#endif + + auto data = _data; assert(this->WriteStream); + if (BufferStrategy) { + data = BufferStrategy->BufferOutMessage(data); + } auto ds = data.size(); @@ -119,7 +124,9 @@ void cmEventBasedConnection::OnDisconnect(int onerror) { (void)onerror; this->OnConnectionShuttingDown(); - this->Server->OnDisconnect(this); + if (this->Server) { + this->Server->OnDisconnect(this); + } } cmConnection::~cmConnection() @@ -128,6 +135,7 @@ cmConnection::~cmConnection() bool cmConnection::OnConnectionShuttingDown() { + this->Server = nullptr; return true; } @@ -149,9 +157,12 @@ bool cmConnection::OnServeStart(std::string* errString) bool cmEventBasedConnection::OnConnectionShuttingDown() { - this->WriteStream->data = nullptr; - this->ReadStream->data = nullptr; - + if (this->WriteStream) { + this->WriteStream->data = nullptr; + } + if (this->ReadStream) { + this->ReadStream->data = nullptr; + } this->ReadStream = nullptr; this->WriteStream = nullptr; return true; diff --git a/Source/cmConnection.h b/Source/cmConnection.h index f9d50de..ddb7744 100644 --- a/Source/cmConnection.h +++ b/Source/cmConnection.h @@ -39,6 +39,17 @@ public: virtual std::string BufferMessage(std::string& rawBuffer) = 0; /*** + * Called to properly buffer an outgoing message. + * + * @param rawBuffer Message to format in the correct way + * + * @return Formatted message + */ + virtual std::string BufferOutMessage(const std::string& rawBuffer) const + { + return rawBuffer; + }; + /*** * Resets the internal state of the buffering */ virtual void clear(); @@ -100,7 +111,12 @@ public: uv_stream_t* WriteStream = nullptr; static void on_close(uv_handle_t* handle); - static void on_close_delete(uv_handle_t* handle); + + template <typename T> + static void on_close_delete(uv_handle_t* handle) + { + delete reinterpret_cast<T*>(handle); + } protected: std::string RawReadBuffer; diff --git a/Source/cmContinueCommand.h b/Source/cmContinueCommand.h index 51f991d..d383d1d 100644 --- a/Source/cmContinueCommand.h +++ b/Source/cmContinueCommand.h @@ -23,14 +23,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmContinueCommand; } + cmCommand* Clone() override { return new cmContinueCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmCoreTryCompile.cxx b/Source/cmCoreTryCompile.cxx index 86f5282..fd258fe 100644 --- a/Source/cmCoreTryCompile.cxx +++ b/Source/cmCoreTryCompile.cxx @@ -71,7 +71,7 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv, bool isTryRun) { this->BinaryDirectory = argv[1]; - this->OutputFile = ""; + this->OutputFile.clear(); // which signature were we called with ? this->SrcFileSignature = true; @@ -417,16 +417,15 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv, // Detect languages to enable. cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator(); std::set<std::string> testLangs; - for (std::vector<std::string>::iterator si = sources.begin(); - si != sources.end(); ++si) { - std::string ext = cmSystemTools::GetFilenameLastExtension(*si); + for (std::string const& si : sources) { + std::string ext = cmSystemTools::GetFilenameLastExtension(si); std::string lang = gg->GetLanguageFromExtension(ext.c_str()); if (!lang.empty()) { testLangs.insert(lang); } else { std::ostringstream err; err << "Unknown extension \"" << ext << "\" for file\n" - << " " << *si << "\n" + << " " << si << "\n" << "try_compile() works only for enabled languages. " << "Currently these are:\n "; std::vector<std::string> langs; @@ -467,11 +466,10 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv, } std::string projectLangs; - for (std::set<std::string>::iterator li = testLangs.begin(); - li != testLangs.end(); ++li) { - projectLangs += " " + *li; + for (std::string const& li : testLangs) { + projectLangs += " " + li; std::string rulesOverrideBase = "CMAKE_USER_MAKE_RULES_OVERRIDE"; - std::string rulesOverrideLang = rulesOverrideBase + "_" + *li; + std::string rulesOverrideLang = rulesOverrideBase + "_" + li; if (const char* rulesOverridePath = this->Makefile->GetDefinition(rulesOverrideLang)) { fprintf(fout, "set(%s \"%s\")\n", rulesOverrideLang.c_str(), @@ -484,15 +482,14 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv, } fprintf(fout, "project(CMAKE_TRY_COMPILE%s)\n", projectLangs.c_str()); fprintf(fout, "set(CMAKE_VERBOSE_MAKEFILE 1)\n"); - for (std::set<std::string>::iterator li = testLangs.begin(); - li != testLangs.end(); ++li) { - std::string langFlags = "CMAKE_" + *li + "_FLAGS"; + for (std::string const& li : testLangs) { + std::string langFlags = "CMAKE_" + li + "_FLAGS"; const char* flags = this->Makefile->GetDefinition(langFlags); - fprintf(fout, "set(CMAKE_%s_FLAGS %s)\n", li->c_str(), + fprintf(fout, "set(CMAKE_%s_FLAGS %s)\n", li.c_str(), cmOutputConverter::EscapeForCMake(flags ? flags : "").c_str()); fprintf(fout, "set(CMAKE_%s_FLAGS \"${CMAKE_%s_FLAGS}" " ${COMPILE_DEFINITIONS}\")\n", - li->c_str(), li->c_str()); + li.c_str(), li.c_str()); } switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0066)) { case cmPolicies::WARN: @@ -522,9 +519,8 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv, static std::string const cfgDefault = "DEBUG"; std::string const cfg = !tcConfig.empty() ? cmSystemTools::UpperCase(tcConfig) : cfgDefault; - for (std::set<std::string>::iterator li = testLangs.begin(); - li != testLangs.end(); ++li) { - std::string const langFlagsCfg = "CMAKE_" + *li + "_FLAGS_" + cfg; + for (std::string const& li : testLangs) { + std::string const langFlagsCfg = "CMAKE_" + li + "_FLAGS_" + cfg; const char* flagsCfg = this->Makefile->GetDefinition(langFlagsCfg); fprintf(fout, "set(%s %s)\n", langFlagsCfg.c_str(), cmOutputConverter::EscapeForCMake(flagsCfg ? flagsCfg : "") @@ -638,9 +634,7 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv, cmakeFlags.push_back(flag); } - for (std::set<std::string>::iterator vi = vars.begin(); vi != vars.end(); - ++vi) { - std::string const& var = *vi; + for (std::string const& var : vars) { if (const char* val = this->Makefile->GetDefinition(var)) { std::string flag = "-D" + var + "=" + val; cmakeFlags.push_back(flag); @@ -669,13 +663,12 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv, /* Create the actual static library. */ fprintf(fout, "add_library(%s STATIC", targetName.c_str()); } - for (std::vector<std::string>::iterator si = sources.begin(); - si != sources.end(); ++si) { - fprintf(fout, " \"%s\"", si->c_str()); + for (std::string const& si : sources) { + fprintf(fout, " \"%s\"", si.c_str()); // Add dependencies on any non-temporary sources. - if (si->find("CMakeTmp") == std::string::npos) { - this->Makefile->AddCMakeDependFile(*si); + if (si.find("CMakeTmp") == std::string::npos) { + this->Makefile->AddCMakeDependFile(si); } } fprintf(fout, ")\n"); @@ -762,9 +755,8 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv, "is not honoring language standard variables in the test project:\n" ; /* clang-format on */ - for (std::vector<std::string>::iterator vi = this->WarnCMP0067.begin(); - vi != this->WarnCMP0067.end(); ++vi) { - w << " " << *vi << "\n"; + for (std::string const& vi : this->WarnCMP0067) { + w << " " << vi << "\n"; } this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, w.str()); } @@ -927,8 +919,8 @@ void cmCoreTryCompile::CleanupFiles(const char* binDir) void cmCoreTryCompile::FindOutputFile(const std::string& targetName, cmStateEnums::TargetType targetType) { - this->FindErrorMessage = ""; - this->OutputFile = ""; + this->FindErrorMessage.clear(); + this->OutputFile.clear(); std::string tmpOutputFile = "/"; if (targetType == cmStateEnums::EXECUTABLE) { tmpOutputFile += targetName; @@ -963,10 +955,9 @@ void cmCoreTryCompile::FindOutputFile(const std::string& targetName, #endif searchDirs.push_back("/Development"); - for (std::vector<std::string>::const_iterator it = searchDirs.begin(); - it != searchDirs.end(); ++it) { + for (std::string const& sdir : searchDirs) { std::string command = this->BinaryDirectory; - command += *it; + command += sdir; command += tmpOutputFile; if (cmSystemTools::FileExists(command.c_str())) { this->OutputFile = cmSystemTools::CollapseFullPath(command); diff --git a/Source/cmCreateTestSourceList.h b/Source/cmCreateTestSourceList.h index 47fb610..005b32c 100644 --- a/Source/cmCreateTestSourceList.h +++ b/Source/cmCreateTestSourceList.h @@ -23,14 +23,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmCreateTestSourceList; } + cmCommand* Clone() override { return new cmCreateTestSourceList; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmCryptoHash.cxx b/Source/cmCryptoHash.cxx index 623c5e0..d914eb1 100644 --- a/Source/cmCryptoHash.cxx +++ b/Source/cmCryptoHash.cxx @@ -2,11 +2,14 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmCryptoHash.h" +#include "cmAlgorithms.h" #include "cm_kwiml.h" #include "cm_rhash.h" #include "cmsys/FStream.hxx" #include <string.h> +#include <memory> // IWYU pragma: keep + static unsigned int const cmCryptoHashAlgoToId[] = { /* clang-format needs this comment to break after the opening brace */ RHASH_MD5, // @@ -43,39 +46,39 @@ cmCryptoHash::~cmCryptoHash() rhash_free(this->CTX); } -CM_AUTO_PTR<cmCryptoHash> cmCryptoHash::New(const char* algo) +std::unique_ptr<cmCryptoHash> cmCryptoHash::New(const char* algo) { if (strcmp(algo, "MD5") == 0) { - return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoMD5)); + return cm::make_unique<cmCryptoHash>(AlgoMD5); } if (strcmp(algo, "SHA1") == 0) { - return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA1)); + return cm::make_unique<cmCryptoHash>(AlgoSHA1); } if (strcmp(algo, "SHA224") == 0) { - return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA224)); + return cm::make_unique<cmCryptoHash>(AlgoSHA224); } if (strcmp(algo, "SHA256") == 0) { - return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA256)); + return cm::make_unique<cmCryptoHash>(AlgoSHA256); } if (strcmp(algo, "SHA384") == 0) { - return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA384)); + return cm::make_unique<cmCryptoHash>(AlgoSHA384); } if (strcmp(algo, "SHA512") == 0) { - return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA512)); + return cm::make_unique<cmCryptoHash>(AlgoSHA512); } if (strcmp(algo, "SHA3_224") == 0) { - return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA3_224)); + return cm::make_unique<cmCryptoHash>(AlgoSHA3_224); } if (strcmp(algo, "SHA3_256") == 0) { - return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA3_256)); + return cm::make_unique<cmCryptoHash>(AlgoSHA3_256); } if (strcmp(algo, "SHA3_384") == 0) { - return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA3_384)); + return cm::make_unique<cmCryptoHash>(AlgoSHA3_384); } if (strcmp(algo, "SHA3_512") == 0) { - return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA3_512)); + return cm::make_unique<cmCryptoHash>(AlgoSHA3_512); } - return CM_AUTO_PTR<cmCryptoHash>(nullptr); + return std::unique_ptr<cmCryptoHash>(nullptr); } bool cmCryptoHash::IntFromHexDigit(char input, char& output) @@ -103,10 +106,9 @@ std::string cmCryptoHash::ByteHashToString( '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; std::string res; - for (std::vector<unsigned char>::const_iterator vit = hash.begin(); - vit != hash.end(); ++vit) { - res.push_back(hex[(*vit) >> 4]); - res.push_back(hex[(*vit) & 0xF]); + for (unsigned char v : hash) { + res.push_back(hex[v >> 4]); + res.push_back(hex[v & 0xF]); } return res; } diff --git a/Source/cmCryptoHash.h b/Source/cmCryptoHash.h index 9c13968..1f2a1b5 100644 --- a/Source/cmCryptoHash.h +++ b/Source/cmCryptoHash.h @@ -5,12 +5,11 @@ #include "cmConfigure.h" // IWYU pragma: keep +#include <memory> // IWYU pragma: keep #include <stddef.h> #include <string> #include <vector> -#include "cm_auto_ptr.hxx" - /** * @brief Abstract base class for cryptographic hash generators */ @@ -42,7 +41,7 @@ public: /// SHA3_224, SHA3_256, SHA3_384, SHA3_512 /// @return A valid auto pointer if algo is supported or /// an invalid/NULL pointer otherwise - static CM_AUTO_PTR<cmCryptoHash> New(const char* algo); + static std::unique_ptr<cmCryptoHash> New(const char* algo); /// @brief Converts a hex character to its binary value (4 bits) /// @arg input Hex character [0-9a-fA-F]. diff --git a/Source/cmCustomCommandGenerator.cxx b/Source/cmCustomCommandGenerator.cxx index fdc0a97..3d816d5 100644 --- a/Source/cmCustomCommandGenerator.cxx +++ b/Source/cmCustomCommandGenerator.cxx @@ -11,7 +11,9 @@ #include "cmOutputConverter.h" #include "cmStateTypes.h" #include "cmSystemTools.h" -#include "cm_auto_ptr.hxx" + +#include <memory> // IWYU pragma: keep +#include <stddef.h> cmCustomCommandGenerator::cmCustomCommandGenerator(cmCustomCommand const& cc, const std::string& config, @@ -24,12 +26,11 @@ cmCustomCommandGenerator::cmCustomCommandGenerator(cmCustomCommand const& cc, , GE(new cmGeneratorExpression(cc.GetBacktrace())) { const cmCustomCommandLines& cmdlines = this->CC.GetCommandLines(); - for (cmCustomCommandLines::const_iterator cmdline = cmdlines.begin(); - cmdline != cmdlines.end(); ++cmdline) { + for (cmCustomCommandLine const& cmdline : cmdlines) { cmCustomCommandLine argv; - for (cmCustomCommandLine::const_iterator clarg = cmdline->begin(); - clarg != cmdline->end(); ++clarg) { - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = this->GE->Parse(*clarg); + for (std::string const& clarg : cmdline) { + std::unique_ptr<cmCompiledGeneratorExpression> cge = + this->GE->Parse(clarg); std::string parsed_arg = cge->Evaluate(this->LG, this->Config); if (this->CC.GetCommandExpandLists()) { std::vector<std::string> ExpandedArg; @@ -43,16 +44,14 @@ cmCustomCommandGenerator::cmCustomCommandGenerator(cmCustomCommand const& cc, } std::vector<std::string> depends = this->CC.GetDepends(); - for (std::vector<std::string>::const_iterator i = depends.begin(); - i != depends.end(); ++i) { - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = this->GE->Parse(*i); + for (std::string const& d : depends) { + std::unique_ptr<cmCompiledGeneratorExpression> cge = this->GE->Parse(d); std::vector<std::string> result; cmSystemTools::ExpandListArgument(cge->Evaluate(this->LG, this->Config), result); - for (std::vector<std::string>::iterator it = result.begin(); - it != result.end(); ++it) { - if (cmSystemTools::FileIsFullPath(it->c_str())) { - *it = cmSystemTools::CollapseFullPath(*it); + for (std::string& it : result) { + if (cmSystemTools::FileIsFullPath(it.c_str())) { + it = cmSystemTools::CollapseFullPath(it); } } this->Depends.insert(this->Depends.end(), result.begin(), result.end()); @@ -97,6 +96,18 @@ const char* cmCustomCommandGenerator::GetArgv0Location(unsigned int c) const return nullptr; } +bool cmCustomCommandGenerator::HasOnlyEmptyCommandLines() const +{ + for (size_t i = 0; i < this->CommandLines.size(); ++i) { + for (size_t j = 0; j < this->CommandLines[i].size(); ++j) { + if (!this->CommandLines[i][j].empty()) { + return false; + } + } + } + return true; +} + std::string cmCustomCommandGenerator::GetCommand(unsigned int c) const { if (const char* emulator = this->GetCrossCompilingEmulator(c)) { diff --git a/Source/cmCustomCommandGenerator.h b/Source/cmCustomCommandGenerator.h index ea33b51..34fd653 100644 --- a/Source/cmCustomCommandGenerator.h +++ b/Source/cmCustomCommandGenerator.h @@ -40,6 +40,7 @@ public: std::vector<std::string> const& GetOutputs() const; std::vector<std::string> const& GetByproducts() const; std::vector<std::string> const& GetDepends() const; + bool HasOnlyEmptyCommandLines() const; }; #endif diff --git a/Source/cmDefinePropertyCommand.h b/Source/cmDefinePropertyCommand.h index 43f6c58..a9c1856 100644 --- a/Source/cmDefinePropertyCommand.h +++ b/Source/cmDefinePropertyCommand.h @@ -15,14 +15,14 @@ class cmExecutionStatus; class cmDefinePropertyCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE { return new cmDefinePropertyCommand; } + cmCommand* Clone() override { return new cmDefinePropertyCommand; } /** * This is called when the command is first encountered in * the input file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: std::string PropertyName; diff --git a/Source/cmDefinitions.cxx b/Source/cmDefinitions.cxx index 021f2e8..e766854 100644 --- a/Source/cmDefinitions.cxx +++ b/Source/cmDefinitions.cxx @@ -66,10 +66,9 @@ std::vector<std::string> cmDefinitions::UnusedKeys() const std::vector<std::string> keys; keys.reserve(this->Map.size()); // Consider local definitions. - for (MapType::const_iterator mi = this->Map.begin(); mi != this->Map.end(); - ++mi) { - if (!mi->second.Used) { - keys.push_back(mi->first); + for (auto const& mi : this->Map) { + if (!mi.second.Used) { + keys.push_back(mi.first); } } return keys; @@ -81,15 +80,14 @@ cmDefinitions cmDefinitions::MakeClosure(StackIter begin, StackIter end) std::set<std::string> undefined; for (StackIter it = begin; it != end; ++it) { // Consider local definitions. - for (MapType::const_iterator mi = it->Map.begin(); mi != it->Map.end(); - ++mi) { + for (auto const& mi : it->Map) { // Use this key if it is not already set or unset. - if (closure.Map.find(mi->first) == closure.Map.end() && - undefined.find(mi->first) == undefined.end()) { - if (mi->second.Exists) { - closure.Map.insert(*mi); + if (closure.Map.find(mi.first) == closure.Map.end() && + undefined.find(mi.first) == undefined.end()) { + if (mi.second.Exists) { + closure.Map.insert(mi); } else { - undefined.insert(mi->first); + undefined.insert(mi.first); } } } @@ -105,11 +103,10 @@ std::vector<std::string> cmDefinitions::ClosureKeys(StackIter begin, for (StackIter it = begin; it != end; ++it) { defined.reserve(defined.size() + it->Map.size()); - for (MapType::const_iterator mi = it->Map.begin(); mi != it->Map.end(); - ++mi) { + for (auto const& mi : it->Map) { // Use this key if it is not already set or unset. - if (bound.insert(mi->first).second && mi->second.Exists) { - defined.push_back(mi->first); + if (bound.insert(mi.first).second && mi.second.Exists) { + defined.push_back(mi.first); } } } diff --git a/Source/cmDepends.cxx b/Source/cmDepends.cxx index a0775b3..cdab671 100644 --- a/Source/cmDepends.cxx +++ b/Source/cmDepends.cxx @@ -42,7 +42,7 @@ bool cmDepends::Write(std::ostream& makeDepends, std::ostream& internalDepends) std::vector<std::string> pairs; cmSystemTools::ExpandListArgument(srcStr, pairs); - std::map<std::string, std::set<std::string> > dependencies; + std::map<std::string, std::set<std::string>> dependencies; for (std::vector<std::string>::iterator si = pairs.begin(); si != pairs.end();) { // Get the source and object file. @@ -53,12 +53,10 @@ bool cmDepends::Write(std::ostream& makeDepends, std::ostream& internalDepends) std::string const& obj = *si++; dependencies[obj].insert(src); } - for (std::map<std::string, std::set<std::string> >::const_iterator it = - dependencies.begin(); - it != dependencies.end(); ++it) { + for (auto const& d : dependencies) { // Write the dependencies for this pair. - if (!this->WriteDependencies(it->second, it->first, makeDepends, + if (!this->WriteDependencies(d.second, d.first, makeDepends, internalDepends)) { return false; } diff --git a/Source/cmDependsC.cxx b/Source/cmDependsC.cxx index 588a78c..1ab3fa2 100644 --- a/Source/cmDependsC.cxx +++ b/Source/cmDependsC.cxx @@ -110,12 +110,11 @@ bool cmDependsC::WriteDependencies(const std::set<std::string>& sources, int srcFiles = static_cast<int>(sources.size()); this->Encountered.clear(); - for (std::set<std::string>::const_iterator srcIt = sources.begin(); - srcIt != sources.end(); ++srcIt) { + for (std::string const& src : sources) { UnscannedEntry root; - root.FileName = *srcIt; + root.FileName = src; this->Unscanned.push(root); - this->Encountered.insert(*srcIt); + this->Encountered.insert(src); } std::set<std::string> scanned; @@ -150,14 +149,12 @@ bool cmDependsC::WriteDependencies(const std::set<std::string>& sources, if (headerLocationIt != this->HeaderLocationCache.end()) { fullName = headerLocationIt->second; } else { - for (std::vector<std::string>::const_iterator i = - this->IncludePath.begin(); - i != this->IncludePath.end(); ++i) { + for (std::string const& i : this->IncludePath) { // Construct the name of the file as if it were in the current // include directory. Avoid using a leading "./". tempPathStr = - cmSystemTools::CollapseCombinedPath(*i, current.FileName); + cmSystemTools::CollapseCombinedPath(i, current.FileName); // Look for the file in this location. if (cmSystemTools::FileExists(tempPathStr.c_str(), true)) { @@ -189,13 +186,11 @@ bool cmDependsC::WriteDependencies(const std::set<std::string>& sources, if (fileIt != this->FileCache.end()) { fileIt->second->Used = true; dependencies.insert(fullName); - for (std::vector<UnscannedEntry>::const_iterator incIt = - fileIt->second->UnscannedEntries.begin(); - incIt != fileIt->second->UnscannedEntries.end(); ++incIt) { - if (this->Encountered.find(incIt->FileName) == + for (UnscannedEntry const& inc : fileIt->second->UnscannedEntries) { + if (this->Encountered.find(inc.FileName) == this->Encountered.end()) { - this->Encountered.insert(incIt->FileName); - this->Unscanned.push(*incIt); + this->Encountered.insert(inc.FileName); + this->Unscanned.push(inc); } } } else { @@ -234,14 +229,13 @@ bool cmDependsC::WriteDependencies(const std::set<std::string>& sources, std::string obj_m = cmSystemTools::ConvertToOutputPath(obj_i.c_str()); internalDepends << obj_i << std::endl; - for (std::set<std::string>::const_iterator i = dependencies.begin(); - i != dependencies.end(); ++i) { + for (std::string const& dep : dependencies) { makeDepends << obj_m << ": " << cmSystemTools::ConvertToOutputPath( - this->LocalGenerator->ConvertToRelativePath(binDir, *i).c_str()) + this->LocalGenerator->ConvertToRelativePath(binDir, dep).c_str()) << std::endl; - internalDepends << " " << *i << std::endl; + internalDepends << " " << dep << std::endl; } makeDepends << std::endl; @@ -330,20 +324,16 @@ void cmDependsC::WriteCacheFile() const cacheOut << this->IncludeRegexComplainString << "\n\n"; cacheOut << this->IncludeRegexTransformString << "\n\n"; - for (std::map<std::string, cmIncludeLines*>::const_iterator fileIt = - this->FileCache.begin(); - fileIt != this->FileCache.end(); ++fileIt) { - if (fileIt->second->Used) { - cacheOut << fileIt->first << std::endl; - - for (std::vector<UnscannedEntry>::const_iterator incIt = - fileIt->second->UnscannedEntries.begin(); - incIt != fileIt->second->UnscannedEntries.end(); ++incIt) { - cacheOut << incIt->FileName << std::endl; - if (incIt->QuotedLocation.empty()) { + for (auto const& fileIt : this->FileCache) { + if (fileIt.second->Used) { + cacheOut << fileIt.first << std::endl; + + for (UnscannedEntry const& inc : fileIt.second->UnscannedEntries) { + cacheOut << inc.FileName << std::endl; + if (inc.QuotedLocation.empty()) { cacheOut << "-" << std::endl; } else { - cacheOut << incIt->QuotedLocation << std::endl; + cacheOut << inc.QuotedLocation << std::endl; } } cacheOut << std::endl; @@ -411,9 +401,8 @@ void cmDependsC::SetupTransforms() if (const char* xform = mf->GetDefinition("CMAKE_INCLUDE_TRANSFORMS")) { cmSystemTools::ExpandListArgument(xform, transformRules, true); } - for (std::vector<std::string>::const_iterator tri = transformRules.begin(); - tri != transformRules.end(); ++tri) { - this->ParseTransform(*tri); + for (std::string const& tr : transformRules) { + this->ParseTransform(tr); } this->IncludeRegexTransformString = INCLUDE_REGEX_TRANSFORM_MARKER; @@ -422,10 +411,9 @@ void cmDependsC::SetupTransforms() // transformed. std::string xform = "^([ \t]*[#%][ \t]*(include|import)[ \t]*)("; const char* sep = ""; - for (TransformRulesType::const_iterator tri = this->TransformRules.begin(); - tri != this->TransformRules.end(); ++tri) { + for (auto const& tr : this->TransformRules) { xform += sep; - xform += tri->first; + xform += tr.first; sep = "|"; } xform += ")[ \t]*\\(([^),]*)\\)"; @@ -434,12 +422,11 @@ void cmDependsC::SetupTransforms() // Build a string that encodes all transformation rules and will // change when rules are changed. this->IncludeRegexTransformString += xform; - for (TransformRulesType::const_iterator tri = this->TransformRules.begin(); - tri != this->TransformRules.end(); ++tri) { + for (auto const& tr : this->TransformRules) { this->IncludeRegexTransformString += " "; - this->IncludeRegexTransformString += tri->first; + this->IncludeRegexTransformString += tr.first; this->IncludeRegexTransformString += "(%)="; - this->IncludeRegexTransformString += tri->second; + this->IncludeRegexTransformString += tr.second; } } } diff --git a/Source/cmDependsC.h b/Source/cmDependsC.h index 7780ccf..2f76f62 100644 --- a/Source/cmDependsC.h +++ b/Source/cmDependsC.h @@ -33,13 +33,13 @@ public: const std::map<std::string, DependencyVector>* validDeps); /** Virtual destructor to cleanup subclasses properly. */ - ~cmDependsC() CM_OVERRIDE; + ~cmDependsC() override; protected: // Implement writing/checking methods required by superclass. bool WriteDependencies(const std::set<std::string>& sources, const std::string& obj, std::ostream& makeDepends, - std::ostream& internalDepends) CM_OVERRIDE; + std::ostream& internalDepends) override; // Method to scan a single file. void Scan(std::istream& is, const char* directory, diff --git a/Source/cmDependsFortran.cxx b/Source/cmDependsFortran.cxx index e149a19..fdbc086 100644 --- a/Source/cmDependsFortran.cxx +++ b/Source/cmDependsFortran.cxx @@ -73,12 +73,10 @@ cmDependsFortran::cmDependsFortran(cmLocalGenerator* lg) // translate i.e. FOO=BAR to FOO and add it to the list of defined // preprocessor symbols - for (std::vector<std::string>::const_iterator it = definitions.begin(); - it != definitions.end(); ++it) { - std::string def = *it; + for (std::string def : definitions) { std::string::size_type assignment = def.find('='); if (assignment != std::string::npos) { - def = it->substr(0, assignment); + def = def.substr(0, assignment); } this->PPDefinitions.insert(def); } @@ -105,9 +103,7 @@ bool cmDependsFortran::WriteDependencies(const std::set<std::string>& sources, } bool okay = true; - for (std::set<std::string>::const_iterator it = sources.begin(); - it != sources.end(); ++it) { - const std::string& src = *it; + for (std::string const& src : sources) { // Get the information object for this source. cmFortranSourceInfo& info = this->Internal->CreateObjectInfo(obj.c_str(), src.c_str()); @@ -154,9 +150,8 @@ bool cmDependsFortran::Finalize(std::ostream& makeDepends, // Actually write dependencies to the streams. typedef cmDependsFortranInternals::ObjectInfoMap ObjectInfoMap; ObjectInfoMap const& objInfo = this->Internal->ObjectInfo; - for (ObjectInfoMap::const_iterator i = objInfo.begin(); i != objInfo.end(); - ++i) { - if (!this->WriteDependenciesReal(i->first.c_str(), i->second, mod_dir, + for (auto const& i : objInfo) { + if (!this->WriteDependenciesReal(i.first.c_str(), i.second, mod_dir, stamp_dir, makeDepends, internalDepends)) { return false; @@ -170,9 +165,8 @@ bool cmDependsFortran::Finalize(std::ostream& makeDepends, fiStream << "# The fortran modules provided by this target.\n"; fiStream << "provides\n"; std::set<std::string> const& provides = this->Internal->TargetProvides; - for (std::set<std::string>::const_iterator i = provides.begin(); - i != provides.end(); ++i) { - fiStream << " " << *i << "\n"; + for (std::string const& i : provides) { + fiStream << " " << i << "\n"; } // Create a script to clean the modules. @@ -184,19 +178,18 @@ bool cmDependsFortran::Finalize(std::ostream& makeDepends, fcStream << "FILE(REMOVE"; std::string currentBinDir = this->LocalGenerator->GetCurrentBinaryDirectory(); - for (std::set<std::string>::const_iterator i = provides.begin(); - i != provides.end(); ++i) { + for (std::string const& i : provides) { std::string mod_upper = mod_dir; mod_upper += "/"; - mod_upper += cmSystemTools::UpperCase(*i); + mod_upper += cmSystemTools::UpperCase(i); mod_upper += ".mod"; std::string mod_lower = mod_dir; mod_lower += "/"; - mod_lower += *i; + mod_lower += i; mod_lower += ".mod"; std::string stamp = stamp_dir; stamp += "/"; - stamp += *i; + stamp += i; stamp += ".mod.stamp"; fcStream << "\n"; fcStream << " \"" @@ -219,16 +212,14 @@ void cmDependsFortran::LocateModules() // Collect the set of modules provided and required by all sources. typedef cmDependsFortranInternals::ObjectInfoMap ObjectInfoMap; ObjectInfoMap const& objInfo = this->Internal->ObjectInfo; - for (ObjectInfoMap::const_iterator infoI = objInfo.begin(); - infoI != objInfo.end(); ++infoI) { - cmFortranSourceInfo const& info = infoI->second; + for (auto const& infoI : objInfo) { + cmFortranSourceInfo const& info = infoI.second; // Include this module in the set provided by this target. this->Internal->TargetProvides.insert(info.Provides.begin(), info.Provides.end()); - for (std::set<std::string>::const_iterator i = info.Requires.begin(); - i != info.Requires.end(); ++i) { - this->Internal->TargetRequires[*i] = ""; + for (std::string const& r : info.Requires) { + this->Internal->TargetRequires[r].clear(); } } @@ -247,9 +238,8 @@ void cmDependsFortran::LocateModules() mf->GetDefinition("CMAKE_TARGET_LINKED_INFO_FILES")) { cmSystemTools::ExpandListArgument(infoFilesValue, infoFiles); } - for (std::vector<std::string>::const_iterator i = infoFiles.begin(); - i != infoFiles.end(); ++i) { - std::string targetDir = cmSystemTools::GetFilenamePath(*i); + for (std::string const& i : infoFiles) { + std::string targetDir = cmSystemTools::GetFilenamePath(i); std::string fname = targetDir + "/fortran.internal"; cmsys::ifstream fin(fname.c_str()); if (fin) { @@ -262,9 +252,8 @@ void cmDependsFortran::MatchLocalModules() { const char* stampDir = this->TargetDirectory.c_str(); std::set<std::string> const& provides = this->Internal->TargetProvides; - for (std::set<std::string>::const_iterator i = provides.begin(); - i != provides.end(); ++i) { - this->ConsiderModule(i->c_str(), stampDir); + for (std::string const& i : provides) { + this->ConsiderModule(i.c_str(), stampDir); } } @@ -326,35 +315,32 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj, std::string obj_m = cmSystemTools::ConvertToOutputPath(obj_i.c_str()); internalDepends << obj_i << std::endl; internalDepends << " " << src << std::endl; - for (std::set<std::string>::const_iterator i = info.Includes.begin(); - i != info.Includes.end(); ++i) { + for (std::string const& i : info.Includes) { makeDepends << obj_m << ": " << cmSystemTools::ConvertToOutputPath( - this->MaybeConvertToRelativePath(binDir, *i).c_str()) + this->MaybeConvertToRelativePath(binDir, i).c_str()) << std::endl; - internalDepends << " " << *i << std::endl; + internalDepends << " " << i << std::endl; } makeDepends << std::endl; // Write module requirements to the output stream. - for (std::set<std::string>::const_iterator i = info.Requires.begin(); - i != info.Requires.end(); ++i) { + for (std::string const& i : info.Requires) { // Require only modules not provided in the same source. - if (std::set<std::string>::const_iterator(info.Provides.find(*i)) != - info.Provides.end()) { + if (info.Provides.find(i) != info.Provides.cend()) { continue; } // If the module is provided in this target special handling is // needed. - if (this->Internal->TargetProvides.find(*i) != + if (this->Internal->TargetProvides.find(i) != this->Internal->TargetProvides.end()) { // The module is provided by a different source in the same // target. Add the proxy dependency to make sure the other // source builds first. std::string proxy = stamp_dir; proxy += "/"; - proxy += *i; + proxy += i; proxy += ".mod.proxy"; proxy = cmSystemTools::ConvertToOutputPath( this->MaybeConvertToRelativePath(binDir, proxy).c_str()); @@ -366,7 +352,7 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj, // The object file should depend on timestamped files for the // modules it uses. TargetRequiresMap::const_iterator required = - this->Internal->TargetRequires.find(*i); + this->Internal->TargetRequires.find(i); if (required == this->Internal->TargetRequires.end()) { abort(); } @@ -379,7 +365,7 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj, // This module is not known to CMake. Try to locate it where // the compiler will and depend on that. std::string module; - if (this->FindModule(*i, module)) { + if (this->FindModule(i, module)) { module = cmSystemTools::ConvertToOutputPath( this->MaybeConvertToRelativePath(binDir, module).c_str()); makeDepends << obj_m << ": " << module << "\n"; @@ -388,11 +374,10 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj, } // Write provided modules to the output stream. - for (std::set<std::string>::const_iterator i = info.Provides.begin(); - i != info.Provides.end(); ++i) { + for (std::string const& i : info.Provides) { std::string proxy = stamp_dir; proxy += "/"; - proxy += *i; + proxy += i; proxy += ".mod.proxy"; proxy = cmSystemTools::ConvertToOutputPath( this->MaybeConvertToRelativePath(binDir, proxy).c_str()); @@ -404,18 +389,17 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj, // Create a target to copy the module after the object file // changes. makeDepends << obj_m << ".provides.build:\n"; - for (std::set<std::string>::const_iterator i = info.Provides.begin(); - i != info.Provides.end(); ++i) { + for (std::string const& i : info.Provides) { // Include this module in the set provided by this target. - this->Internal->TargetProvides.insert(*i); + this->Internal->TargetProvides.insert(i); // Always use lower case for the mod stamp file name. The // cmake_copy_f90_mod will call back to this class, which will // try various cases for the real mod file name. - std::string m = cmSystemTools::LowerCase(*i); + std::string m = cmSystemTools::LowerCase(i); std::string modFile = mod_dir; modFile += "/"; - modFile += *i; + modFile += i; modFile = this->LocalGenerator->ConvertToOutputFormat( this->MaybeConvertToRelativePath(binDir, modFile), cmOutputConverter::SHELL); @@ -462,10 +446,9 @@ bool cmDependsFortran::FindModule(std::string const& name, std::string& module) // Search the include path for the module. std::string fullName; - for (std::vector<std::string>::const_iterator i = this->IncludePath.begin(); - i != this->IncludePath.end(); ++i) { + for (std::string const& ip : this->IncludePath) { // Try the lower-case name. - fullName = *i; + fullName = ip; fullName += "/"; fullName += mod_lower; if (cmSystemTools::FileExists(fullName.c_str(), true)) { @@ -474,7 +457,7 @@ bool cmDependsFortran::FindModule(std::string const& name, std::string& module) } // Try the upper-case name. - fullName = *i; + fullName = ip; fullName += "/"; fullName += mod_upper; if (cmSystemTools::FileExists(fullName.c_str(), true)) { diff --git a/Source/cmDependsFortran.h b/Source/cmDependsFortran.h index 42879f1..ccf267b 100644 --- a/Source/cmDependsFortran.h +++ b/Source/cmDependsFortran.h @@ -35,7 +35,7 @@ public: cmDependsFortran(cmLocalGenerator* lg); /** Virtual destructor to cleanup subclasses properly. */ - ~cmDependsFortran() CM_OVERRIDE; + ~cmDependsFortran() override; /** Callback from build system after a .mod file has been generated by a Fortran90 compiler to copy the .mod file to the @@ -50,7 +50,7 @@ public: protected: // Finalize the dependency information for the target. bool Finalize(std::ostream& makeDepends, - std::ostream& internalDepends) CM_OVERRIDE; + std::ostream& internalDepends) override; // Find all the modules required by the target. void LocateModules(); @@ -62,7 +62,7 @@ protected: // Implement writing/checking methods required by superclass. bool WriteDependencies(const std::set<std::string>& sources, const std::string& file, std::ostream& makeDepends, - std::ostream& internalDepends) CM_OVERRIDE; + std::ostream& internalDepends) override; // Actually write the depenencies to the streams. bool WriteDependenciesReal(const char* obj, cmFortranSourceInfo const& info, diff --git a/Source/cmDependsJava.h b/Source/cmDependsJava.h index 4fd5960..d070840 100644 --- a/Source/cmDependsJava.h +++ b/Source/cmDependsJava.h @@ -25,16 +25,16 @@ public: cmDependsJava(); /** Virtual destructor to cleanup subclasses properly. */ - ~cmDependsJava() CM_OVERRIDE; + ~cmDependsJava() override; protected: // Implement writing/checking methods required by superclass. bool WriteDependencies(const std::set<std::string>& sources, const std::string& file, std::ostream& makeDepends, - std::ostream& internalDepends) CM_OVERRIDE; + std::ostream& internalDepends) override; bool CheckDependencies( std::istream& internalDepends, const char* internalDependsFileName, - std::map<std::string, DependencyVector>& validDeps) CM_OVERRIDE; + std::map<std::string, DependencyVector>& validDeps) override; }; #endif diff --git a/Source/cmDependsJavaParserHelper.cxx b/Source/cmDependsJavaParserHelper.cxx index 3a57a38..f227cf2 100644 --- a/Source/cmDependsJavaParserHelper.cxx +++ b/Source/cmDependsJavaParserHelper.cxx @@ -40,10 +40,8 @@ void cmDependsJavaParserHelper::CurrentClass::AddFileNamesForPrinting( } rname += this->Name; files->push_back(rname); - std::vector<CurrentClass>::const_iterator it; - for (it = this->NestedClasses.begin(); it != this->NestedClasses.end(); - ++it) { - it->AddFileNamesForPrinting(files, rname.c_str(), sep); + for (CurrentClass const& nc : this->NestedClasses) { + nc.AddFileNamesForPrinting(files, rname.c_str(), sep); } } @@ -64,9 +62,8 @@ void cmDependsJavaParserHelper::AddClassFound(const char* sclass) if (!sclass) { return; } - std::vector<std::string>::iterator it; - for (it = this->ClassesFound.begin(); it != this->ClassesFound.end(); it++) { - if (*it == sclass) { + for (std::string const& cf : this->ClassesFound) { + if (cf == sclass) { return; } } @@ -75,10 +72,8 @@ void cmDependsJavaParserHelper::AddClassFound(const char* sclass) void cmDependsJavaParserHelper::AddPackagesImport(const char* sclass) { - std::vector<std::string>::iterator it; - for (it = this->PackagesImport.begin(); it != this->PackagesImport.end(); - it++) { - if (*it == sclass) { + for (std::string const& pi : this->PackagesImport) { + if (pi == sclass) { return; } } @@ -208,10 +203,8 @@ void cmDependsJavaParserHelper::PrintClasses() std::cerr << "Error when parsing. No classes on class stack" << std::endl; abort(); } - std::vector<std::string> files = this->GetFilesProduced(); - std::vector<std::string>::iterator sit; - for (sit = files.begin(); sit != files.end(); ++sit) { - std::cout << " " << *sit << ".class" << std::endl; + for (std::string const& f : this->GetFilesProduced()) { + std::cout << " " << f << ".class" << std::endl; } } @@ -219,10 +212,8 @@ std::vector<std::string> cmDependsJavaParserHelper::GetFilesProduced() { std::vector<std::string> files; CurrentClass const& toplevel = this->ClassStack.front(); - std::vector<CurrentClass>::const_iterator it; - for (it = toplevel.NestedClasses.begin(); it != toplevel.NestedClasses.end(); - ++it) { - it->AddFileNamesForPrinting(&files, nullptr, "$"); + for (CurrentClass const& nc : toplevel.NestedClasses) { + nc.AddFileNamesForPrinting(&files, nullptr, "$"); } return files; } @@ -262,10 +253,8 @@ int cmDependsJavaParserHelper::ParseString(const char* str, int verb) std::cout << std::endl; std::cout << "Depends on:"; if (!this->ClassesFound.empty()) { - std::vector<std::string>::iterator it; - for (it = this->ClassesFound.begin(); it != this->ClassesFound.end(); - ++it) { - std::cout << " " << *it; + for (std::string const& cf : this->ClassesFound) { + std::cout << " " << cf; } } std::cout << std::endl; @@ -282,9 +271,8 @@ int cmDependsJavaParserHelper::ParseString(const char* str, int verb) void cmDependsJavaParserHelper::CleanupParser() { - std::vector<char*>::iterator it; - for (it = this->Allocates.begin(); it != this->Allocates.end(); ++it) { - delete[] * it; + for (char* allocate : this->Allocates) { + delete[] allocate; } this->Allocates.erase(this->Allocates.begin(), this->Allocates.end()); } @@ -322,7 +310,7 @@ void cmDependsJavaParserHelper::Error(const char* str) void cmDependsJavaParserHelper::UpdateCombine(const char* str1, const char* str2) { - if (this->CurrentCombine == "" && str1 != nullptr) { + if (this->CurrentCombine.empty() && str1 != nullptr) { this->CurrentCombine = str1; } this->CurrentCombine += "."; diff --git a/Source/cmDisallowedCommand.h b/Source/cmDisallowedCommand.h index d5bb79a..d85c00f 100644 --- a/Source/cmDisallowedCommand.h +++ b/Source/cmDisallowedCommand.h @@ -24,23 +24,20 @@ public: { } - ~cmDisallowedCommand() CM_OVERRIDE { delete this->Command; } + ~cmDisallowedCommand() override { delete this->Command; } - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { return new cmDisallowedCommand(this->Command->Clone(), this->Policy, this->Message); } bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; - void FinalPass() CM_OVERRIDE { this->Command->FinalPass(); } + void FinalPass() override { this->Command->FinalPass(); } - bool HasFinalPass() const CM_OVERRIDE - { - return this->Command->HasFinalPass(); - } + bool HasFinalPass() const override { return this->Command->HasFinalPass(); } private: cmCommand* Command; diff --git a/Source/cmDocumentation.cxx b/Source/cmDocumentation.cxx index 4af44b4..0c96860 100644 --- a/Source/cmDocumentation.cxx +++ b/Source/cmDocumentation.cxx @@ -123,23 +123,21 @@ bool cmDocumentation::PrintRequestedDocumentation(std::ostream& os) bool result = true; // Loop over requested documentation types. - for (std::vector<RequestedHelpItem>::const_iterator i = - this->RequestedHelpItems.begin(); - i != this->RequestedHelpItems.end(); ++i) { - this->CurrentArgument = i->Argument; + for (RequestedHelpItem const& rhi : this->RequestedHelpItems) { + this->CurrentArgument = rhi.Argument; // If a file name was given, use it. Otherwise, default to the // given stream. cmsys::ofstream fout; std::ostream* s = &os; - if (!i->Filename.empty()) { - fout.open(i->Filename.c_str()); + if (!rhi.Filename.empty()) { + fout.open(rhi.Filename.c_str()); s = &fout; } else if (++count > 1) { os << "\n\n"; } // Print this documentation type to the stream. - if (!this->PrintDocumentation(i->HelpType, *s) || s->fail()) { + if (!this->PrintDocumentation(rhi.HelpType, *s) || s->fail()) { result = false; } } @@ -394,10 +392,8 @@ void cmDocumentation::SetSection(const char* name, const char* docs[][2]) void cmDocumentation::SetSections( std::map<std::string, cmDocumentationSection*>& sections) { - for (std::map<std::string, cmDocumentationSection*>::const_iterator it = - sections.begin(); - it != sections.end(); ++it) { - this->SetSection(it->first.c_str(), it->second); + for (auto const& s : sections) { + this->SetSection(s.first.c_str(), s.second); } } @@ -489,10 +485,9 @@ void cmDocumentation::PrintNames(std::ostream& os, std::string const& pattern) std::vector<std::string> files; this->GlobHelp(files, pattern); std::vector<std::string> names; - for (std::vector<std::string>::const_iterator i = files.begin(); - i != files.end(); ++i) { + for (std::string const& f : files) { std::string line; - cmsys::ifstream fin(i->c_str()); + cmsys::ifstream fin(f.c_str()); while (fin && cmSystemTools::GetLineFromStream(fin, line)) { if (!line.empty() && (isalnum(line[0]) || line[0] == '<')) { names.push_back(line); @@ -501,9 +496,8 @@ void cmDocumentation::PrintNames(std::ostream& os, std::string const& pattern) } } std::sort(names.begin(), names.end()); - for (std::vector<std::string>::iterator i = names.begin(); i != names.end(); - ++i) { - os << *i << "\n"; + for (std::string const& n : names) { + os << n << "\n"; } } @@ -514,9 +508,8 @@ bool cmDocumentation::PrintFiles(std::ostream& os, std::string const& pattern) this->GlobHelp(files, pattern); std::sort(files.begin(), files.end()); cmRST r(os, cmSystemTools::GetCMakeRoot() + "/Help"); - for (std::vector<std::string>::const_iterator i = files.begin(); - i != files.end(); ++i) { - found = r.ProcessFile(*i) || found; + for (std::string const& f : files) { + found = r.ProcessFile(f) || found; } return found; } @@ -586,15 +579,13 @@ bool cmDocumentation::PrintHelpListModules(std::ostream& os) std::vector<std::string> files; this->GlobHelp(files, "module/*"); std::vector<std::string> modules; - for (std::vector<std::string>::iterator fi = files.begin(); - fi != files.end(); ++fi) { - std::string module = cmSystemTools::GetFilenameName(*fi); + for (std::string const& f : files) { + std::string module = cmSystemTools::GetFilenameName(f); modules.push_back(module.substr(0, module.size() - 4)); } std::sort(modules.begin(), modules.end()); - for (std::vector<std::string>::iterator i = modules.begin(); - i != modules.end(); ++i) { - os << *i << "\n"; + for (std::string const& m : modules) { + os << m << "\n"; } return true; } diff --git a/Source/cmDocumentationFormatter.cxx b/Source/cmDocumentationFormatter.cxx index 0018263..6b996e4 100644 --- a/Source/cmDocumentationFormatter.cxx +++ b/Source/cmDocumentationFormatter.cxx @@ -168,26 +168,25 @@ void cmDocumentationFormatter::PrintSection( os << section.GetName() << "\n"; const std::vector<cmDocumentationEntry>& entries = section.GetEntries(); - for (std::vector<cmDocumentationEntry>::const_iterator op = entries.begin(); - op != entries.end(); ++op) { - if (!op->Name.empty()) { - os << " " << op->Name; + for (cmDocumentationEntry const& entry : entries) { + if (!entry.Name.empty()) { + os << " " << entry.Name; this->TextIndent = " "; int align = static_cast<int>(strlen(this->TextIndent)) - 4; - for (int i = static_cast<int>(op->Name.size()); i < align; ++i) { + for (int i = static_cast<int>(entry.Name.size()); i < align; ++i) { os << " "; } - if (op->Name.size() > strlen(this->TextIndent) - 4) { + if (entry.Name.size() > strlen(this->TextIndent) - 4) { os << "\n"; os.write(this->TextIndent, strlen(this->TextIndent) - 2); } os << "= "; - this->PrintColumn(os, op->Brief.c_str()); + this->PrintColumn(os, entry.Brief.c_str()); os << "\n"; } else { os << "\n"; this->TextIndent = ""; - this->PrintFormatted(os, op->Brief.c_str()); + this->PrintFormatted(os, entry.Brief.c_str()); } } os << "\n"; diff --git a/Source/cmDynamicLoader.cxx b/Source/cmDynamicLoader.cxx index 2fe0360..7da6ff5 100644 --- a/Source/cmDynamicLoader.cxx +++ b/Source/cmDynamicLoader.cxx @@ -65,10 +65,8 @@ bool cmDynamicLoaderCache::FlushCache(const char* path) void cmDynamicLoaderCache::FlushCache() { - for (std::map<std::string, cmsys::DynamicLoader::LibraryHandle>::iterator - it = this->CacheMap.begin(); - it != this->CacheMap.end(); it++) { - cmsys::DynamicLoader::CloseLibrary(it->second); + for (auto const& it : this->CacheMap) { + cmsys::DynamicLoader::CloseLibrary(it.second); } delete cmDynamicLoaderCache::Instance; cmDynamicLoaderCache::Instance = nullptr; diff --git a/Source/cmELF.cxx b/Source/cmELF.cxx index e2655e7..76374b2 100644 --- a/Source/cmELF.cxx +++ b/Source/cmELF.cxx @@ -2,10 +2,10 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmELF.h" -#include "cm_auto_ptr.hxx" #include "cm_kwiml.h" #include "cmsys/FStream.hxx" #include <map> +#include <memory> // IWYU pragma: keep #include <sstream> #include <stddef.h> #include <utility> @@ -108,7 +108,7 @@ public: }; // Construct and take ownership of the file stream object. - cmELFInternal(cmELF* external, CM_AUTO_PTR<cmsys::ifstream>& fin, + cmELFInternal(cmELF* external, std::unique_ptr<cmsys::ifstream>& fin, ByteOrderType order) : External(external) , Stream(*fin.release()) @@ -231,27 +231,27 @@ public: typedef typename Types::tagtype tagtype; // Construct with a stream and byte swap indicator. - cmELFInternalImpl(cmELF* external, CM_AUTO_PTR<cmsys::ifstream>& fin, + cmELFInternalImpl(cmELF* external, std::unique_ptr<cmsys::ifstream>& fin, ByteOrderType order); // Return the number of sections as specified by the ELF header. - unsigned int GetNumberOfSections() const CM_OVERRIDE + unsigned int GetNumberOfSections() const override { return static_cast<unsigned int>(this->ELFHeader.e_shnum); } // Get the file position of a dynamic section entry. - unsigned long GetDynamicEntryPosition(int j) CM_OVERRIDE; + unsigned long GetDynamicEntryPosition(int j) override; - cmELF::DynamicEntryList GetDynamicEntries() CM_OVERRIDE; - std::vector<char> EncodeDynamicEntries(const cmELF::DynamicEntryList&) - CM_OVERRIDE; + cmELF::DynamicEntryList GetDynamicEntries() override; + std::vector<char> EncodeDynamicEntries( + const cmELF::DynamicEntryList&) override; // Lookup a string from the dynamic section with the given tag. - StringEntry const* GetDynamicSectionString(unsigned int tag) CM_OVERRIDE; + StringEntry const* GetDynamicSectionString(unsigned int tag) override; // Print information about the ELF file. - void PrintInfo(std::ostream& os) const CM_OVERRIDE + void PrintInfo(std::ostream& os) const override { os << "ELF " << Types::GetName(); if (this->ByteOrder == ByteOrderMSB) { @@ -424,9 +424,8 @@ private: }; template <class Types> -cmELFInternalImpl<Types>::cmELFInternalImpl(cmELF* external, - CM_AUTO_PTR<cmsys::ifstream>& fin, - ByteOrderType order) +cmELFInternalImpl<Types>::cmELFInternalImpl( + cmELF* external, std::unique_ptr<cmsys::ifstream>& fin, ByteOrderType order) : cmELFInternal(external, fin, order) { // Read the main header. @@ -547,10 +546,7 @@ cmELF::DynamicEntryList cmELFInternalImpl<Types>::GetDynamicEntries() // Copy into public array result.reserve(this->DynamicSectionEntries.size()); - for (typename std::vector<ELF_Dyn>::iterator di = - this->DynamicSectionEntries.begin(); - di != this->DynamicSectionEntries.end(); ++di) { - ELF_Dyn& dyn = *di; + for (ELF_Dyn& dyn : this->DynamicSectionEntries) { result.push_back( std::pair<unsigned long, unsigned long>(dyn.d_tag, dyn.d_un.d_val)); } @@ -565,12 +561,11 @@ std::vector<char> cmELFInternalImpl<Types>::EncodeDynamicEntries( std::vector<char> result; result.reserve(sizeof(ELF_Dyn) * entries.size()); - for (cmELF::DynamicEntryList::const_iterator it = entries.begin(); - it != entries.end(); it++) { + for (auto const& entry : entries) { // Store the entry in an ELF_Dyn, byteswap it, then serialize to chars ELF_Dyn dyn; - dyn.d_tag = static_cast<tagtype>(it->first); - dyn.d_un.d_val = static_cast<tagtype>(it->second); + dyn.d_tag = static_cast<tagtype>(entry.first); + dyn.d_un.d_val = static_cast<tagtype>(entry.second); if (this->NeedSwap) { ByteSwap(dyn); @@ -686,7 +681,7 @@ cmELF::cmELF(const char* fname) : Internal(nullptr) { // Try to open the file. - CM_AUTO_PTR<cmsys::ifstream> fin(new cmsys::ifstream(fname)); + std::unique_ptr<cmsys::ifstream> fin(new cmsys::ifstream(fname)); // Quit now if the file could not be opened. if (!fin.get() || !*fin) { diff --git a/Source/cmELF.h b/Source/cmELF.h index 678a595..8c17348 100644 --- a/Source/cmELF.h +++ b/Source/cmELF.h @@ -64,7 +64,7 @@ public: }; /** Represent entire dynamic section header */ - typedef std::vector<std::pair<long, unsigned long> > DynamicEntryList; + typedef std::vector<std::pair<long, unsigned long>> DynamicEntryList; /** Get the type of the file opened. */ FileType GetFileType() const; diff --git a/Source/cmEnableLanguageCommand.cxx b/Source/cmEnableLanguageCommand.cxx index c57b7b1..ddd26de 100644 --- a/Source/cmEnableLanguageCommand.cxx +++ b/Source/cmEnableLanguageCommand.cxx @@ -16,12 +16,11 @@ bool cmEnableLanguageCommand::InitialPass(std::vector<std::string> const& args, this->SetError("called with incorrect number of arguments"); return false; } - for (std::vector<std::string>::const_iterator it = args.begin(); - it != args.end(); ++it) { - if ((*it) == "OPTIONAL") { + for (std::string const& it : args) { + if (it == "OPTIONAL") { optional = true; } else { - languages.push_back(*it); + languages.push_back(it); } } diff --git a/Source/cmEnableLanguageCommand.h b/Source/cmEnableLanguageCommand.h index 2b8cc24..97645a9 100644 --- a/Source/cmEnableLanguageCommand.h +++ b/Source/cmEnableLanguageCommand.h @@ -26,14 +26,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmEnableLanguageCommand; } + cmCommand* Clone() override { return new cmEnableLanguageCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmEnableTestingCommand.h b/Source/cmEnableTestingCommand.h index 1743b25..88a17b9 100644 --- a/Source/cmEnableTestingCommand.h +++ b/Source/cmEnableTestingCommand.h @@ -31,14 +31,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmEnableTestingCommand; } + cmCommand* Clone() override { return new cmEnableTestingCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const&, - cmExecutionStatus&) CM_OVERRIDE; + cmExecutionStatus&) override; }; #endif diff --git a/Source/cmExecProgramCommand.cxx b/Source/cmExecProgramCommand.cxx index 3c39816..88e085d 100644 --- a/Source/cmExecProgramCommand.cxx +++ b/Source/cmExecProgramCommand.cxx @@ -26,8 +26,8 @@ bool cmExecProgramCommand::InitialPass(std::vector<std::string> const& args, bool haveoutput_variable = false; std::string return_variable; bool havereturn_variable = false; - for (size_t i = 0; i < args.size(); ++i) { - if (args[i] == "OUTPUT_VARIABLE") { + for (std::string const& arg : args) { + if (arg == "OUTPUT_VARIABLE") { count++; doingargs = false; havereturn_variable = false; @@ -37,10 +37,10 @@ bool cmExecProgramCommand::InitialPass(std::vector<std::string> const& args, this->SetError("called with incorrect number of arguments"); return false; } - output_variable = args[i]; + output_variable = arg; haveoutput_variable = false; count++; - } else if (args[i] == "RETURN_VALUE") { + } else if (arg == "RETURN_VALUE") { count++; doingargs = false; haveoutput_variable = false; @@ -50,16 +50,16 @@ bool cmExecProgramCommand::InitialPass(std::vector<std::string> const& args, this->SetError("called with incorrect number of arguments"); return false; } - return_variable = args[i]; + return_variable = arg; havereturn_variable = false; count++; - } else if (args[i] == "ARGS") { + } else if (arg == "ARGS") { count++; havereturn_variable = false; haveoutput_variable = false; doingargs = true; } else if (doingargs) { - arguments += args[i]; + arguments += arg; arguments += " "; count++; } diff --git a/Source/cmExecProgramCommand.h b/Source/cmExecProgramCommand.h index e3d696e..dc5da74 100644 --- a/Source/cmExecProgramCommand.h +++ b/Source/cmExecProgramCommand.h @@ -27,14 +27,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmExecProgramCommand; } + cmCommand* Clone() override { return new cmExecProgramCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: static bool RunCommand(const char* command, std::string& output, int& retVal, diff --git a/Source/cmExecuteProcessCommand.cxx b/Source/cmExecuteProcessCommand.cxx index 408497b..39e774e 100644 --- a/Source/cmExecuteProcessCommand.cxx +++ b/Source/cmExecuteProcessCommand.cxx @@ -32,7 +32,7 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args, this->SetError("called with incorrect number of arguments"); return false; } - std::vector<std::vector<const char*> > cmds; + std::vector<std::vector<const char*>> cmds; std::string arguments; bool doing_command = false; size_t command_index = 0; @@ -170,13 +170,13 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args, this->SetError(" called with no COMMAND argument."); return false; } - for (unsigned int i = 0; i < cmds.size(); ++i) { - if (cmds[i].empty()) { + for (auto& cmd : cmds) { + if (cmd.empty()) { this->SetError(" given COMMAND argument with no value."); return false; } // Add the null terminating pointer to the command argument list. - cmds[i].push_back(nullptr); + cmd.push_back(nullptr); } // Parse the timeout string. @@ -192,8 +192,8 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args, cmsysProcess* cp = cmsysProcess_New(); // Set the command sequence. - for (unsigned int i = 0; i < cmds.size(); ++i) { - cmsysProcess_AddCommand(cp, &*cmds[i].begin()); + for (auto const& cmd : cmds) { + cmsysProcess_AddCommand(cp, &*cmd.begin()); } // Set the process working directory. diff --git a/Source/cmExecuteProcessCommand.h b/Source/cmExecuteProcessCommand.h index dcf7b1c..b415deb 100644 --- a/Source/cmExecuteProcessCommand.h +++ b/Source/cmExecuteProcessCommand.h @@ -24,14 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmExecuteProcessCommand; } + cmCommand* Clone() override { return new cmExecuteProcessCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmExportBuildAndroidMKGenerator.cxx b/Source/cmExportBuildAndroidMKGenerator.cxx index 8662e8a..5e2cd53 100644 --- a/Source/cmExportBuildAndroidMKGenerator.cxx +++ b/Source/cmExportBuildAndroidMKGenerator.cxx @@ -3,7 +3,7 @@ #include "cmExportBuildAndroidMKGenerator.h" #include <algorithm> -#include <map> +#include <memory> // IWYU pragma: keep #include <sstream> #include <utility> @@ -16,7 +16,6 @@ #include "cmStateTypes.h" #include "cmSystemTools.h" #include "cmTarget.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" cmExportBuildAndroidMKGenerator::cmExportBuildAndroidMKGenerator() @@ -98,43 +97,41 @@ void cmExportBuildAndroidMKGenerator::GenerateInterfaceProperties( } if (!properties.empty()) { os << "LOCAL_CPP_FEATURES := rtti exceptions\n"; - for (ImportPropertyMap::const_iterator pi = properties.begin(); - pi != properties.end(); ++pi) { - if (pi->first == "INTERFACE_COMPILE_OPTIONS") { + for (auto const& property : properties) { + if (property.first == "INTERFACE_COMPILE_OPTIONS") { os << "LOCAL_CPP_FEATURES += "; - os << (pi->second) << "\n"; - } else if (pi->first == "INTERFACE_LINK_LIBRARIES") { + os << (property.second) << "\n"; + } else if (property.first == "INTERFACE_LINK_LIBRARIES") { // need to look at list in pi->second and see if static or shared // FindTargetToLink // target->GetLocalGenerator()->FindGeneratorTargetToUse() // then add to LOCAL_CPPFLAGS std::vector<std::string> libraries; - cmSystemTools::ExpandListArgument(pi->second, libraries); + cmSystemTools::ExpandListArgument(property.second, libraries); std::string staticLibs; std::string sharedLibs; std::string ldlibs; - for (std::vector<std::string>::iterator i = libraries.begin(); - i != libraries.end(); ++i) { + for (std::string const& lib : libraries) { cmGeneratorTarget* gt = - target->GetLocalGenerator()->FindGeneratorTargetToUse(*i); + target->GetLocalGenerator()->FindGeneratorTargetToUse(lib); if (gt) { if (gt->GetType() == cmStateEnums::SHARED_LIBRARY || gt->GetType() == cmStateEnums::MODULE_LIBRARY) { - sharedLibs += " " + *i; + sharedLibs += " " + lib; } else { - staticLibs += " " + *i; + staticLibs += " " + lib; } } else { // evaluate any generator expressions with the current // build type of the makefile cmGeneratorExpression ge; - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(*i); + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(lib); std::string evaluated = cge->Evaluate(target->GetLocalGenerator(), config); bool relpath = false; if (type == cmExportBuildAndroidMKGenerator::INSTALL) { - relpath = i->substr(0, 3) == "../"; + relpath = lib.substr(0, 3) == "../"; } // check for full path or if it already has a -l, or // in the case of an install check for relative paths @@ -157,20 +154,19 @@ void cmExportBuildAndroidMKGenerator::GenerateInterfaceProperties( if (!ldlibs.empty()) { os << "LOCAL_EXPORT_LDLIBS :=" << ldlibs << "\n"; } - } else if (pi->first == "INTERFACE_INCLUDE_DIRECTORIES") { - std::string includes = pi->second; + } else if (property.first == "INTERFACE_INCLUDE_DIRECTORIES") { + std::string includes = property.second; std::vector<std::string> includeList; cmSystemTools::ExpandListArgument(includes, includeList); os << "LOCAL_EXPORT_C_INCLUDES := "; std::string end; - for (std::vector<std::string>::iterator i = includeList.begin(); - i != includeList.end(); ++i) { - os << end << *i; + for (std::string const& i : includeList) { + os << end << i; end = "\\\n"; } os << "\n"; } else { - os << "# " << pi->first << " " << (pi->second) << "\n"; + os << "# " << property.first << " " << (property.second) << "\n"; } } } diff --git a/Source/cmExportBuildAndroidMKGenerator.h b/Source/cmExportBuildAndroidMKGenerator.h index db386f0..c80839b 100644 --- a/Source/cmExportBuildAndroidMKGenerator.h +++ b/Source/cmExportBuildAndroidMKGenerator.h @@ -42,25 +42,24 @@ public: protected: // Implement virtual methods from the superclass. - void GeneratePolicyHeaderCode(std::ostream&) CM_OVERRIDE {} - void GeneratePolicyFooterCode(std::ostream&) CM_OVERRIDE {} + void GeneratePolicyHeaderCode(std::ostream&) override {} + void GeneratePolicyFooterCode(std::ostream&) override {} void GenerateImportHeaderCode(std::ostream& os, - const std::string& config = "") CM_OVERRIDE; - void GenerateImportFooterCode(std::ostream& os) CM_OVERRIDE; + const std::string& config = "") override; + void GenerateImportFooterCode(std::ostream& os) override; void GenerateImportTargetCode(std::ostream& os, - const cmGeneratorTarget* target) CM_OVERRIDE; + const cmGeneratorTarget* target) override; void GenerateExpectedTargetsCode( - std::ostream& os, const std::string& expectedTargets) CM_OVERRIDE; - void GenerateImportPropertyCode(std::ostream& os, const std::string& config, - cmGeneratorTarget const* target, - ImportPropertyMap const& properties) - CM_OVERRIDE; + std::ostream& os, const std::string& expectedTargets) override; + void GenerateImportPropertyCode( + std::ostream& os, const std::string& config, + cmGeneratorTarget const* target, + ImportPropertyMap const& properties) override; void GenerateMissingTargetsCheckCode( - std::ostream& os, - const std::vector<std::string>& missingTargets) CM_OVERRIDE; + std::ostream& os, const std::vector<std::string>& missingTargets) override; void GenerateInterfaceProperties( cmGeneratorTarget const* target, std::ostream& os, - const ImportPropertyMap& properties) CM_OVERRIDE; + const ImportPropertyMap& properties) override; }; #endif diff --git a/Source/cmExportBuildFileGenerator.cxx b/Source/cmExportBuildFileGenerator.cxx index 6e182b7..bb1dda3 100644 --- a/Source/cmExportBuildFileGenerator.cxx +++ b/Source/cmExportBuildFileGenerator.cxx @@ -45,9 +45,8 @@ bool cmExportBuildFileGenerator::GenerateMainFile(std::ostream& os) std::string sep; std::vector<std::string> targets; this->GetTargets(targets); - for (std::vector<std::string>::const_iterator tei = targets.begin(); - tei != targets.end(); ++tei) { - cmGeneratorTarget* te = this->LG->FindGeneratorTargetToUse(*tei); + for (std::string const& tei : targets) { + cmGeneratorTarget* te = this->LG->FindGeneratorTargetToUse(tei); expectedTargets += sep + this->Namespace + te->GetExportName(); sep = " "; if (this->ExportedTargets.insert(te).second) { @@ -71,10 +70,7 @@ bool cmExportBuildFileGenerator::GenerateMainFile(std::ostream& os) std::vector<std::string> missingTargets; // Create all the imported targets. - for (std::vector<cmGeneratorTarget*>::const_iterator tei = - this->Exports.begin(); - tei != this->Exports.end(); ++tei) { - cmGeneratorTarget* gte = *tei; + for (cmGeneratorTarget* gte : this->Exports) { this->GenerateImportTargetCode(os, gte); gte->Target->AppendBuildInterfaceIncludes(); @@ -115,10 +111,8 @@ bool cmExportBuildFileGenerator::GenerateMainFile(std::ostream& os) } // Generate import file content for each configuration. - for (std::vector<std::string>::const_iterator ci = - this->Configurations.begin(); - ci != this->Configurations.end(); ++ci) { - this->GenerateImportConfig(os, *ci, missingTargets); + for (std::string const& c : this->Configurations) { + this->GenerateImportConfig(os, c, missingTargets); } this->GenerateMissingTargetsCheckCode(os, missingTargets); @@ -130,11 +124,8 @@ void cmExportBuildFileGenerator::GenerateImportTargetsConfig( std::ostream& os, const std::string& config, std::string const& suffix, std::vector<std::string>& missingTargets) { - for (std::vector<cmGeneratorTarget*>::const_iterator tei = - this->Exports.begin(); - tei != this->Exports.end(); ++tei) { + for (cmGeneratorTarget* target : this->Exports) { // Collect import properties for this target. - cmGeneratorTarget* target = *tei; ImportPropertyMap properties; if (target->GetType() != cmStateEnums::INTERFACE_LIBRARY) { @@ -184,10 +175,8 @@ void cmExportBuildFileGenerator::SetImportLocationProperty( target->GetObjectSources(objectSources, config); std::string const obj_dir = target->GetObjectDirectory(config); std::vector<std::string> objects; - for (std::vector<cmSourceFile const*>::const_iterator si = - objectSources.begin(); - si != objectSources.end(); ++si) { - const std::string& obj = target->GetObjectName(*si); + for (cmSourceFile const* sf : objectSources) { + const std::string& obj = target->GetObjectName(sf); objects.push_back(obj_dir + obj); } @@ -256,10 +245,8 @@ void cmExportBuildFileGenerator::GetTargets( std::vector<std::string>& targets) const { if (this->ExportSet) { - for (std::vector<cmTargetExport*>::const_iterator tei = - this->ExportSet->GetTargetExports()->begin(); - tei != this->ExportSet->GetTargetExports()->end(); ++tei) { - targets.push_back((*tei)->TargetName); + for (cmTargetExport* te : *this->ExportSet->GetTargetExports()) { + targets.push_back(te->TargetName); } return; } @@ -274,10 +261,8 @@ std::vector<std::string> cmExportBuildFileGenerator::FindNamespaces( std::map<std::string, cmExportBuildFileGenerator*>& exportSets = gg->GetBuildExportSets(); - for (std::map<std::string, cmExportBuildFileGenerator*>::const_iterator - expIt = exportSets.begin(); - expIt != exportSets.end(); ++expIt) { - const cmExportBuildFileGenerator* exportSet = expIt->second; + for (auto const& exp : exportSets) { + const cmExportBuildFileGenerator* exportSet = exp.second; std::vector<std::string> targets; exportSet->GetTargets(targets); if (std::find(targets.begin(), targets.end(), name) != targets.end()) { diff --git a/Source/cmExportBuildFileGenerator.h b/Source/cmExportBuildFileGenerator.h index d509453..6457a77 100644 --- a/Source/cmExportBuildFileGenerator.h +++ b/Source/cmExportBuildFileGenerator.h @@ -49,14 +49,14 @@ public: protected: // Implement virtual methods from the superclass. - bool GenerateMainFile(std::ostream& os) CM_OVERRIDE; + bool GenerateMainFile(std::ostream& os) override; void GenerateImportTargetsConfig( std::ostream& os, const std::string& config, std::string const& suffix, - std::vector<std::string>& missingTargets) CM_OVERRIDE; + std::vector<std::string>& missingTargets) override; void HandleMissingTarget(std::string& link_libs, std::vector<std::string>& missingTargets, cmGeneratorTarget* depender, - cmGeneratorTarget* dependee) CM_OVERRIDE; + cmGeneratorTarget* dependee) override; void ComplainAboutMissingTarget(cmGeneratorTarget* depender, cmGeneratorTarget* dependee, @@ -69,7 +69,7 @@ protected: ImportPropertyMap& properties); std::string InstallNameDir(cmGeneratorTarget* target, - const std::string& config) CM_OVERRIDE; + const std::string& config) override; std::vector<std::string> FindNamespaces(cmGlobalGenerator* gg, const std::string& name); diff --git a/Source/cmExportCommand.cxx b/Source/cmExportCommand.cxx index 64baa90..9913129 100644 --- a/Source/cmExportCommand.cxx +++ b/Source/cmExportCommand.cxx @@ -136,42 +136,40 @@ bool cmExportCommand::InitialPass(std::vector<std::string> const& args, } this->ExportSet = setMap[setName]; } else if (this->Targets.WasFound()) { - for (std::vector<std::string>::const_iterator currentTarget = - this->Targets.GetVector().begin(); - currentTarget != this->Targets.GetVector().end(); ++currentTarget) { - if (this->Makefile->IsAlias(*currentTarget)) { + for (std::string const& currentTarget : this->Targets.GetVector()) { + if (this->Makefile->IsAlias(currentTarget)) { std::ostringstream e; - e << "given ALIAS target \"" << *currentTarget + e << "given ALIAS target \"" << currentTarget << "\" which may not be exported."; this->SetError(e.str()); return false; } - if (cmTarget* target = gg->FindTarget(*currentTarget)) { + if (cmTarget* target = gg->FindTarget(currentTarget)) { if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) { std::string reason; if (!this->Makefile->GetGlobalGenerator() ->HasKnownObjectFileLocation(&reason)) { std::ostringstream e; - e << "given OBJECT library \"" << *currentTarget + e << "given OBJECT library \"" << currentTarget << "\" which may not be exported" << reason << "."; this->SetError(e.str()); return false; } } if (target->GetType() == cmStateEnums::UTILITY) { - this->SetError("given custom target \"" + *currentTarget + + this->SetError("given custom target \"" + currentTarget + "\" which may not be exported."); return false; } } else { std::ostringstream e; - e << "given target \"" << *currentTarget + e << "given target \"" << currentTarget << "\" which is not built by this project."; this->SetError(e.str()); return false; } - targets.push_back(*currentTarget); + targets.push_back(currentTarget); } if (this->Append.IsEnabled()) { if (cmExportBuildFileGenerator* ebfg = @@ -209,10 +207,8 @@ bool cmExportCommand::InitialPass(std::vector<std::string> const& args, if (configurationTypes.empty()) { configurationTypes.push_back(""); } - for (std::vector<std::string>::const_iterator ci = - configurationTypes.begin(); - ci != configurationTypes.end(); ++ci) { - ebfg->AddConfiguration(*ci); + for (std::string const& ct : configurationTypes) { + ebfg->AddConfiguration(ct); } if (this->ExportSet) { gg->AddBuildExportExportSet(ebfg); diff --git a/Source/cmExportCommand.h b/Source/cmExportCommand.h index 7b6ad11..a5c6751 100644 --- a/Source/cmExportCommand.h +++ b/Source/cmExportCommand.h @@ -27,14 +27,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmExportCommand; } + cmCommand* Clone() override { return new cmExportCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: cmCommandArgumentsHelper Helper; diff --git a/Source/cmExportFileGenerator.cxx b/Source/cmExportFileGenerator.cxx index 972f4b9..7f0cb97 100644 --- a/Source/cmExportFileGenerator.cxx +++ b/Source/cmExportFileGenerator.cxx @@ -17,9 +17,9 @@ #include "cmTargetExport.h" #include "cmake.h" -#include "cm_auto_ptr.hxx" #include "cmsys/FStream.hxx" #include <assert.h> +#include <memory> // IWYU pragma: keep #include <sstream> #include <string.h> #include <utility> @@ -65,18 +65,17 @@ const char* cmExportFileGenerator::GetMainExportFileName() const bool cmExportFileGenerator::GenerateImportFile() { // Open the output file to generate it. - CM_AUTO_PTR<cmsys::ofstream> foutPtr; + std::unique_ptr<cmsys::ofstream> foutPtr; if (this->AppendMode) { // Open for append. - CM_AUTO_PTR<cmsys::ofstream> ap( - new cmsys::ofstream(this->MainImportFile.c_str(), std::ios::app)); - foutPtr = ap; + foutPtr = cm::make_unique<cmsys::ofstream>(this->MainImportFile.c_str(), + std::ios::app); } else { // Generate atomically and with copy-if-different. - CM_AUTO_PTR<cmGeneratedFileStream> ap( + std::unique_ptr<cmGeneratedFileStream> ap( new cmGeneratedFileStream(this->MainImportFile.c_str(), true)); ap->SetCopyIfDifferent(true); - foutPtr = ap; + foutPtr = std::move(ap); } if (!foutPtr.get() || !*foutPtr) { std::string se = cmSystemTools::GetLastSystemError(); @@ -137,7 +136,7 @@ void cmExportFileGenerator::PopulateInterfaceProperty( if (input) { if (!*input) { // Set to empty - properties[outputName] = ""; + properties[outputName].clear(); return; } @@ -206,9 +205,8 @@ static bool checkInterfaceDirs(const std::string& prepro, bool hadFatalError = false; - for (std::vector<std::string>::iterator li = parts.begin(); - li != parts.end(); ++li) { - size_t genexPos = cmGeneratorExpression::Find(*li); + for (std::string const& li : parts) { + size_t genexPos = cmGeneratorExpression::Find(li); if (genexPos == 0) { continue; } @@ -233,20 +231,20 @@ static bool checkInterfaceDirs(const std::string& prepro, hadFatalError = true; } } - if (cmHasLiteralPrefix(li->c_str(), "${_IMPORT_PREFIX}")) { + if (cmHasLiteralPrefix(li.c_str(), "${_IMPORT_PREFIX}")) { continue; } - if (!cmSystemTools::FileIsFullPath(li->c_str())) { + if (!cmSystemTools::FileIsFullPath(li.c_str())) { /* clang-format off */ e << "Target \"" << target->GetName() << "\" " << prop << " property contains relative path:\n" - " \"" << *li << "\""; + " \"" << li << "\""; /* clang-format on */ target->GetLocalGenerator()->IssueMessage(messageType, e.str()); } - bool inBinary = isSubDirectory(li->c_str(), topBinaryDir); - bool inSource = isSubDirectory(li->c_str(), topSourceDir); - if (isSubDirectory(li->c_str(), installDir)) { + bool inBinary = isSubDirectory(li.c_str(), topBinaryDir); + bool inSource = isSubDirectory(li.c_str(), topSourceDir); + if (isSubDirectory(li.c_str(), installDir)) { // The include directory is inside the install tree. If the // install tree is not inside the source tree or build tree then // fall through to the checks below that the include directory is not @@ -261,7 +259,7 @@ static bool checkInterfaceDirs(const std::string& prepro, case cmPolicies::WARN: { std::ostringstream s; s << cmPolicies::GetPolicyWarning(cmPolicies::CMP0052) << "\n"; - s << "Directory:\n \"" << *li + s << "Directory:\n \"" << li << "\"\nin " "INTERFACE_INCLUDE_DIRECTORIES of target \"" << target->GetName() << "\" is a subdirectory of the install " @@ -293,7 +291,7 @@ static bool checkInterfaceDirs(const std::string& prepro, /* clang-format off */ e << "Target \"" << target->GetName() << "\" " << prop << " property contains path:\n" - " \"" << *li << "\"\nwhich is prefixed in the build directory."; + " \"" << li << "\"\nwhich is prefixed in the build directory."; /* clang-format on */ target->GetLocalGenerator()->IssueMessage(messageType, e.str()); } @@ -302,7 +300,7 @@ static bool checkInterfaceDirs(const std::string& prepro, e << "Target \"" << target->GetName() << "\" " << prop << " property contains path:\n" " \"" - << *li << "\"\nwhich is prefixed in the source directory."; + << li << "\"\nwhich is prefixed in the source directory."; target->GetLocalGenerator()->IssueMessage(messageType, e.str()); } } @@ -314,17 +312,16 @@ static void prefixItems(std::string& exportDirs) { std::vector<std::string> entries; cmGeneratorExpression::Split(exportDirs, entries); - exportDirs = ""; + exportDirs.clear(); const char* sep = ""; - for (std::vector<std::string>::const_iterator ei = entries.begin(); - ei != entries.end(); ++ei) { + for (std::string const& e : entries) { exportDirs += sep; sep = ";"; - if (!cmSystemTools::FileIsFullPath(ei->c_str()) && - ei->find("${_IMPORT_PREFIX}") == std::string::npos) { + if (!cmSystemTools::FileIsFullPath(e.c_str()) && + e.find("${_IMPORT_PREFIX}") == std::string::npos) { exportDirs += "${_IMPORT_PREFIX}/"; } - exportDirs += *ei; + exportDirs += e; } } @@ -343,7 +340,7 @@ void cmExportFileGenerator::PopulateSourcesInterface( } if (!*input) { - properties[propName] = ""; + properties[propName].clear(); return; } @@ -374,7 +371,7 @@ void cmExportFileGenerator::PopulateIncludeDirectoriesInterface( std::string dirs = cmGeneratorExpression::Preprocess( tei->InterfaceIncludeDirectories, preprocessRule, true); this->ReplaceInstallPrefix(dirs); - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(dirs); + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(dirs); std::string exportDirs = cge->Evaluate(target->GetLocalGenerator(), "", false, target); @@ -396,7 +393,7 @@ void cmExportFileGenerator::PopulateIncludeDirectoriesInterface( } if ((input && !*input) && exportDirs.empty()) { // Set to empty - properties[propName] = ""; + properties[propName].clear(); return; } @@ -461,18 +458,17 @@ void getCompatibleInterfaceProperties(cmGeneratorTarget* target, const cmComputeLinkInformation::ItemVector& deps = info->GetItems(); - for (cmComputeLinkInformation::ItemVector::const_iterator li = deps.begin(); - li != deps.end(); ++li) { - if (!li->Target) { + for (auto const& dep : deps) { + if (!dep.Target) { continue; } - getPropertyContents(li->Target, "COMPATIBLE_INTERFACE_BOOL", + getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_BOOL", ifaceProperties); - getPropertyContents(li->Target, "COMPATIBLE_INTERFACE_STRING", + getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_STRING", ifaceProperties); - getPropertyContents(li->Target, "COMPATIBLE_INTERFACE_NUMBER_MIN", + getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_NUMBER_MIN", ifaceProperties); - getPropertyContents(li->Target, "COMPATIBLE_INTERFACE_NUMBER_MAX", + getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_NUMBER_MAX", ifaceProperties); } } @@ -504,15 +500,13 @@ void cmExportFileGenerator::PopulateCompatibleInterfaceProperties( std::vector<std::string> configNames; gtarget->Target->GetMakefile()->GetConfigurations(configNames); - for (std::vector<std::string>::const_iterator ci = configNames.begin(); - ci != configNames.end(); ++ci) { - getCompatibleInterfaceProperties(gtarget, ifaceProperties, *ci); + for (std::string const& cn : configNames) { + getCompatibleInterfaceProperties(gtarget, ifaceProperties, cn); } } - for (std::set<std::string>::const_iterator it = ifaceProperties.begin(); - it != ifaceProperties.end(); ++it) { - this->PopulateInterfaceProperty("INTERFACE_" + *it, gtarget, properties); + for (std::string const& ip : ifaceProperties) { + this->PopulateInterfaceProperty("INTERFACE_" + ip, gtarget, properties); } } @@ -524,10 +518,9 @@ void cmExportFileGenerator::GenerateInterfaceProperties( std::string targetName = this->Namespace; targetName += target->GetExportName(); os << "set_target_properties(" << targetName << " PROPERTIES\n"; - for (ImportPropertyMap::const_iterator pi = properties.begin(); - pi != properties.end(); ++pi) { - os << " " << pi->first << " " << cmExportFileGeneratorEscape(pi->second) - << "\n"; + for (auto const& property : properties) { + os << " " << property.first << " " + << cmExportFileGeneratorEscape(property.second) << "\n"; } os << ")\n\n"; } @@ -571,15 +564,14 @@ void cmExportFileGenerator::ResolveTargetsInGeneratorExpressions( cmGeneratorExpression::Split(input, parts); std::string sep; - input = ""; - for (std::vector<std::string>::iterator li = parts.begin(); - li != parts.end(); ++li) { - if (cmGeneratorExpression::Find(*li) == std::string::npos) { - this->AddTargetNamespace(*li, target, missingTargets); + input.clear(); + for (std::string& li : parts) { + if (cmGeneratorExpression::Find(li) == std::string::npos) { + this->AddTargetNamespace(li, target, missingTargets); } else { - this->ResolveTargetsInGeneratorExpression(*li, target, missingTargets); + this->ResolveTargetsInGeneratorExpression(li, target, missingTargets); } - input += sep + *li; + input += sep + li; sep = ";"; } } @@ -720,7 +712,7 @@ void cmExportFileGenerator::SetImportLinkInterface( } if (!*propContent) { - properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix] = ""; + properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix].clear(); return; } @@ -797,13 +789,12 @@ void cmExportFileGenerator::SetImportLinkProperty( // Construct the property value. std::string link_entries; const char* sep = ""; - for (typename std::vector<T>::const_iterator li = entries.begin(); - li != entries.end(); ++li) { + for (T const& l : entries) { // Separate this from the previous entry. link_entries += sep; sep = ";"; - std::string temp = *li; + std::string temp = l; this->AddTargetNamespace(temp, target, missingTargets); link_entries += temp; } @@ -988,10 +979,9 @@ void cmExportFileGenerator::GenerateImportPropertyCode( } os << ")\n"; os << "set_target_properties(" << targetName << " PROPERTIES\n"; - for (ImportPropertyMap::const_iterator pi = properties.begin(); - pi != properties.end(); ++pi) { - os << " " << pi->first << " " << cmExportFileGeneratorEscape(pi->second) - << "\n"; + for (auto const& property : properties) { + os << " " << property.first << " " + << cmExportFileGeneratorEscape(property.second) << "\n"; } os << " )\n" << "\n"; @@ -1015,9 +1005,9 @@ void cmExportFileGenerator::GenerateMissingTargetsCheckCode( "foreach(_target "; /* clang-format on */ std::set<std::string> emitted; - for (unsigned int i = 0; i < missingTargets.size(); ++i) { - if (emitted.insert(missingTargets[i]).second) { - os << "\"" << missingTargets[i] << "\" "; + for (std::string const& missingTarget : missingTargets) { + if (emitted.insert(missingTarget).second) { + os << "\"" << missingTarget << "\" "; } } /* clang-format off */ @@ -1094,9 +1084,8 @@ void cmExportFileGenerator::GenerateImportedFileChecksCode( "list(APPEND _IMPORT_CHECK_FILES_FOR_" << targetName << " "; - for (std::set<std::string>::const_iterator li = importedLocations.begin(); - li != importedLocations.end(); ++li) { - ImportPropertyMap::const_iterator pi = properties.find(*li); + for (std::string const& li : importedLocations) { + ImportPropertyMap::const_iterator pi = properties.find(li); if (pi != properties.end()) { os << cmExportFileGeneratorEscape(pi->second) << " "; } diff --git a/Source/cmExportInstallAndroidMKGenerator.cxx b/Source/cmExportInstallAndroidMKGenerator.cxx index 9a1c647..fe565e6 100644 --- a/Source/cmExportInstallAndroidMKGenerator.cxx +++ b/Source/cmExportInstallAndroidMKGenerator.cxx @@ -34,11 +34,8 @@ void cmExportInstallAndroidMKGenerator::GenerateImportHeaderCode( } os << "_IMPORT_PREFIX := " << "$(LOCAL_PATH)" << path << "\n\n"; - for (std::vector<cmTargetExport*>::const_iterator tei = - this->IEGen->GetExportSet()->GetTargetExports()->begin(); - tei != this->IEGen->GetExportSet()->GetTargetExports()->end(); ++tei) { + for (cmTargetExport* te : *this->IEGen->GetExportSet()->GetTargetExports()) { // Collect import properties for this target. - cmTargetExport const* te = *tei; if (te->Target->GetType() == cmStateEnums::INTERFACE_LIBRARY) { continue; } diff --git a/Source/cmExportInstallAndroidMKGenerator.h b/Source/cmExportInstallAndroidMKGenerator.h index bb43513..3165982 100644 --- a/Source/cmExportInstallAndroidMKGenerator.h +++ b/Source/cmExportInstallAndroidMKGenerator.h @@ -36,37 +36,36 @@ public: protected: // Implement virtual methods from the superclass. - void GeneratePolicyHeaderCode(std::ostream&) CM_OVERRIDE {} - void GeneratePolicyFooterCode(std::ostream&) CM_OVERRIDE {} + void GeneratePolicyHeaderCode(std::ostream&) override {} + void GeneratePolicyFooterCode(std::ostream&) override {} void GenerateImportHeaderCode(std::ostream& os, - const std::string& config = "") CM_OVERRIDE; - void GenerateImportFooterCode(std::ostream& os) CM_OVERRIDE; + const std::string& config = "") override; + void GenerateImportFooterCode(std::ostream& os) override; void GenerateImportTargetCode(std::ostream& os, - const cmGeneratorTarget* target) CM_OVERRIDE; + const cmGeneratorTarget* target) override; void GenerateExpectedTargetsCode( - std::ostream& os, const std::string& expectedTargets) CM_OVERRIDE; - void GenerateImportPropertyCode(std::ostream& os, const std::string& config, - cmGeneratorTarget const* target, - ImportPropertyMap const& properties) - CM_OVERRIDE; + std::ostream& os, const std::string& expectedTargets) override; + void GenerateImportPropertyCode( + std::ostream& os, const std::string& config, + cmGeneratorTarget const* target, + ImportPropertyMap const& properties) override; void GenerateMissingTargetsCheckCode( - std::ostream& os, - const std::vector<std::string>& missingTargets) CM_OVERRIDE; + std::ostream& os, const std::vector<std::string>& missingTargets) override; void GenerateInterfaceProperties( cmGeneratorTarget const* target, std::ostream& os, - const ImportPropertyMap& properties) CM_OVERRIDE; - void GenerateImportPrefix(std::ostream& os) CM_OVERRIDE; - void LoadConfigFiles(std::ostream&) CM_OVERRIDE; + const ImportPropertyMap& properties) override; + void GenerateImportPrefix(std::ostream& os) override; + void LoadConfigFiles(std::ostream&) override; void GenerateRequiredCMakeVersion(std::ostream& os, - const char* versionString) CM_OVERRIDE; - void CleanupTemporaryVariables(std::ostream&) CM_OVERRIDE; - void GenerateImportedFileCheckLoop(std::ostream& os) CM_OVERRIDE; + const char* versionString) override; + void CleanupTemporaryVariables(std::ostream&) override; + void GenerateImportedFileCheckLoop(std::ostream& os) override; void GenerateImportedFileChecksCode( std::ostream& os, cmGeneratorTarget* target, ImportPropertyMap const& properties, - const std::set<std::string>& importedLocations) CM_OVERRIDE; + const std::set<std::string>& importedLocations) override; bool GenerateImportFileConfig(const std::string& config, - std::vector<std::string>&) CM_OVERRIDE; + std::vector<std::string>&) override; }; #endif diff --git a/Source/cmExportInstallFileGenerator.cxx b/Source/cmExportInstallFileGenerator.cxx index 350dc19..9b65e9e 100644 --- a/Source/cmExportInstallFileGenerator.cxx +++ b/Source/cmExportInstallFileGenerator.cxx @@ -4,7 +4,6 @@ #include "cmAlgorithms.h" #include "cmExportSet.h" -#include "cmExportSetMap.h" #include "cmGeneratedFileStream.h" #include "cmGeneratorExpression.h" #include "cmGeneratorTarget.h" @@ -22,6 +21,8 @@ #include <sstream> #include <utility> +class cmExportSetMap; + cmExportInstallFileGenerator::cmExportInstallFileGenerator( cmInstallExportGenerator* iegen) : IEGen(iegen) @@ -42,14 +43,10 @@ bool cmExportInstallFileGenerator::GenerateMainFile(std::ostream& os) { std::string expectedTargets; std::string sep; - for (std::vector<cmTargetExport*>::const_iterator tei = - this->IEGen->GetExportSet()->GetTargetExports()->begin(); - tei != this->IEGen->GetExportSet()->GetTargetExports()->end(); - ++tei) { - expectedTargets += - sep + this->Namespace + (*tei)->Target->GetExportName(); + for (cmTargetExport* te : + *this->IEGen->GetExportSet()->GetTargetExports()) { + expectedTargets += sep + this->Namespace + te->Target->GetExportName(); sep = " "; - cmTargetExport* te = *tei; if (this->ExportedTargets.insert(te->Target).second) { allTargets.push_back(te); } else { @@ -76,9 +73,8 @@ bool cmExportInstallFileGenerator::GenerateMainFile(std::ostream& os) bool require3_1_0 = false; bool requiresConfigFiles = false; // Create all the imported targets. - for (std::vector<cmTargetExport*>::const_iterator tei = allTargets.begin(); - tei != allTargets.end(); ++tei) { - cmGeneratorTarget* gt = (*tei)->Target; + for (cmTargetExport* te : allTargets) { + cmGeneratorTarget* gt = te->Target; requiresConfigFiles = requiresConfigFiles || gt->GetType() != cmStateEnums::INTERFACE_LIBRARY; @@ -88,10 +84,8 @@ bool cmExportInstallFileGenerator::GenerateMainFile(std::ostream& os) ImportPropertyMap properties; this->PopulateIncludeDirectoriesInterface( - *tei, cmGeneratorExpression::InstallInterface, properties, - missingTargets); - this->PopulateSourcesInterface(*tei, - cmGeneratorExpression::InstallInterface, + te, cmGeneratorExpression::InstallInterface, properties, missingTargets); + this->PopulateSourcesInterface(te, cmGeneratorExpression::InstallInterface, properties, missingTargets); this->PopulateInterfaceProperty("INTERFACE_SYSTEM_INCLUDE_DIRECTORIES", gt, cmGeneratorExpression::InstallInterface, @@ -154,10 +148,8 @@ bool cmExportInstallFileGenerator::GenerateMainFile(std::ostream& os) // Generate an import file for each configuration. // Don't do this if we only export INTERFACE_LIBRARY targets. if (requiresConfigFiles) { - for (std::vector<std::string>::const_iterator ci = - this->Configurations.begin(); - ci != this->Configurations.end(); ++ci) { - if (!this->GenerateImportFileConfig(*ci, missingTargets)) { + for (std::string const& c : this->Configurations) { + if (!this->GenerateImportFileConfig(c, missingTargets)) { result = false; } } @@ -314,11 +306,8 @@ void cmExportInstallFileGenerator::GenerateImportTargetsConfig( std::vector<std::string>& missingTargets) { // Add each target in the set to the export. - for (std::vector<cmTargetExport*>::const_iterator tei = - this->IEGen->GetExportSet()->GetTargetExports()->begin(); - tei != this->IEGen->GetExportSet()->GetTargetExports()->end(); ++tei) { + for (cmTargetExport* te : *this->IEGen->GetExportSet()->GetTargetExports()) { // Collect import properties for this target. - cmTargetExport const* te = *tei; if (te->Target->GetType() == cmStateEnums::INTERFACE_LIBRARY) { continue; } @@ -409,9 +398,8 @@ void cmExportInstallFileGenerator::SetImportLocationProperty( // IMPORTED_OBJECTS as a list of object files std::vector<std::string> objects; itgen->GetInstallObjectNames(config, objects); - for (std::vector<std::string>::iterator i = objects.begin(); - i != objects.end(); ++i) { - *i = value + *i; + for (std::string& obj : objects) { + obj = value + obj; } // Store the property. @@ -465,15 +453,14 @@ std::vector<std::string> cmExportInstallFileGenerator::FindNamespaces( std::vector<std::string> namespaces; const cmExportSetMap& exportSets = gg->GetExportSets(); - for (cmExportSetMap::const_iterator expIt = exportSets.begin(); - expIt != exportSets.end(); ++expIt) { - const cmExportSet* exportSet = expIt->second; + for (auto const& expIt : exportSets) { + const cmExportSet* exportSet = expIt.second; std::vector<cmTargetExport*> const* targets = exportSet->GetTargetExports(); bool containsTarget = false; - for (unsigned int i = 0; i < targets->size(); i++) { - if (name == (*targets)[i]->TargetName) { + for (cmTargetExport* target : *targets) { + if (name == target->TargetName) { containsTarget = true; break; } @@ -482,8 +469,8 @@ std::vector<std::string> cmExportInstallFileGenerator::FindNamespaces( if (containsTarget) { std::vector<cmInstallExportGenerator const*> const* installs = exportSet->GetInstallations(); - for (unsigned int i = 0; i < installs->size(); i++) { - namespaces.push_back((*installs)[i]->GetNamespace()); + for (cmInstallExportGenerator const* install : *installs) { + namespaces.push_back(install->GetNamespace()); } } } diff --git a/Source/cmExportInstallFileGenerator.h b/Source/cmExportInstallFileGenerator.h index e535873..cda8433 100644 --- a/Source/cmExportInstallFileGenerator.h +++ b/Source/cmExportInstallFileGenerator.h @@ -53,16 +53,16 @@ public: protected: // Implement virtual methods from the superclass. - bool GenerateMainFile(std::ostream& os) CM_OVERRIDE; + bool GenerateMainFile(std::ostream& os) override; void GenerateImportTargetsConfig( std::ostream& os, const std::string& config, std::string const& suffix, - std::vector<std::string>& missingTargets) CM_OVERRIDE; + std::vector<std::string>& missingTargets) override; void HandleMissingTarget(std::string& link_libs, std::vector<std::string>& missingTargets, cmGeneratorTarget* depender, - cmGeneratorTarget* dependee) CM_OVERRIDE; + cmGeneratorTarget* dependee) override; - void ReplaceInstallPrefix(std::string& input) CM_OVERRIDE; + void ReplaceInstallPrefix(std::string& input) override; void ComplainAboutMissingTarget(cmGeneratorTarget* depender, cmGeneratorTarget* dependee, @@ -91,7 +91,7 @@ protected: std::set<std::string>& importedLocations); std::string InstallNameDir(cmGeneratorTarget* target, - const std::string& config) CM_OVERRIDE; + const std::string& config) override; cmInstallExportGenerator* IEGen; diff --git a/Source/cmExportLibraryDependenciesCommand.cxx b/Source/cmExportLibraryDependenciesCommand.cxx index a1fdeae..50f8cb0 100644 --- a/Source/cmExportLibraryDependenciesCommand.cxx +++ b/Source/cmExportLibraryDependenciesCommand.cxx @@ -4,9 +4,10 @@ #include "cmsys/FStream.hxx" #include <map> -#include <unordered_map> +#include <memory> // IWYU pragma: keep #include <utility> +#include "cmAlgorithms.h" #include "cmGeneratedFileStream.h" #include "cmGlobalGenerator.h" #include "cmMakefile.h" @@ -14,7 +15,6 @@ #include "cmSystemTools.h" #include "cmTarget.h" #include "cmTargetLinkLibraryType.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" class cmExecutionStatus; @@ -48,16 +48,15 @@ void cmExportLibraryDependenciesCommand::FinalPass() void cmExportLibraryDependenciesCommand::ConstFinalPass() const { // Use copy-if-different if not appending. - CM_AUTO_PTR<cmsys::ofstream> foutPtr; + std::unique_ptr<cmsys::ofstream> foutPtr; if (this->Append) { - CM_AUTO_PTR<cmsys::ofstream> ap( - new cmsys::ofstream(this->Filename.c_str(), std::ios::app)); - foutPtr = ap; + foutPtr = + cm::make_unique<cmsys::ofstream>(this->Filename.c_str(), std::ios::app); } else { - CM_AUTO_PTR<cmGeneratedFileStream> ap( + std::unique_ptr<cmGeneratedFileStream> ap( new cmGeneratedFileStream(this->Filename.c_str(), true)); ap->SetCopyIfDifferent(true); - foutPtr = ap; + foutPtr = std::move(ap); } std::ostream& fout = *foutPtr; @@ -75,12 +74,11 @@ void cmExportLibraryDependenciesCommand::ConstFinalPass() const std::map<std::string, std::string> libDepsOld; std::map<std::string, std::string> libDepsNew; std::map<std::string, std::string> libTypes; - for (std::vector<cmMakefile*>::const_iterator i = locals.begin(); - i != locals.end(); ++i) { - const cmTargets& tgts = (*i)->GetTargets(); - for (cmTargets::const_iterator l = tgts.begin(); l != tgts.end(); ++l) { + for (cmMakefile* local : locals) { + const cmTargets& tgts = local->GetTargets(); + for (auto const& tgt : tgts) { // Get the current target. - cmTarget const& target = l->second; + cmTarget const& target = tgt.second; // Skip non-library targets. if (target.GetType() < cmStateEnums::STATIC_LIBRARY || @@ -98,12 +96,11 @@ void cmExportLibraryDependenciesCommand::ConstFinalPass() const std::string valueNew; cmTarget::LinkLibraryVectorType const& libs = target.GetOriginalLinkLibraries(); - for (cmTarget::LinkLibraryVectorType::const_iterator li = libs.begin(); - li != libs.end(); ++li) { - std::string ltVar = li->first; + for (cmTarget::LibraryID const& li : libs) { + std::string ltVar = li.first; ltVar += "_LINK_TYPE"; std::string ltValue; - switch (li->second) { + switch (li.second) { case GENERAL_LibraryType: valueNew += "general;"; ltValue = "general"; @@ -117,7 +114,7 @@ void cmExportLibraryDependenciesCommand::ConstFinalPass() const ltValue = "optimized"; break; } - std::string lib = li->first; + std::string lib = li.first; if (cmTarget* libtgt = global->FindTarget(lib)) { // Handle simple output name changes. This command is // deprecated so we do not support full target name @@ -150,26 +147,21 @@ void cmExportLibraryDependenciesCommand::ConstFinalPass() const fout << "# Generated by CMake\n\n"; fout << "if(" << vertest << ")\n"; fout << " # Information for CMake 2.6 and above.\n"; - for (std::map<std::string, std::string>::const_iterator i = - libDepsNew.begin(); - i != libDepsNew.end(); ++i) { - if (!i->second.empty()) { - fout << " set(\"" << i->first << "\" \"" << i->second << "\")\n"; + for (auto const& i : libDepsNew) { + if (!i.second.empty()) { + fout << " set(\"" << i.first << "\" \"" << i.second << "\")\n"; } } fout << "else()\n"; fout << " # Information for CMake 2.4 and lower.\n"; - for (std::map<std::string, std::string>::const_iterator i = - libDepsOld.begin(); - i != libDepsOld.end(); ++i) { - if (!i->second.empty()) { - fout << " set(\"" << i->first << "\" \"" << i->second << "\")\n"; + for (auto const& i : libDepsOld) { + if (!i.second.empty()) { + fout << " set(\"" << i.first << "\" \"" << i.second << "\")\n"; } } - for (std::map<std::string, std::string>::const_iterator i = libTypes.begin(); - i != libTypes.end(); ++i) { - if (i->second != "general") { - fout << " set(\"" << i->first << "\" \"" << i->second << "\")\n"; + for (auto const& i : libTypes) { + if (i.second != "general") { + fout << " set(\"" << i.first << "\" \"" << i.second << "\")\n"; } } fout << "endif()\n"; diff --git a/Source/cmExportLibraryDependenciesCommand.h b/Source/cmExportLibraryDependenciesCommand.h index 286a3e0..bf5e9bc 100644 --- a/Source/cmExportLibraryDependenciesCommand.h +++ b/Source/cmExportLibraryDependenciesCommand.h @@ -15,15 +15,15 @@ class cmExecutionStatus; class cmExportLibraryDependenciesCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { return new cmExportLibraryDependenciesCommand; } bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; - void FinalPass() CM_OVERRIDE; - bool HasFinalPass() const CM_OVERRIDE { return true; } + void FinalPass() override; + bool HasFinalPass() const override { return true; } private: std::string Filename; diff --git a/Source/cmExportSet.cxx b/Source/cmExportSet.cxx index a936679..a6fa186 100644 --- a/Source/cmExportSet.cxx +++ b/Source/cmExportSet.cxx @@ -13,9 +13,8 @@ cmExportSet::~cmExportSet() void cmExportSet::Compute(cmLocalGenerator* lg) { - for (std::vector<cmTargetExport*>::iterator it = this->TargetExports.begin(); - it != this->TargetExports.end(); ++it) { - (*it)->Target = lg->FindGeneratorTargetToUse((*it)->TargetName); + for (cmTargetExport* tgtExport : this->TargetExports) { + tgtExport->Target = lg->FindGeneratorTargetToUse(tgtExport->TargetName); } } diff --git a/Source/cmExportTryCompileFileGenerator.cxx b/Source/cmExportTryCompileFileGenerator.cxx index 54e0e71..1fb9cf8 100644 --- a/Source/cmExportTryCompileFileGenerator.cxx +++ b/Source/cmExportTryCompileFileGenerator.cxx @@ -11,9 +11,9 @@ #include "cmStateTypes.h" #include "cmSystemTools.h" #include "cmTarget.h" -#include "cm_auto_ptr.hxx" #include <map> +#include <memory> // IWYU pragma: keep #include <utility> cmExportTryCompileFileGenerator::cmExportTryCompileFileGenerator( @@ -65,7 +65,7 @@ std::string cmExportTryCompileFileGenerator::FindTargets( cmGeneratorExpressionDAGChecker dagChecker(tgt->GetName(), propName, nullptr, nullptr); - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(prop); + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(prop); cmTarget dummyHead("try_compile_dummy_exe", cmStateEnums::EXECUTABLE, cmTarget::VisibilityNormal, tgt->Target->GetMakefile()); @@ -77,11 +77,9 @@ std::string cmExportTryCompileFileGenerator::FindTargets( const std::set<cmGeneratorTarget const*>& allTargets = cge->GetAllTargetsSeen(); - for (std::set<cmGeneratorTarget const*>::const_iterator li = - allTargets.begin(); - li != allTargets.end(); ++li) { - if (emitted.insert(*li).second) { - this->Exports.push_back(*li); + for (cmGeneratorTarget const* target : allTargets) { + if (emitted.insert(target).second) { + this->Exports.push_back(target); } } return result; @@ -92,22 +90,20 @@ void cmExportTryCompileFileGenerator::PopulateProperties( std::set<cmGeneratorTarget const*>& emitted) { std::vector<std::string> props = target->GetPropertyKeys(); - for (std::vector<std::string>::const_iterator i = props.begin(); - i != props.end(); ++i) { + for (std::string const& p : props) { - properties[*i] = target->GetProperty(*i); + properties[p] = target->GetProperty(p); - if (i->find("IMPORTED_LINK_INTERFACE_LIBRARIES") == 0 || - i->find("IMPORTED_LINK_DEPENDENT_LIBRARIES") == 0 || - i->find("INTERFACE_LINK_LIBRARIES") == 0) { - std::string evalResult = this->FindTargets(*i, target, emitted); + if (p.find("IMPORTED_LINK_INTERFACE_LIBRARIES") == 0 || + p.find("IMPORTED_LINK_DEPENDENT_LIBRARIES") == 0 || + p.find("INTERFACE_LINK_LIBRARIES") == 0) { + std::string evalResult = this->FindTargets(p, target, emitted); std::vector<std::string> depends; cmSystemTools::ExpandListArgument(evalResult, depends); - for (std::vector<std::string>::const_iterator li = depends.begin(); - li != depends.end(); ++li) { + for (std::string const& li : depends) { cmGeneratorTarget* tgt = - target->GetLocalGenerator()->FindGeneratorTargetToUse(*li); + target->GetLocalGenerator()->FindGeneratorTargetToUse(li); if (tgt && emitted.insert(tgt).second) { this->Exports.push_back(tgt); } diff --git a/Source/cmExportTryCompileFileGenerator.h b/Source/cmExportTryCompileFileGenerator.h index 9f6ac03..70c3857 100644 --- a/Source/cmExportTryCompileFileGenerator.h +++ b/Source/cmExportTryCompileFileGenerator.h @@ -27,15 +27,15 @@ public: void SetConfig(const std::string& config) { this->Config = config; } protected: // Implement virtual methods from the superclass. - bool GenerateMainFile(std::ostream& os) CM_OVERRIDE; + bool GenerateMainFile(std::ostream& os) override; void GenerateImportTargetsConfig(std::ostream&, const std::string&, std::string const&, - std::vector<std::string>&) CM_OVERRIDE + std::vector<std::string>&) override { } void HandleMissingTarget(std::string&, std::vector<std::string>&, - cmGeneratorTarget*, cmGeneratorTarget*) CM_OVERRIDE + cmGeneratorTarget*, cmGeneratorTarget*) override { } @@ -44,7 +44,7 @@ protected: std::set<const cmGeneratorTarget*>& emitted); std::string InstallNameDir(cmGeneratorTarget* target, - const std::string& config) CM_OVERRIDE; + const std::string& config) override; private: std::string FindTargets(const std::string& prop, diff --git a/Source/cmExternalMakefileProjectGenerator.h b/Source/cmExternalMakefileProjectGenerator.h index 6b89037..a1734ee 100644 --- a/Source/cmExternalMakefileProjectGenerator.h +++ b/Source/cmExternalMakefileProjectGenerator.h @@ -99,7 +99,7 @@ public: } cmExternalMakefileProjectGenerator* CreateExternalMakefileProjectGenerator() - const CM_OVERRIDE + const override { T* p = new T; p->SetName(GetName()); diff --git a/Source/cmExtraCodeBlocksGenerator.cxx b/Source/cmExtraCodeBlocksGenerator.cxx index 547fc99..9c9b75b 100644 --- a/Source/cmExtraCodeBlocksGenerator.cxx +++ b/Source/cmExtraCodeBlocksGenerator.cxx @@ -63,11 +63,9 @@ cmExtraCodeBlocksGenerator::GetFactory() void cmExtraCodeBlocksGenerator::Generate() { // for each sub project in the project create a codeblocks project - for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator - it = this->GlobalGenerator->GetProjectMap().begin(); - it != this->GlobalGenerator->GetProjectMap().end(); ++it) { + for (auto const& it : this->GlobalGenerator->GetProjectMap()) { // create a project file - this->CreateProjectFile(it->second); + this->CreateProjectFile(it.second); } } @@ -116,15 +114,14 @@ void Tree::InsertPath(const std::vector<std::string>& splitted, files.insert(fileName); return; } - for (std::vector<Tree>::iterator it = folders.begin(); it != folders.end(); - ++it) { - if ((*it).path == splitted[start]) { + for (Tree& folder : folders) { + if (folder.path == splitted[start]) { if (start + 1 < splitted.size()) { - it->InsertPath(splitted, start + 1, fileName); + folder.InsertPath(splitted, start + 1, fileName); return; } // last part of splitted - it->files.insert(fileName); + folder.files.insert(fileName); return; } } @@ -145,9 +142,8 @@ void Tree::BuildVirtualFolder(cmXMLWriter& xml) const { xml.StartElement("Option"); std::string virtualFolders = "CMake Files\\;"; - for (std::vector<Tree>::const_iterator it = folders.begin(); - it != folders.end(); ++it) { - it->BuildVirtualFolderImpl(virtualFolders, ""); + for (Tree const& folder : folders) { + folder.BuildVirtualFolderImpl(virtualFolders, ""); } xml.Attribute("virtualFolders", virtualFolders); xml.EndElement(); @@ -157,18 +153,16 @@ void Tree::BuildVirtualFolderImpl(std::string& virtualFolders, const std::string& prefix) const { virtualFolders += "CMake Files\\" + prefix + path + "\\;"; - for (std::vector<Tree>::const_iterator it = folders.begin(); - it != folders.end(); ++it) { - it->BuildVirtualFolderImpl(virtualFolders, prefix + path + "\\"); + for (Tree const& folder : folders) { + folder.BuildVirtualFolderImpl(virtualFolders, prefix + path + "\\"); } } void Tree::BuildUnit(cmXMLWriter& xml, const std::string& fsPath) const { - for (std::set<std::string>::const_iterator it = files.begin(); - it != files.end(); ++it) { + for (std::string const& f : files) { xml.StartElement("Unit"); - xml.Attribute("filename", fsPath + *it); + xml.Attribute("filename", fsPath + f); xml.StartElement("Option"); xml.Attribute("virtualFolder", "CMake Files\\"); @@ -176,9 +170,8 @@ void Tree::BuildUnit(cmXMLWriter& xml, const std::string& fsPath) const xml.EndElement(); } - for (std::vector<Tree>::const_iterator it = folders.begin(); - it != folders.end(); ++it) { - it->BuildUnitImpl(xml, "", fsPath); + for (Tree const& folder : folders) { + folder.BuildUnitImpl(xml, "", fsPath); } } @@ -186,10 +179,9 @@ void Tree::BuildUnitImpl(cmXMLWriter& xml, const std::string& virtualFolderPath, const std::string& fsPath) const { - for (std::set<std::string>::const_iterator it = files.begin(); - it != files.end(); ++it) { + for (std::string const& f : files) { xml.StartElement("Unit"); - xml.Attribute("filename", fsPath + path + "/" + *it); + xml.Attribute("filename", fsPath + path + "/" + f); xml.StartElement("Option"); xml.Attribute("virtualFolder", @@ -198,10 +190,9 @@ void Tree::BuildUnitImpl(cmXMLWriter& xml, xml.EndElement(); } - for (std::vector<Tree>::const_iterator it = folders.begin(); - it != folders.end(); ++it) { - it->BuildUnitImpl(xml, virtualFolderPath + path + "\\", - fsPath + path + "/"); + for (Tree const& folder : folders) { + folder.BuildUnitImpl(xml, virtualFolderPath + path + "\\", + fsPath + path + "/"); } } @@ -217,29 +208,24 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile( Tree tree; // build tree of virtual folders - for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator - it = this->GlobalGenerator->GetProjectMap().begin(); - it != this->GlobalGenerator->GetProjectMap().end(); ++it) { + for (auto const& it : this->GlobalGenerator->GetProjectMap()) { // Collect all files std::vector<std::string> listFiles; - for (std::vector<cmLocalGenerator*>::const_iterator jt = - it->second.begin(); - jt != it->second.end(); ++jt) { + for (cmLocalGenerator* lg : it.second) { const std::vector<std::string>& files = - (*jt)->GetMakefile()->GetListFiles(); + lg->GetMakefile()->GetListFiles(); listFiles.insert(listFiles.end(), files.begin(), files.end()); } // Convert - for (std::vector<std::string>::const_iterator jt = listFiles.begin(); - jt != listFiles.end(); ++jt) { + for (std::string const& listFile : listFiles) { // don't put cmake's own files into the project (#12110): - if (jt->find(cmSystemTools::GetCMakeRoot()) == 0) { + if (listFile.find(cmSystemTools::GetCMakeRoot()) == 0) { continue; } const std::string& relative = cmSystemTools::RelativePath( - it->second[0]->GetSourceDirectory(), jt->c_str()); + it.second[0]->GetSourceDirectory(), listFile.c_str()); std::vector<std::string> splitted; cmSystemTools::SplitPath(relative, splitted, false); // Split filename from path @@ -249,7 +235,14 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile( // We don't want paths with CMakeFiles in them // or do we? // In speedcrunch those where purely internal + // + // Also we can disable external (outside the project) files by setting ON + // CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES variable. + const bool excludeExternal = + cmSystemTools::IsOn(it.second[0]->GetMakefile()->GetSafeDefinition( + "CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES")); if (!splitted.empty() && + (!excludeExternal || (relative.find("..") == std::string::npos)) && relative.find("CMakeFiles") == std::string::npos) { tree.InsertPath(splitted, 1, fileName); } @@ -295,20 +288,17 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile( // add all executable and library targets and some of the GLOBAL // and UTILITY targets - for (std::vector<cmLocalGenerator*>::const_iterator lg = lgs.begin(); - lg != lgs.end(); lg++) { - const std::vector<cmGeneratorTarget*>& targets = - (*lg)->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator ti = targets.begin(); - ti != targets.end(); ti++) { - std::string targetName = (*ti)->GetName(); - switch ((*ti)->GetType()) { + for (cmLocalGenerator* lg : lgs) { + const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets(); + for (cmGeneratorTarget* target : targets) { + std::string targetName = target->GetName(); + switch (target->GetType()) { case cmStateEnums::GLOBAL_TARGET: { // Only add the global targets from CMAKE_BINARY_DIR, // not from the subdirs - if (strcmp((*lg)->GetCurrentBinaryDirectory(), - (*lg)->GetBinaryDirectory()) == 0) { - this->AppendTarget(xml, targetName, nullptr, make.c_str(), *lg, + if (strcmp(lg->GetCurrentBinaryDirectory(), + lg->GetBinaryDirectory()) == 0) { + this->AppendTarget(xml, targetName, nullptr, make.c_str(), lg, compiler.c_str(), makeArgs); } } break; @@ -324,7 +314,7 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile( break; } - this->AppendTarget(xml, targetName, nullptr, make.c_str(), *lg, + this->AppendTarget(xml, targetName, nullptr, make.c_str(), lg, compiler.c_str(), makeArgs); break; case cmStateEnums::EXECUTABLE: @@ -332,12 +322,12 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile( case cmStateEnums::SHARED_LIBRARY: case cmStateEnums::MODULE_LIBRARY: case cmStateEnums::OBJECT_LIBRARY: { - cmGeneratorTarget* gt = *ti; - this->AppendTarget(xml, targetName, gt, make.c_str(), *lg, + cmGeneratorTarget* gt = target; + this->AppendTarget(xml, targetName, gt, make.c_str(), lg, compiler.c_str(), makeArgs); std::string fastTarget = targetName; fastTarget += "/fast"; - this->AppendTarget(xml, fastTarget, gt, make.c_str(), *lg, + this->AppendTarget(xml, fastTarget, gt, make.c_str(), lg, compiler.c_str(), makeArgs); } break; default: @@ -358,14 +348,11 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile( std::vector<std::string> const& srcExts = this->GlobalGenerator->GetCMakeInstance()->GetSourceExtensions(); - for (std::vector<cmLocalGenerator*>::const_iterator lg = lgs.begin(); - lg != lgs.end(); lg++) { - cmMakefile* makefile = (*lg)->GetMakefile(); - const std::vector<cmGeneratorTarget*>& targets = - (*lg)->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator ti = targets.begin(); - ti != targets.end(); ti++) { - switch ((*ti)->GetType()) { + for (cmLocalGenerator* lg : lgs) { + cmMakefile* makefile = lg->GetMakefile(); + const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets(); + for (cmGeneratorTarget* target : targets) { + switch (target->GetType()) { case cmStateEnums::EXECUTABLE: case cmStateEnums::STATIC_LIBRARY: case cmStateEnums::SHARED_LIBRARY: @@ -374,41 +361,51 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile( case cmStateEnums::UTILITY: // can have sources since 2.6.3 { std::vector<cmSourceFile*> sources; - cmGeneratorTarget* gt = *ti; + cmGeneratorTarget* gt = target; gt->GetSourceFiles(sources, makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")); - for (std::vector<cmSourceFile*>::const_iterator si = sources.begin(); - si != sources.end(); si++) { + for (cmSourceFile* s : sources) { // don't add source files from UTILITY target which have the // GENERATED property set: if (gt->GetType() == cmStateEnums::UTILITY && - (*si)->GetPropertyAsBool("GENERATED")) { + s->GetPropertyAsBool("GENERATED")) { continue; } // check whether it is a C/C++ implementation file bool isCFile = false; - std::string lang = (*si)->GetLanguage(); + std::string lang = s->GetLanguage(); if (lang == "C" || lang == "CXX") { - std::string const& srcext = (*si)->GetExtension(); - for (std::vector<std::string>::const_iterator ext = - srcExts.begin(); - ext != srcExts.end(); ++ext) { - if (srcext == *ext) { + std::string const& srcext = s->GetExtension(); + for (std::string const& ext : srcExts) { + if (srcext == ext) { isCFile = true; break; } } } - std::string const& fullPath = (*si)->GetFullPath(); + std::string const& fullPath = s->GetFullPath(); + + // Check file position relative to project root dir. + const std::string& relative = cmSystemTools::RelativePath( + (*lg).GetSourceDirectory(), fullPath.c_str()); + // Do not add this file if it has ".." in relative path and + // if CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES variable is on. + const bool excludeExternal = + cmSystemTools::IsOn((*lg).GetMakefile()->GetSafeDefinition( + "CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES")); + if (excludeExternal && + (relative.find("..") != std::string::npos)) { + continue; + } if (isCFile) { cFiles.push_back(fullPath); } CbpUnit& cbpUnit = allFiles[fullPath]; - cbpUnit.Targets.push_back(*ti); + cbpUnit.Targets.push_back(target); } } default: // intended fallthrough @@ -427,19 +424,16 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile( // file exists. If it does, it is inserted into the map of files. // A very similar version of that code exists also in the kdevelop // project generator. - for (std::vector<std::string>::const_iterator sit = cFiles.begin(); - sit != cFiles.end(); ++sit) { - std::string const& fileName = *sit; + for (std::string const& fileName : cFiles) { std::string headerBasename = cmSystemTools::GetFilenamePath(fileName); headerBasename += "/"; headerBasename += cmSystemTools::GetFilenameWithoutExtension(fileName); // check if there's a matching header around - for (std::vector<std::string>::const_iterator ext = headerExts.begin(); - ext != headerExts.end(); ++ext) { + for (std::string const& ext : headerExts) { std::string hname = headerBasename; hname += "."; - hname += *ext; + hname += ext; // if it's already in the set, don't check if it exists on disk if (allFiles.find(hname) != allFiles.end()) { break; @@ -453,19 +447,16 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile( } // insert all source files in the CodeBlocks project - for (all_files_map_t::const_iterator sit = allFiles.begin(); - sit != allFiles.end(); ++sit) { - std::string const& unitFilename = sit->first; - CbpUnit const& unit = sit->second; + for (auto const& s : allFiles) { + std::string const& unitFilename = s.first; + CbpUnit const& unit = s.second; xml.StartElement("Unit"); xml.Attribute("filename", unitFilename); - for (std::vector<const cmGeneratorTarget*>::const_iterator ti = - unit.Targets.begin(); - ti != unit.Targets.end(); ++ti) { + for (cmGeneratorTarget const* tgt : unit.Targets) { xml.StartElement("Option"); - xml.Attribute("target", (*ti)->GetName()); + xml.Attribute("target", tgt->GetName()); xml.EndElement(); } @@ -575,10 +566,9 @@ void cmExtraCodeBlocksGenerator::AppendTarget( target->GetCompileDefinitions(cdefs, buildType, "C"); // Expand the list. - for (std::vector<std::string>::const_iterator di = cdefs.begin(); - di != cdefs.end(); ++di) { + for (std::string const& d : cdefs) { xml.StartElement("Add"); - xml.Attribute("option", "-D" + *di); + xml.Attribute("option", "-D" + d); xml.EndElement(); } diff --git a/Source/cmExtraCodeBlocksGenerator.h b/Source/cmExtraCodeBlocksGenerator.h index 9397733..be3af25 100644 --- a/Source/cmExtraCodeBlocksGenerator.h +++ b/Source/cmExtraCodeBlocksGenerator.h @@ -25,7 +25,7 @@ public: static cmExternalMakefileProjectGeneratorFactory* GetFactory(); - void Generate() CM_OVERRIDE; + void Generate() override; private: struct CbpUnit diff --git a/Source/cmExtraCodeLiteGenerator.cxx b/Source/cmExtraCodeLiteGenerator.cxx index 96502d5..5a02d54 100644 --- a/Source/cmExtraCodeLiteGenerator.cxx +++ b/Source/cmExtraCodeLiteGenerator.cxx @@ -54,26 +54,24 @@ void cmExtraCodeLiteGenerator::Generate() std::string workspaceFileName; std::string workspaceSourcePath; - const std::map<std::string, std::vector<cmLocalGenerator*> >& projectMap = + const std::map<std::string, std::vector<cmLocalGenerator*>>& projectMap = this->GlobalGenerator->GetProjectMap(); // loop projects and locate the root project. // and extract the information for creating the worspace // root makefile - for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator - it = projectMap.begin(); - it != projectMap.end(); ++it) { - const cmMakefile* mf = it->second[0]->GetMakefile(); + for (auto const& it : projectMap) { + const cmMakefile* mf = it.second[0]->GetMakefile(); this->ConfigName = GetConfigurationName(mf); - if (strcmp(it->second[0]->GetCurrentBinaryDirectory(), - it->second[0]->GetBinaryDirectory()) == 0) { - workspaceOutputDir = it->second[0]->GetCurrentBinaryDirectory(); - workspaceProjectName = it->second[0]->GetProjectName(); - workspaceSourcePath = it->second[0]->GetSourceDirectory(); + if (strcmp(it.second[0]->GetCurrentBinaryDirectory(), + it.second[0]->GetBinaryDirectory()) == 0) { + workspaceOutputDir = it.second[0]->GetCurrentBinaryDirectory(); + workspaceProjectName = it.second[0]->GetProjectName(); + workspaceSourcePath = it.second[0]->GetSourceDirectory(); workspaceFileName = workspaceOutputDir + "/"; workspaceFileName += workspaceProjectName + ".workspace"; - this->WorkspacePath = it->second[0]->GetCurrentBinaryDirectory(); + this->WorkspacePath = it.second[0]->GetCurrentBinaryDirectory(); ; break; } @@ -101,10 +99,9 @@ void cmExtraCodeLiteGenerator::Generate() xml.Attribute("Name", this->ConfigName); xml.Attribute("Selected", "yes"); - for (std::vector<std::string>::iterator it(ProjectNames.begin()); - it != ProjectNames.end(); it++) { + for (std::string const& it : ProjectNames) { xml.StartElement("Project"); - xml.Attribute("Name", *it); + xml.Attribute("Name", it); xml.Attribute("ConfigName", this->ConfigName); xml.EndElement(); } @@ -122,14 +119,11 @@ std::vector<std::string> cmExtraCodeLiteGenerator::CreateProjectsByTarget( // for each target in the workspace create a codelite project const std::vector<cmLocalGenerator*>& lgs = this->GlobalGenerator->GetLocalGenerators(); - for (std::vector<cmLocalGenerator*>::const_iterator lg(lgs.begin()); - lg != lgs.end(); lg++) { - for (std::vector<cmGeneratorTarget*>::const_iterator lt = - (*lg)->GetGeneratorTargets().begin(); - lt != (*lg)->GetGeneratorTargets().end(); lt++) { - cmStateEnums::TargetType type = (*lt)->GetType(); - std::string outputDir = (*lg)->GetCurrentBinaryDirectory(); - std::string targetName = (*lt)->GetName(); + for (cmLocalGenerator* lg : lgs) { + for (cmGeneratorTarget* lt : lg->GetGeneratorTargets()) { + cmStateEnums::TargetType type = lt->GetType(); + std::string outputDir = lg->GetCurrentBinaryDirectory(); + std::string targetName = lt->GetName(); std::string filename = outputDir + "/" + targetName + ".project"; retval.push_back(targetName); // Make the project file relative to the workspace @@ -149,7 +143,7 @@ std::vector<std::string> cmExtraCodeLiteGenerator::CreateProjectsByTarget( xml->Attribute("Active", "No"); xml->EndElement(); - CreateNewProjectFile(*lt, filename); + CreateNewProjectFile(lt, filename); break; default: break; @@ -165,12 +159,10 @@ std::vector<std::string> cmExtraCodeLiteGenerator::CreateProjectsByProjectMaps( { std::vector<std::string> retval; // for each sub project in the workspace create a codelite project - for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator - it = this->GlobalGenerator->GetProjectMap().begin(); - it != this->GlobalGenerator->GetProjectMap().end(); it++) { + for (auto const& it : this->GlobalGenerator->GetProjectMap()) { - std::string outputDir = it->second[0]->GetCurrentBinaryDirectory(); - std::string projectName = it->second[0]->GetProjectName(); + std::string outputDir = it.second[0]->GetCurrentBinaryDirectory(); + std::string projectName = it.second[0]->GetProjectName(); retval.push_back(projectName); std::string filename = outputDir + "/" + projectName + ".project"; @@ -179,7 +171,7 @@ std::vector<std::string> cmExtraCodeLiteGenerator::CreateProjectsByProjectMaps( filename.c_str()); // create a project file - this->CreateProjectFile(it->second); + this->CreateProjectFile(it.second); xml->StartElement("Project"); xml->Attribute("Name", projectName); xml->Attribute("Path", filename); @@ -235,16 +227,14 @@ std::string cmExtraCodeLiteGenerator::CollectSourceFiles( std::vector<cmSourceFile*> sources; gt->GetSourceFiles(sources, makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")); - for (std::vector<cmSourceFile*>::const_iterator si = sources.begin(); - si != sources.end(); si++) { + for (cmSourceFile* s : sources) { // check whether it is a C/C++ implementation file bool isCFile = false; - std::string lang = (*si)->GetLanguage(); + std::string lang = s->GetLanguage(); if (lang == "C" || lang == "CXX") { - std::string const& srcext = (*si)->GetExtension(); - for (std::vector<std::string>::const_iterator ext = srcExts.begin(); - ext != srcExts.end(); ++ext) { - if (srcext == *ext) { + std::string const& srcext = s->GetExtension(); + for (std::string const& ext : srcExts) { + if (srcext == ext) { isCFile = true; break; } @@ -253,9 +243,9 @@ std::string cmExtraCodeLiteGenerator::CollectSourceFiles( // then put it accordingly into one of the two containers if (isCFile) { - cFiles[(*si)->GetFullPath()] = *si; + cFiles[s->GetFullPath()] = s; } else { - otherFiles.insert((*si)->GetFullPath()); + otherFiles.insert(s->GetFullPath()); } } } @@ -289,14 +279,11 @@ void cmExtraCodeLiteGenerator::CreateNewProjectFile( std::map<std::string, cmSourceFile*> cFiles; std::set<std::string> otherFiles; - for (std::vector<cmLocalGenerator*>::const_iterator lg = lgs.begin(); - lg != lgs.end(); lg++) { - cmMakefile* makefile = (*lg)->GetMakefile(); - const std::vector<cmGeneratorTarget*>& targets = - (*lg)->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator ti = targets.begin(); - ti != targets.end(); ti++) { - projectType = CollectSourceFiles(makefile, *ti, cFiles, otherFiles); + for (cmLocalGenerator* lg : lgs) { + cmMakefile* makefile = lg->GetMakefile(); + const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets(); + for (cmGeneratorTarget* target : targets) { + projectType = CollectSourceFiles(makefile, target, cFiles, otherFiles); } } @@ -324,19 +311,16 @@ void cmExtraCodeLiteGenerator::FindMatchingHeaderfiles( // file exists. If it does, it is inserted into the map of files. // A very similar version of that code exists also in the kdevelop // project generator. - for (std::map<std::string, cmSourceFile*>::const_iterator sit = - cFiles.begin(); - sit != cFiles.end(); ++sit) { - std::string headerBasename = cmSystemTools::GetFilenamePath(sit->first); + for (auto const& sit : cFiles) { + std::string headerBasename = cmSystemTools::GetFilenamePath(sit.first); headerBasename += "/"; - headerBasename += cmSystemTools::GetFilenameWithoutExtension(sit->first); + headerBasename += cmSystemTools::GetFilenameWithoutExtension(sit.first); // check if there's a matching header around - for (std::vector<std::string>::const_iterator ext = headerExts.begin(); - ext != headerExts.end(); ++ext) { + for (std::string const& ext : headerExts) { std::string hname = headerBasename; hname += "."; - hname += *ext; + hname += ext; // if it's already in the set, don't check if it exists on disk std::set<std::string>::const_iterator headerIt = otherFiles.find(hname); if (headerIt != otherFiles.end()) { @@ -359,10 +343,9 @@ void cmExtraCodeLiteGenerator::CreateFoldersAndFiles( std::vector<std::string> components; size_t numOfEndEl = 0; - for (std::set<std::string>::const_iterator it = cFiles.begin(); - it != cFiles.end(); ++it) { + for (std::string const& cFile : cFiles) { std::string frelapath = - cmSystemTools::RelativePath(projectPath.c_str(), it->c_str()); + cmSystemTools::RelativePath(projectPath.c_str(), cFile.c_str()); cmsys::SystemTools::SplitPath(frelapath, components, false); components.pop_back(); // erase last member -> it is file, not folder components.erase(components.begin()); // erase "root" @@ -424,10 +407,8 @@ void cmExtraCodeLiteGenerator::CreateFoldersAndFiles( const std::string& projectPath) { std::set<std::string> s; - for (std::map<std::string, cmSourceFile*>::const_iterator it = - cFiles.begin(); - it != cFiles.end(); ++it) { - s.insert(it->first); + for (auto const& it : cFiles) { + s.insert(it.first); } this->CreateFoldersAndFiles(s, xml, projectPath); } diff --git a/Source/cmExtraCodeLiteGenerator.h b/Source/cmExtraCodeLiteGenerator.h index 549802e..029054f 100644 --- a/Source/cmExtraCodeLiteGenerator.h +++ b/Source/cmExtraCodeLiteGenerator.h @@ -60,7 +60,7 @@ public: static cmExternalMakefileProjectGeneratorFactory* GetFactory(); - void Generate() CM_OVERRIDE; + void Generate() override; void CreateProjectFile(const std::vector<cmLocalGenerator*>& lgs); void CreateNewProjectFile(const std::vector<cmLocalGenerator*>& lgs, diff --git a/Source/cmExtraEclipseCDT4Generator.cxx b/Source/cmExtraEclipseCDT4Generator.cxx index 684d1f5..a200385 100644 --- a/Source/cmExtraEclipseCDT4Generator.cxx +++ b/Source/cmExtraEclipseCDT4Generator.cxx @@ -5,7 +5,6 @@ #include "cmsys/RegularExpression.hxx" #include <algorithm> #include <assert.h> -#include <map> #include <sstream> #include <stdio.h> #include <utility> @@ -78,16 +77,15 @@ void cmExtraEclipseCDT4Generator::EnableLanguage( std::vector<std::string> const& languages, cmMakefile* /*unused*/, bool /*optional*/) { - for (std::vector<std::string>::const_iterator lit = languages.begin(); - lit != languages.end(); ++lit) { - if (*lit == "CXX") { + for (std::string const& l : languages) { + if (l == "CXX") { this->Natures.insert("org.eclipse.cdt.core.ccnature"); this->Natures.insert("org.eclipse.cdt.core.cnature"); this->CXXEnabled = true; - } else if (*lit == "C") { + } else if (l == "C") { this->Natures.insert("org.eclipse.cdt.core.cnature"); this->CEnabled = true; - } else if (*lit == "Java") { + } else if (l == "Java") { this->Natures.insert("org.eclipse.jdt.core.javanature"); } } @@ -224,7 +222,7 @@ void cmExtraEclipseCDT4Generator::AddEnvVar(std::ostream& out, std::string valueToUse; if (!envVarSet && cacheValue == nullptr) { // nothing known, do nothing - valueToUse = ""; + valueToUse.clear(); } else if (envVarSet && cacheValue == nullptr) { // The variable is in the env, but not in the cache. Use it and put it // in the cache @@ -382,18 +380,16 @@ void cmExtraEclipseCDT4Generator::CreateProjectFile() xml.Element("nature", "org.eclipse.cdt.make.core.ScannerConfigNature"); ; - for (std::set<std::string>::const_iterator nit = this->Natures.begin(); - nit != this->Natures.end(); ++nit) { - xml.Element("nature", *nit); + for (std::string const& n : this->Natures) { + xml.Element("nature", n); } if (const char* extraNaturesProp = mf->GetState()->GetGlobalProperty("ECLIPSE_EXTRA_NATURES")) { std::vector<std::string> extraNatures; cmSystemTools::ExpandListArgument(extraNaturesProp, extraNatures); - for (std::vector<std::string>::const_iterator nit = extraNatures.begin(); - nit != extraNatures.end(); ++nit) { - xml.Element("nature", *nit); + for (std::string const& n : extraNatures) { + xml.Element("nature", n); } } @@ -435,25 +431,22 @@ void cmExtraEclipseCDT4Generator::WriteGroups( std::vector<cmSourceGroup> const& sourceGroups, std::string& linkName, cmXMLWriter& xml) { - for (std::vector<cmSourceGroup>::const_iterator sgIt = sourceGroups.begin(); - sgIt != sourceGroups.end(); ++sgIt) { + for (cmSourceGroup const& sg : sourceGroups) { std::string linkName3 = linkName; linkName3 += "/"; - linkName3 += sgIt->GetFullName(); + linkName3 += sg.GetFullName(); std::replace(linkName3.begin(), linkName3.end(), '\\', '/'); this->AppendLinkedResource(xml, linkName3, "virtual:/virtual", VirtualFolder); - std::vector<cmSourceGroup> const& children = sgIt->GetGroupChildren(); + std::vector<cmSourceGroup> const& children = sg.GetGroupChildren(); if (!children.empty()) { this->WriteGroups(children, linkName, xml); } - std::vector<const cmSourceFile*> sFiles = sgIt->GetSourceFiles(); - for (std::vector<const cmSourceFile*>::const_iterator fileIt = - sFiles.begin(); - fileIt != sFiles.end(); ++fileIt) { - std::string const& fullPath = (*fileIt)->GetFullPath(); + std::vector<const cmSourceFile*> sFiles = sg.GetSourceFiles(); + for (cmSourceFile const* file : sFiles) { + std::string const& fullPath = file->GetFullPath(); if (!cmSystemTools::FileIsDirectory(fullPath)) { std::string linkName4 = linkName3; @@ -471,28 +464,24 @@ void cmExtraEclipseCDT4Generator::CreateLinksForTargets(cmXMLWriter& xml) std::string linkName = "[Targets]"; this->AppendLinkedResource(xml, linkName, "virtual:/virtual", VirtualFolder); - for (std::vector<cmLocalGenerator*>::const_iterator lgIt = - this->GlobalGenerator->GetLocalGenerators().begin(); - lgIt != this->GlobalGenerator->GetLocalGenerators().end(); ++lgIt) { - cmMakefile* makefile = (*lgIt)->GetMakefile(); - const std::vector<cmGeneratorTarget*>& targets = - (*lgIt)->GetGeneratorTargets(); + for (cmLocalGenerator* lg : this->GlobalGenerator->GetLocalGenerators()) { + cmMakefile* makefile = lg->GetMakefile(); + const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator ti = targets.begin(); - ti != targets.end(); ++ti) { + for (cmGeneratorTarget* target : targets) { std::string linkName2 = linkName; linkName2 += "/"; - switch ((*ti)->GetType()) { + switch (target->GetType()) { case cmStateEnums::EXECUTABLE: case cmStateEnums::STATIC_LIBRARY: case cmStateEnums::SHARED_LIBRARY: case cmStateEnums::MODULE_LIBRARY: case cmStateEnums::OBJECT_LIBRARY: { const char* prefix = - ((*ti)->GetType() == cmStateEnums::EXECUTABLE ? "[exe] " - : "[lib] "); + (target->GetType() == cmStateEnums::EXECUTABLE ? "[exe] " + : "[lib] "); linkName2 += prefix; - linkName2 += (*ti)->GetName(); + linkName2 += target->GetName(); this->AppendLinkedResource(xml, linkName2, "virtual:/virtual", VirtualFolder); if (!this->GenerateLinkedResources) { @@ -501,17 +490,16 @@ void cmExtraEclipseCDT4Generator::CreateLinksForTargets(cmXMLWriter& xml) std::vector<cmSourceGroup> sourceGroups = makefile->GetSourceGroups(); // get the files from the source lists then add them to the groups - cmGeneratorTarget* gt = const_cast<cmGeneratorTarget*>(*ti); + cmGeneratorTarget* gt = const_cast<cmGeneratorTarget*>(target); std::vector<cmSourceFile*> files; gt->GetSourceFiles(files, makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")); - for (std::vector<cmSourceFile*>::const_iterator sfIt = files.begin(); - sfIt != files.end(); sfIt++) { + for (cmSourceFile* sf : files) { // Add the file to the list of sources. - std::string const& source = (*sfIt)->GetFullPath(); + std::string const& source = sf->GetFullPath(); cmSourceGroup* sourceGroup = makefile->FindSourceGroup(source.c_str(), sourceGroups); - sourceGroup->AssignSource(*sfIt); + sourceGroup->AssignSource(sf); } this->WriteGroups(sourceGroups, linkName2, xml); @@ -536,17 +524,15 @@ void cmExtraEclipseCDT4Generator::CreateLinksToSubprojects( this->AppendLinkedResource(xml, "[Subprojects]", "virtual:/virtual", VirtualFolder); - for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator - it = this->GlobalGenerator->GetProjectMap().begin(); - it != this->GlobalGenerator->GetProjectMap().end(); ++it) { + for (auto const& it : this->GlobalGenerator->GetProjectMap()) { std::string linkSourceDirectory = - this->GetEclipsePath(it->second[0]->GetCurrentSourceDirectory()); + this->GetEclipsePath(it.second[0]->GetCurrentSourceDirectory()); // a linked resource must not point to a parent directory of .project or // .project itself if ((baseDir != linkSourceDirectory) && !cmSystemTools::IsSubDirectory(baseDir, linkSourceDirectory)) { std::string linkName = "[Subprojects]/"; - linkName += it->first; + linkName += it.first; this->AppendLinkedResource(xml, linkName, this->GetEclipsePath(linkSourceDirectory), LinkToFolder); @@ -560,10 +546,9 @@ void cmExtraEclipseCDT4Generator::AppendIncludeDirectories( cmXMLWriter& xml, const std::vector<std::string>& includeDirs, std::set<std::string>& emittedDirs) { - for (std::vector<std::string>::const_iterator inc = includeDirs.begin(); - inc != includeDirs.end(); ++inc) { - if (!inc->empty()) { - std::string dir = cmSystemTools::CollapseFullPath(*inc); + for (std::string const& inc : includeDirs) { + if (!inc.empty()) { + std::string dir = cmSystemTools::CollapseFullPath(inc); // handle framework include dirs on OSX, the remainder after the // Frameworks/ part has to be stripped @@ -712,19 +697,17 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const xml.EndElement(); } - for (std::vector<std::string>::const_iterator it = - this->SrcLinkedResources.begin(); - it != this->SrcLinkedResources.end(); ++it) { + for (std::string const& p : this->SrcLinkedResources) { xml.StartElement("pathentry"); xml.Attribute("kind", "src"); - xml.Attribute("path", *it); + xml.Attribute("path", p); xml.EndElement(); // exlude source directory from output search path // - only if not named the same as an output directory if (!cmSystemTools::FileIsDirectory( - std::string(this->HomeOutputDirectory + "/" + *it))) { - excludeFromOut += *it + "/|"; + std::string(this->HomeOutputDirectory + "/" + p))) { + excludeFromOut += p + "/|"; } } @@ -738,34 +721,31 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const // add pre-processor definitions to allow eclipse to gray out sections emmited.clear(); - for (std::vector<cmLocalGenerator*>::const_iterator it = - this->GlobalGenerator->GetLocalGenerators().begin(); - it != this->GlobalGenerator->GetLocalGenerators().end(); ++it) { + for (cmLocalGenerator* lgen : this->GlobalGenerator->GetLocalGenerators()) { if (const char* cdefs = - (*it)->GetMakefile()->GetProperty("COMPILE_DEFINITIONS")) { + lgen->GetMakefile()->GetProperty("COMPILE_DEFINITIONS")) { // Expand the list. std::vector<std::string> defs; cmGeneratorExpression::Split(cdefs, defs); - for (std::vector<std::string>::const_iterator di = defs.begin(); - di != defs.end(); ++di) { - if (cmGeneratorExpression::Find(*di) != std::string::npos) { + for (std::string const& d : defs) { + if (cmGeneratorExpression::Find(d) != std::string::npos) { continue; } - std::string::size_type equals = di->find('=', 0); - std::string::size_type enddef = di->length(); + std::string::size_type equals = d.find('=', 0); + std::string::size_type enddef = d.length(); std::string def; std::string val; if (equals != std::string::npos && equals < enddef) { // we have -DFOO=BAR - def = di->substr(0, equals); - val = di->substr(equals + 1, enddef - equals + 1); + def = d.substr(0, equals); + val = d.substr(equals + 1, enddef - equals + 1); } else { // we have -DFOO - def = *di; + def = d; } // insert the definition if not already added. @@ -850,16 +830,13 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const // include dirs emmited.clear(); - for (std::vector<cmLocalGenerator*>::const_iterator it = - this->GlobalGenerator->GetLocalGenerators().begin(); - it != this->GlobalGenerator->GetLocalGenerators().end(); ++it) { + for (cmLocalGenerator* lgen : this->GlobalGenerator->GetLocalGenerators()) { const std::vector<cmGeneratorTarget*>& targets = - (*it)->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator l = targets.begin(); - l != targets.end(); ++l) { + lgen->GetGeneratorTargets(); + for (cmGeneratorTarget* target : targets) { std::vector<std::string> includeDirs; std::string config = mf->GetSafeDefinition("CMAKE_BUILD_TYPE"); - (*it)->GetIncludeDirectories(includeDirs, *l, "C", config); + lgen->GetIncludeDirectories(includeDirs, target, "C", config); this->AppendIncludeDirectories(xml, includeDirs, emmited); } } @@ -908,21 +885,18 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const // add all executable and library targets and some of the GLOBAL // and UTILITY targets - for (std::vector<cmLocalGenerator*>::const_iterator it = - this->GlobalGenerator->GetLocalGenerators().begin(); - it != this->GlobalGenerator->GetLocalGenerators().end(); ++it) { + for (cmLocalGenerator* lgen : this->GlobalGenerator->GetLocalGenerators()) { const std::vector<cmGeneratorTarget*>& targets = - (*it)->GetGeneratorTargets(); - std::string subdir = (*it)->ConvertToRelativePath( - this->HomeOutputDirectory, (*it)->GetCurrentBinaryDirectory()); + lgen->GetGeneratorTargets(); + std::string subdir = lgen->ConvertToRelativePath( + this->HomeOutputDirectory, lgen->GetCurrentBinaryDirectory()); if (subdir == ".") { - subdir = ""; + subdir.clear(); } - for (std::vector<cmGeneratorTarget*>::const_iterator ti = targets.begin(); - ti != targets.end(); ++ti) { - std::string targetName = (*ti)->GetName(); - switch ((*ti)->GetType()) { + for (cmGeneratorTarget* target : targets) { + std::string targetName = target->GetName(); + switch (target->GetType()) { case cmStateEnums::GLOBAL_TARGET: { // Only add the global targets from CMAKE_BINARY_DIR, // not from the subdirs @@ -950,8 +924,8 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const case cmStateEnums::MODULE_LIBRARY: case cmStateEnums::OBJECT_LIBRARY: { const char* prefix = - ((*ti)->GetType() == cmStateEnums::EXECUTABLE ? "[exe] " - : "[lib] "); + (target->GetType() == cmStateEnums::EXECUTABLE ? "[exe] " + : "[lib] "); this->AppendTarget(xml, targetName, make, makeArgs, subdir, prefix); std::string fastTarget = targetName; fastTarget += "/fast"; @@ -963,19 +937,19 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const virtDir += prefix; virtDir += targetName; std::string buildArgs = "-C \""; - buildArgs += (*it)->GetBinaryDirectory(); + buildArgs += lgen->GetBinaryDirectory(); buildArgs += "\" "; buildArgs += makeArgs; this->AppendTarget(xml, "Build", make, buildArgs, virtDir, "", targetName.c_str()); std::string cleanArgs = "-E chdir \""; - cleanArgs += (*it)->GetCurrentBinaryDirectory(); + cleanArgs += lgen->GetCurrentBinaryDirectory(); cleanArgs += "\" \""; cleanArgs += cmSystemTools::GetCMakeCommand(); cleanArgs += "\" -P \""; - cmGeneratorTarget* gt = *ti; - cleanArgs += (*it)->GetTargetDirectory(gt); + cmGeneratorTarget* gt = target; + cleanArgs += lgen->GetTargetDirectory(gt); cleanArgs += "/cmake_clean.cmake\""; this->AppendTarget(xml, "Clean", cmSystemTools::GetCMakeCommand(), cleanArgs, virtDir, "", ""); @@ -997,17 +971,15 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const // insert rules for compiling, preprocessing and assembling individual // files std::vector<std::string> objectFileTargets; - (*it)->GetIndividualFileTargets(objectFileTargets); - for (std::vector<std::string>::const_iterator fit = - objectFileTargets.begin(); - fit != objectFileTargets.end(); ++fit) { + lg->GetIndividualFileTargets(objectFileTargets); + for (std::string const& f : objectFileTargets) { const char* prefix = "[obj] "; - if ((*fit)[fit->length() - 1] == 's') { + if (f[f.length() - 1] == 's') { prefix = "[to asm] "; - } else if ((*fit)[fit->length() - 1] == 'i') { + } else if (f[f.length() - 1] == 'i') { prefix = "[pre] "; } - this->AppendTarget(xml, *fit, make, makeArgs, subdir, prefix); + this->AppendTarget(xml, f, make, makeArgs, subdir, prefix); } } diff --git a/Source/cmExtraEclipseCDT4Generator.h b/Source/cmExtraEclipseCDT4Generator.h index 5d2ca10..5136660 100644 --- a/Source/cmExtraEclipseCDT4Generator.h +++ b/Source/cmExtraEclipseCDT4Generator.h @@ -35,9 +35,9 @@ public: static cmExternalMakefileProjectGeneratorFactory* GetFactory(); void EnableLanguage(std::vector<std::string> const& languages, cmMakefile*, - bool optional) CM_OVERRIDE; + bool optional) override; - void Generate() CM_OVERRIDE; + void Generate() override; private: // create .project file in the source tree diff --git a/Source/cmExtraKateGenerator.cxx b/Source/cmExtraKateGenerator.cxx index a75a400..79cc6ef 100644 --- a/Source/cmExtraKateGenerator.cxx +++ b/Source/cmExtraKateGenerator.cxx @@ -112,18 +112,16 @@ void cmExtraKateGenerator::WriteTargets(const cmLocalGenerator* lg, // add all executable and library targets and some of the GLOBAL // and UTILITY targets - for (std::vector<cmLocalGenerator*>::const_iterator it = - this->GlobalGenerator->GetLocalGenerators().begin(); - it != this->GlobalGenerator->GetLocalGenerators().end(); ++it) { + for (cmLocalGenerator* localGen : + this->GlobalGenerator->GetLocalGenerators()) { const std::vector<cmGeneratorTarget*>& targets = - (*it)->GetGeneratorTargets(); - std::string currentDir = (*it)->GetCurrentBinaryDirectory(); - bool topLevel = (currentDir == (*it)->GetBinaryDirectory()); - - for (std::vector<cmGeneratorTarget*>::const_iterator ti = targets.begin(); - ti != targets.end(); ++ti) { - std::string targetName = (*ti)->GetName(); - switch ((*ti)->GetType()) { + localGen->GetGeneratorTargets(); + std::string currentDir = localGen->GetCurrentBinaryDirectory(); + bool topLevel = (currentDir == localGen->GetBinaryDirectory()); + + for (cmGeneratorTarget* target : targets) { + std::string const& targetName = target->GetName(); + switch (target->GetType()) { case cmStateEnums::GLOBAL_TARGET: { bool insertTarget = false; // Only add the global targets from CMAKE_BINARY_DIR, @@ -134,7 +132,7 @@ void cmExtraKateGenerator::WriteTargets(const cmLocalGenerator* lg, // this will not work within the IDE if (targetName == "edit_cache") { const char* editCommand = - (*it)->GetMakefile()->GetDefinition("CMAKE_EDIT_COMMAND"); + localGen->GetMakefile()->GetDefinition("CMAKE_EDIT_COMMAND"); if (editCommand == nullptr) { insertTarget = false; } else if (strstr(editCommand, "ccmake") != nullptr) { @@ -183,12 +181,9 @@ void cmExtraKateGenerator::WriteTargets(const cmLocalGenerator* lg, // insert rules for compiling, preprocessing and assembling individual // files std::vector<std::string> objectFileTargets; - (*it)->GetIndividualFileTargets(objectFileTargets); - for (std::vector<std::string>::const_iterator fit = - objectFileTargets.begin(); - fit != objectFileTargets.end(); ++fit) { - this->AppendTarget(fout, *fit, make, makeArgs, currentDir, - homeOutputDir); + localGen->GetIndividualFileTargets(objectFileTargets); + for (std::string const& f : objectFileTargets) { + this->AppendTarget(fout, f, make, makeArgs, currentDir, homeOutputDir); } } @@ -251,22 +246,18 @@ std::string cmExtraKateGenerator::GenerateFilesString( const std::vector<cmLocalGenerator*>& lgs = this->GlobalGenerator->GetLocalGenerators(); - for (std::vector<cmLocalGenerator*>::const_iterator it = lgs.begin(); - it != lgs.end(); it++) { - cmMakefile* makefile = (*it)->GetMakefile(); + for (cmLocalGenerator* lgen : lgs) { + cmMakefile* makefile = lgen->GetMakefile(); const std::vector<std::string>& listFiles = makefile->GetListFiles(); - for (std::vector<std::string>::const_iterator lt = listFiles.begin(); - lt != listFiles.end(); lt++) { - tmp = *lt; + for (std::string const& listFile : listFiles) { + tmp = listFile; { files.insert(tmp); } } const std::vector<cmSourceFile*>& sources = makefile->GetSourceFiles(); - for (std::vector<cmSourceFile*>::const_iterator sfIt = sources.begin(); - sfIt != sources.end(); sfIt++) { - cmSourceFile* sf = *sfIt; + for (cmSourceFile* sf : sources) { if (sf->GetPropertyAsBool("GENERATED")) { continue; } @@ -278,11 +269,10 @@ std::string cmExtraKateGenerator::GenerateFilesString( const char* sep = ""; tmp = "\"list\": ["; - for (std::set<std::string>::const_iterator it = files.begin(); - it != files.end(); ++it) { + for (std::string const& f : files) { tmp += sep; tmp += " \""; - tmp += *it; + tmp += f; tmp += "\""; sep = ","; } diff --git a/Source/cmExtraKateGenerator.h b/Source/cmExtraKateGenerator.h index 7e80314..9716fe7 100644 --- a/Source/cmExtraKateGenerator.h +++ b/Source/cmExtraKateGenerator.h @@ -22,7 +22,7 @@ public: static cmExternalMakefileProjectGeneratorFactory* GetFactory(); - void Generate() CM_OVERRIDE; + void Generate() override; private: void CreateKateProjectFile(const cmLocalGenerator* lg) const; diff --git a/Source/cmExtraSublimeTextGenerator.cxx b/Source/cmExtraSublimeTextGenerator.cxx index 5bb424b..73a9c85 100644 --- a/Source/cmExtraSublimeTextGenerator.cxx +++ b/Source/cmExtraSublimeTextGenerator.cxx @@ -68,11 +68,9 @@ void cmExtraSublimeTextGenerator::Generate() "CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS"); // for each sub project in the project create a sublime text 2 project - for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator - it = this->GlobalGenerator->GetProjectMap().begin(); - it != this->GlobalGenerator->GetProjectMap().end(); ++it) { + for (auto const& it : this->GlobalGenerator->GetProjectMap()) { // create a project file - this->CreateProjectFile(it->second); + this->CreateProjectFile(it.second); } } @@ -144,20 +142,19 @@ void cmExtraSublimeTextGenerator::CreateNewProjectFile( fout << "\n\t{"; fout << "\n\t\t" << systemName << ":"; fout << "\n\t\t{"; - for (std::vector<std::string>::iterator i = tokens.begin(); - i != tokens.end(); ++i) { - size_t const pos = i->find_first_of('='); + for (std::string const& t : tokens) { + size_t const pos = t.find_first_of('='); if (pos != std::string::npos) { - std::string varName = i->substr(0, pos); - std::string varValue = i->substr(pos + 1); + std::string varName = t.substr(0, pos); + std::string varValue = t.substr(pos + 1); fout << "\n\t\t\t\"" << varName << "\":\"" << varValue << "\""; } else { std::ostringstream e; e << "Could not parse Env Vars specified in " "\"CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS\"" - << ", corrupted string " << *i; + << ", corrupted string " << t; mf->IssueMessage(cmake::FATAL_ERROR, e.str()); } } @@ -182,21 +179,18 @@ void cmExtraSublimeTextGenerator::AppendAllTargets( // add all executable and library targets and some of the GLOBAL // and UTILITY targets - for (std::vector<cmLocalGenerator*>::const_iterator lg = lgs.begin(); - lg != lgs.end(); lg++) { - cmMakefile* makefile = (*lg)->GetMakefile(); - const std::vector<cmGeneratorTarget*>& targets = - (*lg)->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator ti = targets.begin(); - ti != targets.end(); ti++) { - std::string targetName = (*ti)->GetName(); - switch ((*ti)->GetType()) { + for (cmLocalGenerator* lg : lgs) { + cmMakefile* makefile = lg->GetMakefile(); + const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets(); + for (cmGeneratorTarget* target : targets) { + std::string targetName = target->GetName(); + switch (target->GetType()) { case cmStateEnums::GLOBAL_TARGET: { // Only add the global targets from CMAKE_BINARY_DIR, // not from the subdirs - if (strcmp((*lg)->GetCurrentBinaryDirectory(), - (*lg)->GetBinaryDirectory()) == 0) { - this->AppendTarget(fout, targetName, *lg, nullptr, make.c_str(), + if (strcmp(lg->GetCurrentBinaryDirectory(), + lg->GetBinaryDirectory()) == 0) { + this->AppendTarget(fout, targetName, lg, nullptr, make.c_str(), makefile, compiler.c_str(), sourceFileFlags, false); } @@ -213,7 +207,7 @@ void cmExtraSublimeTextGenerator::AppendAllTargets( break; } - this->AppendTarget(fout, targetName, *lg, nullptr, make.c_str(), + this->AppendTarget(fout, targetName, lg, nullptr, make.c_str(), makefile, compiler.c_str(), sourceFileFlags, false); break; @@ -222,12 +216,12 @@ void cmExtraSublimeTextGenerator::AppendAllTargets( case cmStateEnums::SHARED_LIBRARY: case cmStateEnums::MODULE_LIBRARY: case cmStateEnums::OBJECT_LIBRARY: { - this->AppendTarget(fout, targetName, *lg, *ti, make.c_str(), + this->AppendTarget(fout, targetName, lg, target, make.c_str(), makefile, compiler.c_str(), sourceFileFlags, false); std::string fastTarget = targetName; fastTarget += "/fast"; - this->AppendTarget(fout, fastTarget, *lg, *ti, make.c_str(), + this->AppendTarget(fout, fastTarget, lg, target, make.c_str(), makefile, compiler.c_str(), sourceFileFlags, false); } break; @@ -249,11 +243,7 @@ void cmExtraSublimeTextGenerator::AppendTarget( std::vector<cmSourceFile*> sourceFiles; target->GetSourceFiles(sourceFiles, makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")); - std::vector<cmSourceFile*>::const_iterator sourceFilesEnd = - sourceFiles.end(); - for (std::vector<cmSourceFile*>::const_iterator iter = sourceFiles.begin(); - iter != sourceFilesEnd; ++iter) { - cmSourceFile* sourceFile = *iter; + for (cmSourceFile* sourceFile : sourceFiles) { MapSourceFileFlags::iterator sourceFileFlagsIter = sourceFileFlags.find(sourceFile->GetFullPath()); if (sourceFileFlagsIter == sourceFileFlags.end()) { @@ -264,8 +254,9 @@ void cmExtraSublimeTextGenerator::AppendTarget( .first; } std::vector<std::string>& flags = sourceFileFlagsIter->second; - std::string flagsString = this->ComputeFlagsForObject(*iter, lg, target); - std::string definesString = this->ComputeDefines(*iter, lg, target); + std::string flagsString = + this->ComputeFlagsForObject(sourceFile, lg, target); + std::string definesString = this->ComputeDefines(sourceFile, lg, target); flags.clear(); cmsys::RegularExpression flagRegex; // Regular expression to extract compiler flags from a string @@ -283,7 +274,7 @@ void cmExtraSublimeTextGenerator::AppendTarget( if (flagRegex.end() < workString.size()) { workString = workString.substr(flagRegex.end()); } else { - workString = ""; + workString.clear(); } } } diff --git a/Source/cmExtraSublimeTextGenerator.h b/Source/cmExtraSublimeTextGenerator.h index bf6d23f..7fb304e 100644 --- a/Source/cmExtraSublimeTextGenerator.h +++ b/Source/cmExtraSublimeTextGenerator.h @@ -24,10 +24,10 @@ class cmExtraSublimeTextGenerator : public cmExternalMakefileProjectGenerator { public: static cmExternalMakefileProjectGeneratorFactory* GetFactory(); - typedef std::map<std::string, std::vector<std::string> > MapSourceFileFlags; + typedef std::map<std::string, std::vector<std::string>> MapSourceFileFlags; cmExtraSublimeTextGenerator(); - void Generate() CM_OVERRIDE; + void Generate() override; private: void CreateProjectFile(const std::vector<cmLocalGenerator*>& lgs); diff --git a/Source/cmFLTKWrapUICommand.h b/Source/cmFLTKWrapUICommand.h index 64c29f8..044755e 100644 --- a/Source/cmFLTKWrapUICommand.h +++ b/Source/cmFLTKWrapUICommand.h @@ -25,14 +25,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmFLTKWrapUICommand; } + cmCommand* Clone() override { return new cmFLTKWrapUICommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; /** * This is called at the end after all the information @@ -40,8 +40,8 @@ public: * not implement this method. At this point, reading and * writing to the cache can be done. */ - void FinalPass() CM_OVERRIDE; - bool HasFinalPass() const CM_OVERRIDE { return true; } + void FinalPass() override; + bool HasFinalPass() const override { return true; } private: /** diff --git a/Source/cmFileCommand.cxx b/Source/cmFileCommand.cxx index 3af7484..f06ef43 100644 --- a/Source/cmFileCommand.cxx +++ b/Source/cmFileCommand.cxx @@ -10,6 +10,7 @@ #include "cmsys/String.hxx" #include <algorithm> #include <assert.h> +#include <memory> // IWYU pragma: keep #include <sstream> #include <stdio.h> #include <stdlib.h> @@ -30,7 +31,6 @@ #include "cmPolicies.h" #include "cmSystemTools.h" #include "cmTimestamp.h" -#include "cm_auto_ptr.hxx" #include "cm_sys_stat.h" #include "cmake.h" @@ -368,8 +368,8 @@ bool cmFileCommand::HandleHashCommand(std::vector<std::string> const& args) return false; } - CM_AUTO_PTR<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str())); - if (hash.get()) { + std::unique_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str())); + if (hash) { std::string out = hash->HashFile(args[1]); if (!out.empty()) { this->Makefile->AddDefinition(args[2], out.c_str()); @@ -656,7 +656,7 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) c = current_str[current_str.size() - 1 - j]; fin.putback(static_cast<char>(c)); } - current_str = ""; + current_str.clear(); } } @@ -667,14 +667,14 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) if (s.length() >= minlen && (!have_regex || regex.find(s.c_str()))) { output_size += static_cast<int>(s.size()) + 1; if (limit_output >= 0 && output_size >= limit_output) { - s = ""; + s.clear(); break; } strings.push_back(s); } // Reset the string to empty. - s = ""; + s.clear(); } else if (current_str.empty()) { // A non-string character has been found. Check if the current // string matches the requirements. We require that the length @@ -683,14 +683,14 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) (!have_regex || regex.find(s.c_str()))) { output_size += static_cast<int>(s.size()) + 1; if (limit_output >= 0 && output_size >= limit_output) { - s = ""; + s.clear(); break; } strings.push_back(s); } // Reset the string to empty. - s = ""; + s.clear(); } else { s += current_str; } @@ -700,12 +700,12 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) if (s.length() >= minlen && (!have_regex || regex.find(s.c_str()))) { output_size += static_cast<int>(s.size()) + 1; if (limit_output >= 0 && output_size >= limit_output) { - s = ""; + s.clear(); break; } strings.push_back(s); } - s = ""; + s.clear(); } } @@ -723,20 +723,18 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) // Encode the result in a CMake list. const char* sep = ""; std::string output; - for (std::vector<std::string>::const_iterator si = strings.begin(); - si != strings.end(); ++si) { + for (std::string const& sr : strings) { // Separate the strings in the output to make it a list. output += sep; sep = ";"; // Store the string in the output, but escape semicolons to // make sure it is a list. - std::string const& sr = *si; - for (unsigned int i = 0; i < sr.size(); ++i) { - if (sr[i] == ';') { + for (char i : sr) { + if (i == ';') { output += '\\'; } - output += sr[i]; + output += i; } } @@ -841,17 +839,16 @@ bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args, if (!globMessages.empty()) { bool shouldExit = false; - for (cmsys::Glob::GlobMessagesIterator it = globMessages.begin(); - it != globMessages.end(); ++it) { - if (it->type == cmsys::Glob::cyclicRecursion) { + for (cmsys::Glob::Message const& globMessage : globMessages) { + if (globMessage.type == cmsys::Glob::cyclicRecursion) { this->Makefile->IssueMessage( cmake::AUTHOR_WARNING, "Cyclic recursion detected while globbing for '" + *i + "':\n" + - it->content); + globMessage.content); } else { this->Makefile->IssueMessage( cmake::FATAL_ERROR, "Error has occurred while globbing for '" + - *i + "' - " + it->content); + *i + "' - " + globMessage.content); shouldExit = true; } } @@ -1060,12 +1057,11 @@ protected: // Collect properties from all matching rules. bool matched = false; MatchProperties result; - for (std::vector<MatchRule>::iterator mr = this->MatchRules.begin(); - mr != this->MatchRules.end(); ++mr) { - if (mr->Regex.find(file_to_match)) { + for (MatchRule& mr : this->MatchRules) { + if (mr.Regex.find(file_to_match)) { matched = true; - result.Exclude |= mr->Properties.Exclude; - result.Permissions |= mr->Properties.Permissions; + result.Exclude |= mr.Properties.Exclude; + result.Permissions |= mr.Properties.Permissions; } } if (!matched && !this->MatchlessFiles) { @@ -1421,23 +1417,22 @@ bool cmFileCopier::Run(std::vector<std::string> const& args) return false; } - for (std::vector<std::string>::const_iterator i = this->Files.begin(); - i != this->Files.end(); ++i) { + for (std::string const& f : this->Files) { std::string file; - if (!i->empty() && !cmSystemTools::FileIsFullPath(*i)) { + if (!f.empty() && !cmSystemTools::FileIsFullPath(f)) { if (!this->FilesFromDir.empty()) { file = this->FilesFromDir; } else { file = this->Makefile->GetCurrentSourceDirectory(); } file += "/"; - file += *i; + file += f; } else if (!this->FilesFromDir.empty()) { this->FileCommand->SetError("option FILES_FROM_DIR requires all files " "to be specified as relative paths."); return false; } else { - file = *i; + file = f; } // Split the input file into its directory and name components. @@ -1450,7 +1445,7 @@ bool cmFileCopier::Run(std::vector<std::string> const& args) // Compute the full path to the destination file. std::string toFile = this->Destination; if (!this->FilesFromDir.empty()) { - std::string dir = cmSystemTools::GetFilenamePath(*i); + std::string dir = cmSystemTools::GetFilenamePath(f); if (!dir.empty()) { toFile += "/"; toFile += dir; @@ -1711,7 +1706,7 @@ struct cmFileInstaller : public cmFileCopier this->Manifest = this->Makefile->GetSafeDefinition("CMAKE_INSTALL_MANIFEST_FILES"); } - ~cmFileInstaller() CM_OVERRIDE + ~cmFileInstaller() override { // Save the updated install manifest. this->Makefile->AddDefinition("CMAKE_INSTALL_MANIFEST_FILES", @@ -1736,12 +1731,12 @@ protected: this->Manifest += file.substr(this->DestDirLength); } - std::string const& ToName(std::string const& fromName) CM_OVERRIDE + std::string const& ToName(std::string const& fromName) override { return this->Rename.empty() ? fromName : this->Rename; } - void ReportCopy(const char* toFile, Type type, bool copy) CM_OVERRIDE + void ReportCopy(const char* toFile, Type type, bool copy) override { if (!this->MessageNever && (copy || !this->MessageLazy)) { std::string message = (copy ? "Installing: " : "Up-to-date: "); @@ -1753,11 +1748,11 @@ protected: this->ManifestAppend(toFile); } } - bool ReportMissing(const char* fromFile) CM_OVERRIDE + bool ReportMissing(const char* fromFile) override { return (this->Optional || this->cmFileCopier::ReportMissing(fromFile)); } - bool Install(const char* fromFile, const char* toFile) CM_OVERRIDE + bool Install(const char* fromFile, const char* toFile) override { // Support installing from empty source to make a directory. if (this->InstallType == cmInstallType_DIRECTORY && !*fromFile) { @@ -1766,16 +1761,16 @@ protected: return this->cmFileCopier::Install(fromFile, toFile); } - bool Parse(std::vector<std::string> const& args) CM_OVERRIDE; + bool Parse(std::vector<std::string> const& args) override; enum { DoingType = DoingLast1, DoingRename, DoingLast2 }; - bool CheckKeyword(std::string const& arg) CM_OVERRIDE; - bool CheckValue(std::string const& arg) CM_OVERRIDE; - void DefaultFilePermissions() CM_OVERRIDE + bool CheckKeyword(std::string const& arg) override; + bool CheckValue(std::string const& arg) override; + void DefaultFilePermissions() override { this->cmFileCopier::DefaultFilePermissions(); // Add execute permissions based on the target type. @@ -2634,7 +2629,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) const char* cainfo = this->Makefile->GetDefinition("CMAKE_TLS_CAINFO"); std::string expectedHash; std::string hashMatchMSG; - CM_AUTO_PTR<cmCryptoHash> hash; + std::unique_ptr<cmCryptoHash> hash; bool showProgress = false; std::string userpwd; @@ -2693,8 +2688,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) this->SetError("DOWNLOAD missing sum value for EXPECTED_MD5."); return false; } - hash = - CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(cmCryptoHash::AlgoMD5)); + hash = cm::make_unique<cmCryptoHash>(cmCryptoHash::AlgoMD5); hashMatchMSG = "MD5 sum"; expectedHash = cmSystemTools::LowerCase(*i); } else if (*i == "SHOW_PROGRESS") { @@ -2715,7 +2709,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) } std::string algo = i->substr(0, pos); expectedHash = cmSystemTools::LowerCase(i->substr(pos + 1)); - hash = CM_AUTO_PTR<cmCryptoHash>(cmCryptoHash::New(algo.c_str())); + hash = std::unique_ptr<cmCryptoHash>(cmCryptoHash::New(algo.c_str())); if (!hash.get()) { std::string err = "DOWNLOAD EXPECTED_HASH given unknown ALGO: "; err += algo; @@ -2882,9 +2876,8 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) } struct curl_slist* headers = nullptr; - for (std::vector<std::string>::const_iterator h = curl_headers.begin(); - h != curl_headers.end(); ++h) { - headers = ::curl_slist_append(headers, h->c_str()); + for (std::string const& h : curl_headers) { + headers = ::curl_slist_append(headers, h.c_str()); } ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); @@ -2912,7 +2905,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) // Verify MD5 sum if requested: // - if (hash.get()) { + if (hash) { std::string actualHash = hash->HashFile(file); if (actualHash.empty()) { this->SetError("DOWNLOAD cannot compute hash on downloaded file"); @@ -3141,9 +3134,8 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args) } struct curl_slist* headers = nullptr; - for (std::vector<std::string>::const_iterator h = curl_headers.begin(); - h != curl_headers.end(); ++h) { - headers = ::curl_slist_append(headers, h->c_str()); + for (std::string const& h : curl_headers) { + headers = ::curl_slist_append(headers, h.c_str()); } ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); @@ -3202,15 +3194,15 @@ void cmFileCommand::AddEvaluationFile(const std::string& inputName, cmListFileBacktrace lfbt = this->Makefile->GetBacktrace(); cmGeneratorExpression outputGe(lfbt); - CM_AUTO_PTR<cmCompiledGeneratorExpression> outputCge = + std::unique_ptr<cmCompiledGeneratorExpression> outputCge = outputGe.Parse(outputExpr); cmGeneratorExpression conditionGe(lfbt); - CM_AUTO_PTR<cmCompiledGeneratorExpression> conditionCge = + std::unique_ptr<cmCompiledGeneratorExpression> conditionCge = conditionGe.Parse(condition); - this->Makefile->AddEvaluationFile(inputName, outputCge, conditionCge, - inputIsContent); + this->Makefile->AddEvaluationFile(inputName, std::move(outputCge), + std::move(conditionCge), inputIsContent); } bool cmFileCommand::HandleGenerateCommand(std::vector<std::string> const& args) diff --git a/Source/cmFileCommand.h b/Source/cmFileCommand.h index 1de8b59..17269f3 100644 --- a/Source/cmFileCommand.h +++ b/Source/cmFileCommand.h @@ -22,14 +22,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmFileCommand; } + cmCommand* Clone() override { return new cmFileCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; protected: bool HandleRename(std::vector<std::string> const& args); diff --git a/Source/cmFileLock.cxx b/Source/cmFileLock.cxx index 786d6c6..f309241 100644 --- a/Source/cmFileLock.cxx +++ b/Source/cmFileLock.cxx @@ -42,7 +42,7 @@ cmFileLockResult cmFileLock::Lock(const std::string& filename, } if (!result.IsOk()) { - this->Filename = ""; + this->Filename.clear(); } return result; diff --git a/Source/cmFileLockPool.cxx b/Source/cmFileLockPool.cxx index 7b1564c..5dc9243 100644 --- a/Source/cmFileLockPool.cxx +++ b/Source/cmFileLockPool.cxx @@ -75,16 +75,15 @@ cmFileLockResult cmFileLockPool::LockProcessScope(const std::string& filename, cmFileLockResult cmFileLockPool::Release(const std::string& filename) { - for (It i = this->FunctionScopes.begin(); i != this->FunctionScopes.end(); - ++i) { - const cmFileLockResult result = (*i)->Release(filename); + for (auto& funcScope : this->FunctionScopes) { + const cmFileLockResult result = funcScope->Release(filename); if (!result.IsOk()) { return result; } } - for (It i = this->FileScopes.begin(); i != this->FileScopes.end(); ++i) { - const cmFileLockResult result = (*i)->Release(filename); + for (auto& fileScope : this->FileScopes) { + const cmFileLockResult result = fileScope->Release(filename); if (!result.IsOk()) { return result; } @@ -95,16 +94,15 @@ cmFileLockResult cmFileLockPool::Release(const std::string& filename) bool cmFileLockPool::IsAlreadyLocked(const std::string& filename) const { - for (CIt i = this->FunctionScopes.begin(); i != this->FunctionScopes.end(); - ++i) { - const bool result = (*i)->IsAlreadyLocked(filename); + for (auto const& funcScope : this->FunctionScopes) { + const bool result = funcScope->IsAlreadyLocked(filename); if (result) { return true; } } - for (CIt i = this->FileScopes.begin(); i != this->FileScopes.end(); ++i) { - const bool result = (*i)->IsAlreadyLocked(filename); + for (auto const& fileScope : this->FileScopes) { + const bool result = fileScope->IsAlreadyLocked(filename); if (result) { return true; } @@ -138,9 +136,9 @@ cmFileLockResult cmFileLockPool::ScopePool::Lock(const std::string& filename, cmFileLockResult cmFileLockPool::ScopePool::Release( const std::string& filename) { - for (It i = this->Locks.begin(); i != this->Locks.end(); ++i) { - if ((*i)->IsLocked(filename)) { - return (*i)->Release(); + for (auto& lock : this->Locks) { + if (lock->IsLocked(filename)) { + return lock->Release(); } } return cmFileLockResult::MakeOk(); @@ -149,8 +147,8 @@ cmFileLockResult cmFileLockPool::ScopePool::Release( bool cmFileLockPool::ScopePool::IsAlreadyLocked( const std::string& filename) const { - for (CIt i = this->Locks.begin(); i != this->Locks.end(); ++i) { - if ((*i)->IsLocked(filename)) { + for (auto const& lock : this->Locks) { + if (lock->IsLocked(filename)) { return true; } } diff --git a/Source/cmFileMonitor.cxx b/Source/cmFileMonitor.cxx index c0401d7..04a3c0e 100644 --- a/Source/cmFileMonitor.cxx +++ b/Source/cmFileMonitor.cxx @@ -49,8 +49,8 @@ public: int status) const final { if (pathSegment.empty()) { - for (const auto& i : this->Children) { - i.second->Trigger(std::string(), events, status); + for (auto const& child : this->Children) { + child.second->Trigger(std::string(), events, status); } } else { const auto i = this->Children.find(pathSegment); @@ -62,24 +62,24 @@ public: void StartWatching() override { - for (const auto& i : this->Children) { - i.second->StartWatching(); + for (auto const& child : this->Children) { + child.second->StartWatching(); } } void StopWatching() override { - for (const auto& i : this->Children) { - i.second->StopWatching(); + for (auto const& child : this->Children) { + child.second->StopWatching(); } } std::vector<std::string> WatchedFiles() const final { std::vector<std::string> result; - for (const auto& i : this->Children) { - for (const auto& j : i.second->WatchedFiles()) { - result.push_back(j); + for (auto const& child : this->Children) { + for (std::string const& f : child.second->WatchedFiles()) { + result.push_back(f); } } return result; @@ -88,9 +88,9 @@ public: std::vector<std::string> WatchedDirectories() const override { std::vector<std::string> result; - for (const auto& i : this->Children) { - for (const auto& j : i.second->WatchedDirectories()) { - result.push_back(j); + for (auto const& child : this->Children) { + for (std::string const& dir : child.second->WatchedDirectories()) { + result.push_back(dir); } } return result; @@ -184,8 +184,9 @@ public: std::vector<std::string> WatchedDirectories() const override { std::vector<std::string> result = { Path() }; - for (const auto& j : cmVirtualDirectoryWatcher::WatchedDirectories()) { - result.push_back(j); + for (std::string const& dir : + cmVirtualDirectoryWatcher::WatchedDirectories()) { + result.push_back(dir); } return result; } @@ -267,7 +268,7 @@ public: static_cast<void>(ps); const std::string path = this->Path(); - for (const auto& cb : this->CbList) { + for (cmFileMonitor::Callback const& cb : this->CbList) { cb(path, events, status); } } @@ -311,7 +312,7 @@ cmFileMonitor::~cmFileMonitor() void cmFileMonitor::MonitorPaths(const std::vector<std::string>& paths, Callback const& cb) { - for (const auto& p : paths) { + for (std::string const& p : paths) { std::vector<std::string> pathSegments; cmsys::SystemTools::SplitPath(p, pathSegments, true); diff --git a/Source/cmFindBase.cxx b/Source/cmFindBase.cxx index b195d27..417cdd2 100644 --- a/Source/cmFindBase.cxx +++ b/Source/cmFindBase.cxx @@ -280,10 +280,8 @@ void cmFindBase::FillUserHintsPath() { cmSearchPath& paths = this->LabeledPaths[PathLabel::Hints]; - for (std::vector<std::string>::const_iterator p = - this->UserHintsArgs.begin(); - p != this->UserHintsArgs.end(); ++p) { - paths.AddUserPath(*p); + for (std::string const& p : this->UserHintsArgs) { + paths.AddUserPath(p); } paths.AddSuffixes(this->SearchPathSuffixes); } @@ -292,10 +290,8 @@ void cmFindBase::FillUserGuessPath() { cmSearchPath& paths = this->LabeledPaths[PathLabel::Guess]; - for (std::vector<std::string>::const_iterator p = - this->UserGuessArgs.begin(); - p != this->UserGuessArgs.end(); ++p) { - paths.AddUserPath(*p); + for (std::string const& p : this->UserGuessArgs) { + paths.AddUserPath(p); } paths.AddSuffixes(this->SearchPathSuffixes); } diff --git a/Source/cmFindCommon.cxx b/Source/cmFindCommon.cxx index 9ebe824..8142962 100644 --- a/Source/cmFindCommon.cxx +++ b/Source/cmFindCommon.cxx @@ -155,10 +155,9 @@ void cmFindCommon::SelectDefaultMacMode() void cmFindCommon::RerootPaths(std::vector<std::string>& paths) { #if 0 - for(std::vector<std::string>::const_iterator i = paths.begin(); - i != paths.end(); ++i) + for(std::string const& p : paths) { - fprintf(stderr, "[%s]\n", i->c_str()); + fprintf(stderr, "[%s]\n", p.c_str()); } #endif // Short-circuit if there is nothing to do. @@ -194,9 +193,8 @@ void cmFindCommon::RerootPaths(std::vector<std::string>& paths) if (sysroot) { roots.push_back(sysroot); } - for (std::vector<std::string>::iterator ri = roots.begin(); - ri != roots.end(); ++ri) { - cmSystemTools::ConvertToUnixSlashes(*ri); + for (std::string& r : roots) { + cmSystemTools::ConvertToUnixSlashes(r); } const char* stagePrefix = @@ -206,24 +204,22 @@ void cmFindCommon::RerootPaths(std::vector<std::string>& paths) std::vector<std::string> unrootedPaths = paths; paths.clear(); - for (std::vector<std::string>::const_iterator ri = roots.begin(); - ri != roots.end(); ++ri) { - for (std::vector<std::string>::const_iterator ui = unrootedPaths.begin(); - ui != unrootedPaths.end(); ++ui) { + for (std::string const& r : roots) { + for (std::string const& up : unrootedPaths) { // Place the unrooted path under the current root if it is not // already inside. Skip the unrooted path if it is relative to // a user home directory or is empty. std::string rootedDir; - if (cmSystemTools::IsSubDirectory(*ui, *ri) || - (stagePrefix && cmSystemTools::IsSubDirectory(*ui, stagePrefix))) { - rootedDir = *ui; - } else if (!ui->empty() && (*ui)[0] != '~') { + if (cmSystemTools::IsSubDirectory(up, r) || + (stagePrefix && cmSystemTools::IsSubDirectory(up, stagePrefix))) { + rootedDir = up; + } else if (!up.empty() && up[0] != '~') { // Start with the new root. - rootedDir = *ri; + rootedDir = r; rootedDir += "/"; // Append the original path with its old root removed. - rootedDir += cmSystemTools::SplitPathRootComponent(*ui); + rootedDir += cmSystemTools::SplitPathRootComponent(up); } // Store the new path. @@ -255,9 +251,8 @@ void cmFindCommon::GetIgnoredPaths(std::vector<std::string>& ignore) cmSystemTools::ExpandListArgument(ignorePath, ignore); } - for (std::vector<std::string>::iterator i = ignore.begin(); - i != ignore.end(); ++i) { - cmSystemTools::ConvertToUnixSlashes(*i); + for (std::string& i : ignore) { + cmSystemTools::ConvertToUnixSlashes(i); } } @@ -337,9 +332,8 @@ void cmFindCommon::ComputeFinalPaths() // Combine the seperate path types, filtering out ignores this->SearchPaths.clear(); std::vector<PathLabel>& allLabels = this->PathGroupLabelMap[PathGroup::All]; - for (std::vector<PathLabel>::const_iterator l = allLabels.begin(); - l != allLabels.end(); ++l) { - this->LabeledPaths[*l].ExtractWithout(ignored, this->SearchPaths); + for (PathLabel const& l : allLabels) { + this->LabeledPaths[l].ExtractWithout(ignored, this->SearchPaths); } // Expand list of paths inside all search roots. diff --git a/Source/cmFindCommon.h b/Source/cmFindCommon.h index 939a5bc..b237f1b 100644 --- a/Source/cmFindCommon.h +++ b/Source/cmFindCommon.h @@ -25,7 +25,7 @@ class cmFindCommon : public cmCommand { public: cmFindCommon(); - ~cmFindCommon() CM_OVERRIDE; + ~cmFindCommon() override; protected: friend class cmSearchPath; @@ -112,7 +112,7 @@ protected: std::vector<std::string> SearchPathSuffixes; - std::map<PathGroup, std::vector<PathLabel> > PathGroupLabelMap; + std::map<PathGroup, std::vector<PathLabel>> PathGroupLabelMap; std::vector<PathGroup> PathGroupOrder; std::map<std::string, PathLabel> PathLabelStringMap; std::map<PathLabel, cmSearchPath> LabeledPaths; diff --git a/Source/cmFindFileCommand.h b/Source/cmFindFileCommand.h index 88c2372..4309449 100644 --- a/Source/cmFindFileCommand.h +++ b/Source/cmFindFileCommand.h @@ -24,7 +24,7 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmFindFileCommand; } + cmCommand* Clone() override { return new cmFindFileCommand; } }; #endif diff --git a/Source/cmFindLibraryCommand.cxx b/Source/cmFindLibraryCommand.cxx index a6b1a21..b8b51ba 100644 --- a/Source/cmFindLibraryCommand.cxx +++ b/Source/cmFindLibraryCommand.cxx @@ -68,8 +68,8 @@ bool cmFindLibraryCommand::InitialPass(std::vector<std::string> const& argsIn, this->AddArchitecturePaths("x32"); } - std::string library = this->FindLibrary(); - if (library != "") { + std::string const library = this->FindLibrary(); + if (!library.empty()) { // Save the value in the cache this->Makefile->AddCacheDefinition(this->VariableName, library.c_str(), this->VariableDocumentation.c_str(), @@ -87,9 +87,8 @@ void cmFindLibraryCommand::AddArchitecturePaths(const char* suffix) { std::vector<std::string> original; original.swap(this->SearchPaths); - for (std::vector<std::string>::const_iterator i = original.begin(); - i != original.end(); ++i) { - this->AddArchitecturePath(*i, 0, suffix); + for (std::string const& o : original) { + this->AddArchitecturePath(o, 0, suffix); } } @@ -254,8 +253,7 @@ cmFindLibraryHelper::cmFindLibraryHelper(cmMakefile* mf) void cmFindLibraryHelper::RegexFromLiteral(std::string& out, std::string const& in) { - for (std::string::const_iterator ci = in.begin(); ci != in.end(); ++ci) { - char ch = *ci; + for (char ch : in) { if (ch == '[' || ch == ']' || ch == '(' || ch == ')' || ch == '\\' || ch == '.' || ch == '*' || ch == '+' || ch == '?' || ch == '-' || ch == '^' || ch == '$') { @@ -276,23 +274,20 @@ void cmFindLibraryHelper::RegexFromList(std::string& out, // else and the result can be checked after matching. out += "("; const char* sep = ""; - for (std::vector<std::string>::const_iterator si = in.begin(); - si != in.end(); ++si) { + for (std::string const& s : in) { // Separate from previous item. out += sep; sep = "|"; // Append this item. - this->RegexFromLiteral(out, *si); + this->RegexFromLiteral(out, s); } out += ")"; } bool cmFindLibraryHelper::HasValidSuffix(std::string const& name) { - for (std::vector<std::string>::const_iterator si = this->Suffixes.begin(); - si != this->Suffixes.end(); ++si) { - std::string suffix = *si; + for (std::string suffix : this->Suffixes) { if (name.length() <= suffix.length()) { continue; } @@ -339,9 +334,8 @@ void cmFindLibraryHelper::SetName(std::string const& name) bool cmFindLibraryHelper::CheckDirectory(std::string const& path) { - for (std::vector<Name>::iterator i = this->Names.begin(); - i != this->Names.end(); ++i) { - if (this->CheckDirectoryForName(path, *i)) { + for (Name& i : this->Names) { + if (this->CheckDirectoryForName(path, i)) { return true; } } @@ -376,9 +370,7 @@ bool cmFindLibraryHelper::CheckDirectoryForName(std::string const& path, std::string dir = path; cmSystemTools::ConvertToUnixSlashes(dir); std::set<std::string> const& files = this->GG->GetDirectoryContent(dir); - for (std::set<std::string>::const_iterator fi = files.begin(); - fi != files.end(); ++fi) { - std::string const& origName = *fi; + for (std::string const& origName : files) { #if defined(_WIN32) || defined(__APPLE__) std::string testName = cmSystemTools::LowerCase(origName); #else @@ -430,14 +422,12 @@ std::string cmFindLibraryCommand::FindNormalLibraryNamesPerDir() { // Search for all names in each directory. cmFindLibraryHelper helper(this->Makefile); - for (std::vector<std::string>::const_iterator ni = this->Names.begin(); - ni != this->Names.end(); ++ni) { - helper.AddName(*ni); + for (std::string const& n : this->Names) { + helper.AddName(n); } // Search every directory. - for (std::vector<std::string>::const_iterator p = this->SearchPaths.begin(); - p != this->SearchPaths.end(); ++p) { - if (helper.CheckDirectory(*p)) { + for (std::string const& sp : this->SearchPaths) { + if (helper.CheckDirectory(sp)) { return helper.BestPath; } } @@ -449,16 +439,13 @@ std::string cmFindLibraryCommand::FindNormalLibraryDirsPerName() { // Search the entire path for each name. cmFindLibraryHelper helper(this->Makefile); - for (std::vector<std::string>::const_iterator ni = this->Names.begin(); - ni != this->Names.end(); ++ni) { + for (std::string const& n : this->Names) { // Switch to searching for this name. - helper.SetName(*ni); + helper.SetName(n); // Search every directory. - for (std::vector<std::string>::const_iterator p = - this->SearchPaths.begin(); - p != this->SearchPaths.end(); ++p) { - if (helper.CheckDirectory(*p)) { + for (std::string const& sp : this->SearchPaths) { + if (helper.CheckDirectory(sp)) { return helper.BestPath; } } @@ -479,12 +466,10 @@ std::string cmFindLibraryCommand::FindFrameworkLibraryNamesPerDir() { std::string fwPath; // Search for all names in each search path. - for (std::vector<std::string>::const_iterator di = this->SearchPaths.begin(); - di != this->SearchPaths.end(); ++di) { - for (std::vector<std::string>::const_iterator ni = this->Names.begin(); - ni != this->Names.end(); ++ni) { - fwPath = *di; - fwPath += *ni; + for (std::string const& d : this->SearchPaths) { + for (std::string const& n : this->Names) { + fwPath = d; + fwPath += n; fwPath += ".framework"; if (cmSystemTools::FileIsDirectory(fwPath)) { return cmSystemTools::CollapseFullPath(fwPath); @@ -500,13 +485,10 @@ std::string cmFindLibraryCommand::FindFrameworkLibraryDirsPerName() { std::string fwPath; // Search for each name in all search paths. - for (std::vector<std::string>::const_iterator ni = this->Names.begin(); - ni != this->Names.end(); ++ni) { - for (std::vector<std::string>::const_iterator di = - this->SearchPaths.begin(); - di != this->SearchPaths.end(); ++di) { - fwPath = *di; - fwPath += *ni; + for (std::string const& n : this->Names) { + for (std::string const& d : this->SearchPaths) { + fwPath = d; + fwPath += n; fwPath += ".framework"; if (cmSystemTools::FileIsDirectory(fwPath)) { return cmSystemTools::CollapseFullPath(fwPath); diff --git a/Source/cmFindLibraryCommand.h b/Source/cmFindLibraryCommand.h index fb0a44f..fb8a700 100644 --- a/Source/cmFindLibraryCommand.h +++ b/Source/cmFindLibraryCommand.h @@ -27,14 +27,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmFindLibraryCommand; } + cmCommand* Clone() override { return new cmFindLibraryCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; protected: void AddArchitecturePaths(const char* suffix); diff --git a/Source/cmFindPackageCommand.cxx b/Source/cmFindPackageCommand.cxx index d0cc6ce..5a72655 100644 --- a/Source/cmFindPackageCommand.cxx +++ b/Source/cmFindPackageCommand.cxx @@ -13,6 +13,7 @@ #include <deque> #include <functional> #include <iterator> +#include <memory> // IWYU pragma: keep #include <sstream> #include <stdio.h> #include <string.h> @@ -24,7 +25,6 @@ #include "cmState.h" #include "cmStateTypes.h" #include "cmVersion.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" #if defined(__HAIKU__) @@ -367,14 +367,12 @@ bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args, if (!this->UseFindModules && !this->UseConfigFiles) { std::ostringstream e; e << "given options exclusive to Module mode:\n"; - for (std::set<unsigned int>::const_iterator si = moduleArgs.begin(); - si != moduleArgs.end(); ++si) { - e << " " << args[*si] << "\n"; + for (unsigned int si : moduleArgs) { + e << " " << args[si] << "\n"; } e << "and options exclusive to Config mode:\n"; - for (std::set<unsigned int>::const_iterator si = configArgs.begin(); - si != configArgs.end(); ++si) { - e << " " << args[*si] << "\n"; + for (unsigned int si : configArgs) { + e << " " << args[si] << "\n"; } e << "The options are incompatible."; this->SetError(e.str()); @@ -518,13 +516,12 @@ bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args, // Add the default configs. if (this->Configs.empty()) { - for (std::vector<std::string>::const_iterator ni = this->Names.begin(); - ni != this->Names.end(); ++ni) { - std::string config = *ni; + for (std::string const& n : this->Names) { + std::string config = n; config += "Config.cmake"; this->Configs.push_back(config); - config = cmSystemTools::LowerCase(*ni); + config = cmSystemTools::LowerCase(n); config += "-config.cmake"; this->Configs.push_back(config); } @@ -611,14 +608,12 @@ void cmFindPackageCommand::AddFindDefinition(const std::string& var, void cmFindPackageCommand::RestoreFindDefinitions() { - for (std::map<std::string, OriginalDef>::iterator i = - this->OriginalDefs.begin(); - i != this->OriginalDefs.end(); ++i) { - OriginalDef const& od = i->second; + for (auto const& i : this->OriginalDefs) { + OriginalDef const& od = i.second; if (od.exists) { - this->Makefile->AddDefinition(i->first, od.value.c_str()); + this->Makefile->AddDefinition(i.first, od.value.c_str()); } else { - this->Makefile->RemoveDefinition(i->first); + this->Makefile->RemoveDefinition(i.first); } } } @@ -874,13 +869,11 @@ bool cmFindPackageCommand::HandlePackageMode() std::string consideredVersions; const char* sep = ""; - for (std::vector<ConfigFileInfo>::const_iterator i = - this->ConsideredConfigs.begin(); - i != this->ConsideredConfigs.end(); ++i) { + for (ConfigFileInfo const& i : this->ConsideredConfigs) { consideredConfigFiles += sep; consideredVersions += sep; - consideredConfigFiles += i->filename; - consideredVersions += i->version; + consideredConfigFiles += i.filename; + consideredVersions += i.version; sep = ";"; } @@ -946,9 +939,8 @@ bool cmFindPackageCommand::FindConfig() bool cmFindPackageCommand::FindPrefixedConfig() { std::vector<std::string> const& prefixes = this->SearchPaths; - for (std::vector<std::string>::const_iterator pi = prefixes.begin(); - pi != prefixes.end(); ++pi) { - if (this->SearchPrefix(*pi)) { + for (std::string const& p : prefixes) { + if (this->SearchPrefix(p)) { return true; } } @@ -958,9 +950,8 @@ bool cmFindPackageCommand::FindPrefixedConfig() bool cmFindPackageCommand::FindFrameworkConfig() { std::vector<std::string> const& prefixes = this->SearchPaths; - for (std::vector<std::string>::const_iterator i = prefixes.begin(); - i != prefixes.end(); ++i) { - if (this->SearchFrameworkPrefix(*i)) { + for (std::string const& p : prefixes) { + if (this->SearchFrameworkPrefix(p)) { return true; } } @@ -970,9 +961,8 @@ bool cmFindPackageCommand::FindFrameworkConfig() bool cmFindPackageCommand::FindAppBundleConfig() { std::vector<std::string> const& prefixes = this->SearchPaths; - for (std::vector<std::string>::const_iterator i = prefixes.begin(); - i != prefixes.end(); ++i) { - if (this->SearchAppBundlePrefix(*i)) { + for (std::string const& p : prefixes) { + if (this->SearchAppBundlePrefix(p)) { return true; } } @@ -1171,14 +1161,12 @@ void cmFindPackageCommand::FillPrefixesSystemEnvironment() // working directory. std::vector<std::string> tmp; cmSystemTools::GetPath(tmp); - for (std::vector<std::string>::iterator i = tmp.begin(); i != tmp.end(); - ++i) { + for (std::string const& i : tmp) { // If the path is a PREFIX/bin case then add its parent instead. - if ((cmHasLiteralSuffix(*i, "/bin")) || - (cmHasLiteralSuffix(*i, "/sbin"))) { - paths.AddPath(cmSystemTools::GetFilenamePath(*i)); + if ((cmHasLiteralSuffix(i, "/bin")) || (cmHasLiteralSuffix(i, "/sbin"))) { + paths.AddPath(cmSystemTools::GetFilenamePath(i)); } else { - paths.AddPath(*i); + paths.AddPath(i); } } } @@ -1296,9 +1284,8 @@ void cmFindPackageCommand::LoadPackageRegistryWin(bool user, unsigned int view, if (user && !bad.empty() && RegOpenKeyExW(HKEY_CURRENT_USER, key.c_str(), 0, KEY_SET_VALUE | view, &hKey) == ERROR_SUCCESS) { - for (std::set<std::wstring>::const_iterator vi = bad.begin(); - vi != bad.end(); ++vi) { - RegDeleteValueW(hKey, vi->c_str()); + for (std::wstring const& v : bad) { + RegDeleteValueW(hKey, v.c_str()); } RegCloseKey(hKey); } @@ -1395,10 +1382,8 @@ void cmFindPackageCommand::FillPrefixesUserGuess() { cmSearchPath& paths = this->LabeledPaths[PathLabel::Guess]; - for (std::vector<std::string>::const_iterator p = - this->UserGuessArgs.begin(); - p != this->UserGuessArgs.end(); ++p) { - paths.AddUserPath(*p); + for (std::string const& p : this->UserGuessArgs) { + paths.AddUserPath(p); } } @@ -1406,10 +1391,8 @@ void cmFindPackageCommand::FillPrefixesUserHints() { cmSearchPath& paths = this->LabeledPaths[PathLabel::Hints]; - for (std::vector<std::string>::const_iterator p = - this->UserHintsArgs.begin(); - p != this->UserHintsArgs.end(); ++p) { - paths.AddUserPath(*p); + for (std::string const& p : this->UserHintsArgs) { + paths.AddUserPath(p); } } @@ -1418,12 +1401,10 @@ bool cmFindPackageCommand::SearchDirectory(std::string const& dir) assert(!dir.empty() && dir[dir.size() - 1] == '/'); // Check each path suffix on this directory. - for (std::vector<std::string>::const_iterator si = - this->SearchPathSuffixes.begin(); - si != this->SearchPathSuffixes.end(); ++si) { + for (std::string const& s : this->SearchPathSuffixes) { std::string d = dir; - if (!si->empty()) { - d += *si; + if (!s.empty()) { + d += s; d += "/"; } if (this->CheckDirectory(d)) { @@ -1454,11 +1435,10 @@ bool cmFindPackageCommand::FindConfigFile(std::string const& dir, return false; } - for (std::vector<std::string>::const_iterator ci = this->Configs.begin(); - ci != this->Configs.end(); ++ci) { + for (std::string const& c : this->Configs) { file = dir; file += "/"; - file += *ci; + file += c; if (this->DebugMode) { fprintf(stderr, "Checking file [%s]\n", file.c_str()); } @@ -1631,10 +1611,10 @@ protected: private: bool Search(cmFileList&); virtual bool Search(std::string const& parent, cmFileList&) = 0; - virtual CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const = 0; + virtual std::unique_ptr<cmFileListGeneratorBase> Clone() const = 0; friend class cmFileList; cmFileListGeneratorBase* SetNext(cmFileListGeneratorBase const& next); - CM_AUTO_PTR<cmFileListGeneratorBase> Next; + std::unique_ptr<cmFileListGeneratorBase> Next; }; class cmFileList @@ -1658,7 +1638,7 @@ public: } bool Search() { - if (this->First.get()) { + if (this->First) { return this->First->Search(*this); } return false; @@ -1667,7 +1647,7 @@ public: private: virtual bool Visit(std::string const& fullPath) = 0; friend class cmFileListGeneratorBase; - CM_AUTO_PTR<cmFileListGeneratorBase> First; + std::unique_ptr<cmFileListGeneratorBase> First; cmFileListGeneratorBase* Last; }; @@ -1682,7 +1662,7 @@ public: } private: - bool Visit(std::string const& fullPath) CM_OVERRIDE + bool Visit(std::string const& fullPath) override { if (this->UseSuffixes) { return this->FPC->SearchDirectory(fullPath); @@ -1708,7 +1688,7 @@ cmFileListGeneratorBase* cmFileListGeneratorBase::SetNext( bool cmFileListGeneratorBase::Consider(std::string const& fullPath, cmFileList& listing) { - if (this->Next.get()) { + if (this->Next) { return this->Next->Search(fullPath + "/", listing); } return listing.Visit(fullPath + "/"); @@ -1730,14 +1710,14 @@ public: private: std::string String; - bool Search(std::string const& parent, cmFileList& lister) CM_OVERRIDE + bool Search(std::string const& parent, cmFileList& lister) override { std::string fullPath = parent + this->String; return this->Consider(fullPath, lister); } - CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const CM_OVERRIDE + std::unique_ptr<cmFileListGeneratorBase> Clone() const override { - CM_AUTO_PTR<cmFileListGeneratorBase> g( + std::unique_ptr<cmFileListGeneratorBase> g( new cmFileListGeneratorFixed(*this)); return g; } @@ -1759,19 +1739,18 @@ public: private: std::vector<std::string> const& Vector; - bool Search(std::string const& parent, cmFileList& lister) CM_OVERRIDE + bool Search(std::string const& parent, cmFileList& lister) override { - for (std::vector<std::string>::const_iterator i = this->Vector.begin(); - i != this->Vector.end(); ++i) { - if (this->Consider(parent + *i, lister)) { + for (std::string const& i : this->Vector) { + if (this->Consider(parent + i, lister)) { return true; } } return false; } - CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const CM_OVERRIDE + std::unique_ptr<cmFileListGeneratorBase> Clone() const override { - CM_AUTO_PTR<cmFileListGeneratorBase> g( + std::unique_ptr<cmFileListGeneratorBase> g( new cmFileListGeneratorEnumerate(*this)); return g; } @@ -1809,7 +1788,7 @@ protected: private: std::vector<std::string> const& Names; - bool Search(std::string const& parent, cmFileList& lister) CM_OVERRIDE + bool Search(std::string const& parent, cmFileList& lister) override { // Construct a list of matches. std::vector<std::string> matches; @@ -1820,9 +1799,8 @@ private: if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) { continue; } - for (std::vector<std::string>::const_iterator ni = this->Names.begin(); - ni != this->Names.end(); ++ni) { - if (cmsysString_strncasecmp(fname, ni->c_str(), ni->length()) == 0) { + for (std::string const& n : this->Names) { + if (cmsysString_strncasecmp(fname, n.c_str(), n.length()) == 0) { matches.push_back(fname); } } @@ -1835,17 +1813,16 @@ private: SortDirection); } - for (std::vector<std::string>::const_iterator i = matches.begin(); - i != matches.end(); ++i) { - if (this->Consider(parent + *i, lister)) { + for (std::string const& i : matches) { + if (this->Consider(parent + i, lister)) { return true; } } return false; } - CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const CM_OVERRIDE + std::unique_ptr<cmFileListGeneratorBase> Clone() const override { - CM_AUTO_PTR<cmFileListGeneratorBase> g( + std::unique_ptr<cmFileListGeneratorBase> g( new cmFileListGeneratorProject(*this)); return g; } @@ -1871,7 +1848,7 @@ public: private: std::vector<std::string> const& Names; std::string Extension; - bool Search(std::string const& parent, cmFileList& lister) CM_OVERRIDE + bool Search(std::string const& parent, cmFileList& lister) override { // Construct a list of matches. std::vector<std::string> matches; @@ -1882,9 +1859,7 @@ private: if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) { continue; } - for (std::vector<std::string>::const_iterator ni = this->Names.begin(); - ni != this->Names.end(); ++ni) { - std::string name = *ni; + for (std::string name : this->Names) { name += this->Extension; if (cmsysString_strcasecmp(fname, name.c_str()) == 0) { matches.push_back(fname); @@ -1892,17 +1867,16 @@ private: } } - for (std::vector<std::string>::const_iterator i = matches.begin(); - i != matches.end(); ++i) { - if (this->Consider(parent + *i, lister)) { + for (std::string const& i : matches) { + if (this->Consider(parent + i, lister)) { return true; } } return false; } - CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const CM_OVERRIDE + std::unique_ptr<cmFileListGeneratorBase> Clone() const override { - CM_AUTO_PTR<cmFileListGeneratorBase> g( + std::unique_ptr<cmFileListGeneratorBase> g( new cmFileListGeneratorMacProject(*this)); return g; } @@ -1925,7 +1899,7 @@ public: private: std::string String; - bool Search(std::string const& parent, cmFileList& lister) CM_OVERRIDE + bool Search(std::string const& parent, cmFileList& lister) override { // Look for matching files. std::vector<std::string> matches; @@ -1944,9 +1918,9 @@ private: } return false; } - CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const CM_OVERRIDE + std::unique_ptr<cmFileListGeneratorBase> Clone() const override { - CM_AUTO_PTR<cmFileListGeneratorBase> g( + std::unique_ptr<cmFileListGeneratorBase> g( new cmFileListGeneratorCaseInsensitive(*this)); return g; } @@ -1968,7 +1942,7 @@ public: private: std::string Pattern; - bool Search(std::string const& parent, cmFileList& lister) CM_OVERRIDE + bool Search(std::string const& parent, cmFileList& lister) override { // Glob the set of matching files. std::string expr = parent; @@ -1980,20 +1954,18 @@ private: std::vector<std::string> const& files = g.GetFiles(); // Look for directories among the matches. - for (std::vector<std::string>::const_iterator fi = files.begin(); - fi != files.end(); ++fi) { - if (cmSystemTools::FileIsDirectory(*fi)) { - if (this->Consider(*fi, lister)) { + for (std::string const& f : files) { + if (cmSystemTools::FileIsDirectory(f)) { + if (this->Consider(f, lister)) { return true; } } } return false; } - CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const CM_OVERRIDE + std::unique_ptr<cmFileListGeneratorBase> Clone() const override { - CM_AUTO_PTR<cmFileListGeneratorBase> g(new cmFileListGeneratorGlob(*this)); - return g; + return cm::make_unique<cmFileListGeneratorGlob>(*this); } }; diff --git a/Source/cmFindPackageCommand.h b/Source/cmFindPackageCommand.h index 69deb13..150a51d 100644 --- a/Source/cmFindPackageCommand.h +++ b/Source/cmFindPackageCommand.h @@ -51,14 +51,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmFindPackageCommand; } + cmCommand* Clone() override { return new cmFindPackageCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: class PathLabel : public cmFindCommon::PathLabel diff --git a/Source/cmFindPathCommand.cxx b/Source/cmFindPathCommand.cxx index d3541ca..ea26410 100644 --- a/Source/cmFindPathCommand.cxx +++ b/Source/cmFindPathCommand.cxx @@ -85,7 +85,7 @@ std::string cmFindPathCommand::FindHeaderInFramework(std::string const& file, // if the framework has a path in it then just use the filename if (frameWorkName.find('/') != std::string::npos) { fileName = file; - frameWorkName = ""; + frameWorkName.clear(); } if (!frameWorkName.empty()) { std::string fpath = dir; @@ -124,18 +124,15 @@ std::string cmFindPathCommand::FindHeaderInFramework(std::string const& file, std::string cmFindPathCommand::FindNormalHeader() { std::string tryPath; - for (std::vector<std::string>::const_iterator ni = this->Names.begin(); - ni != this->Names.end(); ++ni) { - for (std::vector<std::string>::const_iterator p = - this->SearchPaths.begin(); - p != this->SearchPaths.end(); ++p) { - tryPath = *p; - tryPath += *ni; + for (std::string const& n : this->Names) { + for (std::string const& sp : this->SearchPaths) { + tryPath = sp; + tryPath += n; if (cmSystemTools::FileExists(tryPath.c_str())) { if (this->IncludeFileInPath) { return tryPath; } - return *p; + return sp; } } } @@ -144,12 +141,9 @@ std::string cmFindPathCommand::FindNormalHeader() std::string cmFindPathCommand::FindFrameworkHeader() { - for (std::vector<std::string>::const_iterator ni = this->Names.begin(); - ni != this->Names.end(); ++ni) { - for (std::vector<std::string>::const_iterator p = - this->SearchPaths.begin(); - p != this->SearchPaths.end(); ++p) { - std::string fwPath = this->FindHeaderInFramework(*ni, *p); + for (std::string const& n : this->Names) { + for (std::string const& sp : this->SearchPaths) { + std::string fwPath = this->FindHeaderInFramework(n, sp); if (!fwPath.empty()) { return fwPath; } diff --git a/Source/cmFindPathCommand.h b/Source/cmFindPathCommand.h index 5b9ddf8..cb0db4c 100644 --- a/Source/cmFindPathCommand.h +++ b/Source/cmFindPathCommand.h @@ -27,14 +27,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmFindPathCommand; } + cmCommand* Clone() override { return new cmFindPathCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; bool IncludeFileInPath; diff --git a/Source/cmFindProgramCommand.cxx b/Source/cmFindProgramCommand.cxx index 9327c18..2059b3d 100644 --- a/Source/cmFindProgramCommand.cxx +++ b/Source/cmFindProgramCommand.cxx @@ -45,9 +45,8 @@ struct cmFindProgramHelper } bool CheckDirectory(std::string const& path) { - for (std::vector<std::string>::iterator i = this->Names.begin(); - i != this->Names.end(); ++i) { - if (this->CheckDirectoryForName(path, *i)) { + for (std::string const& n : this->Names) { + if (this->CheckDirectoryForName(path, n)) { return true; } } @@ -55,14 +54,13 @@ struct cmFindProgramHelper } bool CheckDirectoryForName(std::string const& path, std::string const& name) { - for (std::vector<std::string>::iterator ext = this->Extensions.begin(); - ext != this->Extensions.end(); ++ext) { + for (std::string const& ext : this->Extensions) { this->TestPath = path; this->TestPath += name; - if (!ext->empty() && cmSystemTools::StringEndsWith(name, ext->c_str())) { + if (!ext.empty() && cmSystemTools::StringEndsWith(name, ext.c_str())) { continue; } - this->TestPath += *ext; + this->TestPath += ext; if (cmSystemTools::FileExists(this->TestPath, true)) { this->BestPath = cmSystemTools::CollapseFullPath(this->TestPath); return true; @@ -99,8 +97,8 @@ bool cmFindProgramCommand::InitialPass(std::vector<std::string> const& argsIn, return true; } - std::string result = FindProgram(); - if (result != "") { + std::string const result = FindProgram(); + if (!result.empty()) { // Save the value in the cache this->Makefile->AddCacheDefinition(this->VariableName, result.c_str(), this->VariableDocumentation.c_str(), @@ -143,9 +141,8 @@ std::string cmFindProgramCommand::FindNormalProgramNamesPerDir() { // Search for all names in each directory. cmFindProgramHelper helper; - for (std::vector<std::string>::const_iterator ni = this->Names.begin(); - ni != this->Names.end(); ++ni) { - helper.AddName(*ni); + for (std::string const& n : this->Names) { + helper.AddName(n); } // Check for the names themselves (e.g. absolute paths). @@ -154,9 +151,8 @@ std::string cmFindProgramCommand::FindNormalProgramNamesPerDir() } // Search every directory. - for (std::vector<std::string>::const_iterator p = this->SearchPaths.begin(); - p != this->SearchPaths.end(); ++p) { - if (helper.CheckDirectory(*p)) { + for (std::string const& sp : this->SearchPaths) { + if (helper.CheckDirectory(sp)) { return helper.BestPath; } } @@ -168,10 +164,9 @@ std::string cmFindProgramCommand::FindNormalProgramDirsPerName() { // Search the entire path for each name. cmFindProgramHelper helper; - for (std::vector<std::string>::const_iterator ni = this->Names.begin(); - ni != this->Names.end(); ++ni) { + for (std::string const& n : this->Names) { // Switch to searching for this name. - helper.SetName(*ni); + helper.SetName(n); // Check for the name by itself (e.g. an absolute path). if (helper.CheckDirectory(std::string())) { @@ -179,10 +174,8 @@ std::string cmFindProgramCommand::FindNormalProgramDirsPerName() } // Search every directory. - for (std::vector<std::string>::const_iterator p = - this->SearchPaths.begin(); - p != this->SearchPaths.end(); ++p) { - if (helper.CheckDirectory(*p)) { + for (std::string const& sp : this->SearchPaths) { + if (helper.CheckDirectory(sp)) { return helper.BestPath; } } @@ -193,10 +186,9 @@ std::string cmFindProgramCommand::FindNormalProgramDirsPerName() std::string cmFindProgramCommand::FindAppBundle() { - for (std::vector<std::string>::const_iterator name = this->Names.begin(); - name != this->Names.end(); ++name) { + for (std::string const& name : this->Names) { - std::string appName = *name + std::string(".app"); + std::string appName = name + std::string(".app"); std::string appPath = cmSystemTools::FindDirectory(appName, this->SearchPaths, true); @@ -237,7 +229,7 @@ std::string cmFindProgramCommand::GetBundleExecutable( // returned executableURL is relative to <appbundle>/Contents/MacOS/ CFURLRef executableURL = CFBundleCopyExecutableURL(appBundle); - if (executableURL != NULL) { + if (executableURL != nullptr) { const int MAX_OSX_PATH_SIZE = 1024; char buffer[MAX_OSX_PATH_SIZE]; diff --git a/Source/cmFindProgramCommand.h b/Source/cmFindProgramCommand.h index f4d78b4..147936c 100644 --- a/Source/cmFindProgramCommand.h +++ b/Source/cmFindProgramCommand.h @@ -28,14 +28,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmFindProgramCommand; } + cmCommand* Clone() override { return new cmFindProgramCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: std::string FindProgram(); diff --git a/Source/cmForEachCommand.cxx b/Source/cmForEachCommand.cxx index 8346b23..542a860 100644 --- a/Source/cmForEachCommand.cxx +++ b/Source/cmForEachCommand.cxx @@ -2,6 +2,7 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmForEachCommand.h" +#include <memory> // IWYU pragma: keep #include <sstream> #include <stdio.h> #include <stdlib.h> @@ -9,7 +10,6 @@ #include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmSystemTools.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" cmForEachFunctionBlocker::cmForEachFunctionBlocker(cmMakefile* mf) @@ -35,7 +35,8 @@ bool cmForEachFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff, // if this is the endofreach for this statement if (!this->Depth) { // Remove the function blocker for this scope or bail. - CM_AUTO_PTR<cmFunctionBlocker> fb(mf.RemoveFunctionBlocker(this, lff)); + std::unique_ptr<cmFunctionBlocker> fb( + mf.RemoveFunctionBlocker(this, lff)); if (!fb.get()) { return false; } @@ -54,9 +55,9 @@ bool cmForEachFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff, mf.AddDefinition(this->Args[0], j->c_str()); // Invoke all the functions that were collected in the block. cmExecutionStatus status; - for (unsigned int c = 0; c < this->Functions.size(); ++c) { + for (cmListFileFunction const& func : this->Functions) { status.Clear(); - mf.ExecuteCommand(this->Functions[c], status); + mf.ExecuteCommand(func, status); if (status.GetReturnInvoked()) { inStatus.SetReturnInvoked(); // restore the variable to its prior value @@ -181,7 +182,7 @@ bool cmForEachCommand::InitialPass(std::vector<std::string> const& args, bool cmForEachCommand::HandleInMode(std::vector<std::string> const& args) { - CM_AUTO_PTR<cmForEachFunctionBlocker> f( + std::unique_ptr<cmForEachFunctionBlocker> f( new cmForEachFunctionBlocker(this->Makefile)); f->Args.push_back(args[0]); @@ -213,7 +214,7 @@ bool cmForEachCommand::HandleInMode(std::vector<std::string> const& args) } } - this->Makefile->AddFunctionBlocker(f.release()); // TODO: pass auto_ptr + this->Makefile->AddFunctionBlocker(f.release()); // TODO: pass unique_ptr return true; } diff --git a/Source/cmForEachCommand.h b/Source/cmForEachCommand.h index 6787023..5131a4f 100644 --- a/Source/cmForEachCommand.h +++ b/Source/cmForEachCommand.h @@ -19,10 +19,10 @@ class cmForEachFunctionBlocker : public cmFunctionBlocker { public: cmForEachFunctionBlocker(cmMakefile* mf); - ~cmForEachFunctionBlocker() CM_OVERRIDE; + ~cmForEachFunctionBlocker() override; bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf, - cmExecutionStatus&) CM_OVERRIDE; - bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf) CM_OVERRIDE; + cmExecutionStatus&) override; + bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf) override; std::vector<std::string> Args; std::vector<cmListFileFunction> Functions; @@ -39,14 +39,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmForEachCommand; } + cmCommand* Clone() override { return new cmForEachCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: bool HandleInMode(std::vector<std::string> const& args); diff --git a/Source/cmFortranParserImpl.cxx b/Source/cmFortranParserImpl.cxx index 333b6c1..81f1286 100644 --- a/Source/cmFortranParserImpl.cxx +++ b/Source/cmFortranParserImpl.cxx @@ -30,9 +30,8 @@ bool cmFortranParser_s::FindIncludeFile(const char* dir, } // Search the include path for the file. - for (std::vector<std::string>::const_iterator i = this->IncludePath.begin(); - i != this->IncludePath.end(); ++i) { - fullName = *i; + for (std::string const& i : this->IncludePath) { + fullName = i; fullName += "/"; fullName += includeName; if (cmSystemTools::FileExists(fullName.c_str(), true)) { @@ -127,7 +126,7 @@ int cmFortranParser_Input(cmFortranParser* parser, char* buffer, void cmFortranParser_StringStart(cmFortranParser* parser) { - parser->TokenString = ""; + parser->TokenString.clear(); } const char* cmFortranParser_StringEnd(cmFortranParser* parser) diff --git a/Source/cmFunctionCommand.cxx b/Source/cmFunctionCommand.cxx index ee52bde..774df84 100644 --- a/Source/cmFunctionCommand.cxx +++ b/Source/cmFunctionCommand.cxx @@ -18,12 +18,12 @@ public: cmFunctionHelperCommand() {} ///! clean up any memory allocated by the function - ~cmFunctionHelperCommand() CM_OVERRIDE {} + ~cmFunctionHelperCommand() override {} /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmFunctionHelperCommand* newC = new cmFunctionHelperCommand; // we must copy when we clone @@ -39,10 +39,10 @@ public: * the CMakeLists.txt file. */ bool InvokeInitialPass(const std::vector<cmListFileArgument>& args, - cmExecutionStatus&) CM_OVERRIDE; + cmExecutionStatus&) override; bool InitialPass(std::vector<std::string> const&, - cmExecutionStatus&) CM_OVERRIDE + cmExecutionStatus&) override { return false; } @@ -104,9 +104,9 @@ bool cmFunctionHelperCommand::InvokeInitialPass( // Invoke all the functions that were collected in the block. // for each function - for (unsigned int c = 0; c < this->Functions.size(); ++c) { + for (cmListFileFunction const& func : this->Functions) { cmExecutionStatus status; - if (!this->Makefile->ExecuteCommand(this->Functions[c], status) || + if (!this->Makefile->ExecuteCommand(func, status) || status.GetNestedError()) { // The error message should have already included the call stack // so we do not need to report an error here. diff --git a/Source/cmFunctionCommand.h b/Source/cmFunctionCommand.h index 48d6b36..3352b92 100644 --- a/Source/cmFunctionCommand.h +++ b/Source/cmFunctionCommand.h @@ -19,10 +19,10 @@ class cmFunctionFunctionBlocker : public cmFunctionBlocker { public: cmFunctionFunctionBlocker() { this->Depth = 0; } - ~cmFunctionFunctionBlocker() CM_OVERRIDE {} + ~cmFunctionFunctionBlocker() override {} bool IsFunctionBlocked(const cmListFileFunction&, cmMakefile& mf, - cmExecutionStatus&) CM_OVERRIDE; - bool ShouldRemove(const cmListFileFunction&, cmMakefile& mf) CM_OVERRIDE; + cmExecutionStatus&) override; + bool ShouldRemove(const cmListFileFunction&, cmMakefile& mf) override; std::vector<std::string> Args; std::vector<cmListFileFunction> Functions; @@ -36,14 +36,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmFunctionCommand; } + cmCommand* Clone() override { return new cmFunctionCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmGeneratedFileStream.h b/Source/cmGeneratedFileStream.h index 5144772..a96f38f 100644 --- a/Source/cmGeneratedFileStream.h +++ b/Source/cmGeneratedFileStream.h @@ -94,7 +94,7 @@ public: * file was successfully written before allowing the original to be * replaced. */ - ~cmGeneratedFileStream() CM_OVERRIDE; + ~cmGeneratedFileStream() override; /** * Open an output file by name. This should be used only with a diff --git a/Source/cmGeneratorExpression.cxx b/Source/cmGeneratorExpression.cxx index 00b5ff4..86991c1 100644 --- a/Source/cmGeneratorExpression.cxx +++ b/Source/cmGeneratorExpression.cxx @@ -3,6 +3,7 @@ #include "cmGeneratorExpression.h" #include "cmsys/RegularExpression.hxx" +#include <memory> // IWYU pragma: keep #include <utility> #include "assert.h" @@ -12,7 +13,6 @@ #include "cmGeneratorExpressionLexer.h" #include "cmGeneratorExpressionParser.h" #include "cmSystemTools.h" -#include "cm_auto_ptr.hxx" cmGeneratorExpression::cmGeneratorExpression( const cmListFileBacktrace& backtrace) @@ -20,14 +20,14 @@ cmGeneratorExpression::cmGeneratorExpression( { } -CM_AUTO_PTR<cmCompiledGeneratorExpression> cmGeneratorExpression::Parse( +std::unique_ptr<cmCompiledGeneratorExpression> cmGeneratorExpression::Parse( std::string const& input) { - return CM_AUTO_PTR<cmCompiledGeneratorExpression>( + return std::unique_ptr<cmCompiledGeneratorExpression>( new cmCompiledGeneratorExpression(this->Backtrace, input)); } -CM_AUTO_PTR<cmCompiledGeneratorExpression> cmGeneratorExpression::Parse( +std::unique_ptr<cmCompiledGeneratorExpression> cmGeneratorExpression::Parse( const char* input) { return this->Parse(std::string(input ? input : "")); @@ -68,7 +68,7 @@ const char* cmCompiledGeneratorExpression::EvaluateWithContext( return this->Input.c_str(); } - this->Output = ""; + this->Output.clear(); std::vector<cmGeneratorExpressionEvaluator*>::const_iterator it = this->Evaluators.begin(); @@ -81,7 +81,7 @@ const char* cmCompiledGeneratorExpression::EvaluateWithContext( this->SeenTargetProperties.insert(context.SeenTargetProperties.begin(), context.SeenTargetProperties.end()); if (context.HadError) { - this->Output = ""; + this->Output.clear(); break; } } @@ -199,15 +199,14 @@ static void prefixItems(const std::string& content, std::string& result, std::vector<std::string> entries; cmGeneratorExpression::Split(content, entries); const char* sep = ""; - for (std::vector<std::string>::const_iterator ei = entries.begin(); - ei != entries.end(); ++ei) { + for (std::string const& e : entries) { result += sep; sep = ";"; - if (!cmSystemTools::FileIsFullPath(ei->c_str()) && - cmGeneratorExpression::Find(*ei) != 0) { + if (!cmSystemTools::FileIsFullPath(e.c_str()) && + cmGeneratorExpression::Find(e) != 0) { result += prefix; } - result += *ei; + result += e; } } @@ -297,7 +296,7 @@ void cmGeneratorExpression::Split(const std::string& input, std::string::size_type startPos = input.rfind(';', pos); if (startPos == std::string::npos) { preGenex = part; - part = ""; + part.clear(); } else if (startPos != pos - 1 && startPos >= lastPos) { part = input.substr(lastPos, startPos - lastPos); preGenex = input.substr(startPos + 1, pos - startPos - 1); @@ -379,7 +378,7 @@ void cmCompiledGeneratorExpression::GetMaxLanguageStandard( const cmGeneratorTarget* tgt, std::map<std::string, std::string>& mapping) { typedef std::map<cmGeneratorTarget const*, - std::map<std::string, std::string> > + std::map<std::string, std::string>> MapType; MapType::const_iterator it = this->MaxLanguageStandard.find(tgt); if (it != this->MaxLanguageStandard.end()) { diff --git a/Source/cmGeneratorExpression.h b/Source/cmGeneratorExpression.h index 9d9ae4e..cface0d 100644 --- a/Source/cmGeneratorExpression.h +++ b/Source/cmGeneratorExpression.h @@ -7,8 +7,8 @@ #include "cmListFileCache.h" -#include "cm_auto_ptr.hxx" #include <map> +#include <memory> // IWYU pragma: keep #include <set> #include <string> #include <vector> @@ -39,8 +39,9 @@ public: cmListFileBacktrace const& backtrace = cmListFileBacktrace()); ~cmGeneratorExpression(); - CM_AUTO_PTR<cmCompiledGeneratorExpression> Parse(std::string const& input); - CM_AUTO_PTR<cmCompiledGeneratorExpression> Parse(const char* input); + std::unique_ptr<cmCompiledGeneratorExpression> Parse( + std::string const& input); + std::unique_ptr<cmCompiledGeneratorExpression> Parse(const char* input); enum PreprocessContext { @@ -143,7 +144,7 @@ private: mutable std::set<cmGeneratorTarget const*> AllTargetsSeen; mutable std::set<std::string> SeenTargetProperties; mutable std::map<cmGeneratorTarget const*, - std::map<std::string, std::string> > + std::map<std::string, std::string>> MaxLanguageStandard; mutable std::string Output; mutable bool HadContextSensitiveCondition; diff --git a/Source/cmGeneratorExpressionContext.h b/Source/cmGeneratorExpressionContext.h index cf292dc..5b0123e 100644 --- a/Source/cmGeneratorExpressionContext.h +++ b/Source/cmGeneratorExpressionContext.h @@ -26,7 +26,7 @@ struct cmGeneratorExpressionContext std::set<cmGeneratorTarget const*> AllTargets; std::set<std::string> SeenTargetProperties; std::set<cmGeneratorTarget const*> SourceSensitiveTargets; - std::map<cmGeneratorTarget const*, std::map<std::string, std::string> > + std::map<cmGeneratorTarget const*, std::map<std::string, std::string>> MaxLanguageStandard; cmLocalGenerator* LG; std::string Config; diff --git a/Source/cmGeneratorExpressionDAGChecker.cxx b/Source/cmGeneratorExpressionDAGChecker.cxx index c026631..f0eafb4 100644 --- a/Source/cmGeneratorExpressionDAGChecker.cxx +++ b/Source/cmGeneratorExpressionDAGChecker.cxx @@ -58,7 +58,7 @@ void cmGeneratorExpressionDAGChecker::Initialize() TEST_TRANSITIVE_PROPERTY_METHOD) false)) // NOLINT(clang-tidy) #undef TEST_TRANSITIVE_PROPERTY_METHOD { - std::map<std::string, std::set<std::string> >::const_iterator it = + std::map<std::string, std::set<std::string>>::const_iterator it = top->Seen.find(this->Target); if (it != top->Seen.end()) { const std::set<std::string>& propSet = it->second; diff --git a/Source/cmGeneratorExpressionDAGChecker.h b/Source/cmGeneratorExpressionDAGChecker.h index a3974ab..3f73fca 100644 --- a/Source/cmGeneratorExpressionDAGChecker.h +++ b/Source/cmGeneratorExpressionDAGChecker.h @@ -82,7 +82,7 @@ private: const cmGeneratorExpressionDAGChecker* const Parent; const std::string Target; const std::string Property; - std::map<std::string, std::set<std::string> > Seen; + std::map<std::string, std::set<std::string>> Seen; const GeneratorExpressionContent* const Content; const cmListFileBacktrace Backtrace; Result CheckResult; diff --git a/Source/cmGeneratorExpressionEvaluationFile.cxx b/Source/cmGeneratorExpressionEvaluationFile.cxx index a2ff189..87b6b34 100644 --- a/Source/cmGeneratorExpressionEvaluationFile.cxx +++ b/Source/cmGeneratorExpressionEvaluationFile.cxx @@ -3,6 +3,7 @@ #include "cmGeneratorExpressionEvaluationFile.h" #include "cmsys/FStream.hxx" +#include <memory> // IWYU pragma: keep #include <sstream> #include <utility> @@ -13,17 +14,16 @@ #include "cmMakefile.h" #include "cmSourceFile.h" #include "cmSystemTools.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" cmGeneratorExpressionEvaluationFile::cmGeneratorExpressionEvaluationFile( const std::string& input, - CM_AUTO_PTR<cmCompiledGeneratorExpression> outputFileExpr, - CM_AUTO_PTR<cmCompiledGeneratorExpression> condition, bool inputIsContent, - cmPolicies::PolicyStatus policyStatusCMP0070) + std::unique_ptr<cmCompiledGeneratorExpression> outputFileExpr, + std::unique_ptr<cmCompiledGeneratorExpression> condition, + bool inputIsContent, cmPolicies::PolicyStatus policyStatusCMP0070) : Input(input) - , OutputFileExpr(outputFileExpr) - , Condition(condition) + , OutputFileExpr(std::move(outputFileExpr)) + , Condition(std::move(condition)) , InputIsContent(inputIsContent) , PolicyStatusCMP0070(policyStatusCMP0070) { @@ -99,10 +99,9 @@ void cmGeneratorExpressionEvaluationFile::CreateOutputFile( cmGlobalGenerator* gg = lg->GetGlobalGenerator(); gg->GetEnabledLanguages(enabledLanguages); - for (std::vector<std::string>::const_iterator le = enabledLanguages.begin(); - le != enabledLanguages.end(); ++le) { + for (std::string const& le : enabledLanguages) { std::string name = this->OutputFileExpr->Evaluate( - lg, config, false, nullptr, nullptr, nullptr, *le); + lg, config, false, nullptr, nullptr, nullptr, le); cmSourceFile* sf = lg->GetMakefile()->GetOrCreateSource(name); sf->SetProperty("GENERATED", "1"); @@ -145,7 +144,7 @@ void cmGeneratorExpressionEvaluationFile::Generate(cmLocalGenerator* lg) cmListFileBacktrace lfbt = this->OutputFileExpr->GetBacktrace(); cmGeneratorExpression contentGE(lfbt); - CM_AUTO_PTR<cmCompiledGeneratorExpression> inputExpression = + std::unique_ptr<cmCompiledGeneratorExpression> inputExpression = contentGE.Parse(inputContent); std::map<std::string, std::string> outputFiles; @@ -161,11 +160,9 @@ void cmGeneratorExpressionEvaluationFile::Generate(cmLocalGenerator* lg) cmGlobalGenerator* gg = lg->GetGlobalGenerator(); gg->GetEnabledLanguages(enabledLanguages); - for (std::vector<std::string>::const_iterator le = enabledLanguages.begin(); - le != enabledLanguages.end(); ++le) { - for (std::vector<std::string>::const_iterator li = allConfigs.begin(); - li != allConfigs.end(); ++li) { - this->Generate(lg, *li, *le, inputExpression.get(), outputFiles, perm); + for (std::string const& le : enabledLanguages) { + for (std::string const& li : allConfigs) { + this->Generate(lg, li, le, inputExpression.get(), outputFiles, perm); if (cmSystemTools::GetFatalErrorOccured()) { return; } diff --git a/Source/cmGeneratorExpressionEvaluationFile.h b/Source/cmGeneratorExpressionEvaluationFile.h index ecf919d..2a79069 100644 --- a/Source/cmGeneratorExpressionEvaluationFile.h +++ b/Source/cmGeneratorExpressionEvaluationFile.h @@ -6,12 +6,12 @@ #include "cmConfigure.h" // IWYU pragma: keep #include <map> +#include <memory> // IWYU pragma: keep #include <string> #include <vector> #include "cmGeneratorExpression.h" #include "cmPolicies.h" -#include "cm_auto_ptr.hxx" #include "cm_sys_stat.h" class cmLocalGenerator; @@ -21,9 +21,9 @@ class cmGeneratorExpressionEvaluationFile public: cmGeneratorExpressionEvaluationFile( const std::string& input, - CM_AUTO_PTR<cmCompiledGeneratorExpression> outputFileExpr, - CM_AUTO_PTR<cmCompiledGeneratorExpression> condition, bool inputIsContent, - cmPolicies::PolicyStatus policyStatusCMP0070); + std::unique_ptr<cmCompiledGeneratorExpression> outputFileExpr, + std::unique_ptr<cmCompiledGeneratorExpression> condition, + bool inputIsContent, cmPolicies::PolicyStatus policyStatusCMP0070); void Generate(cmLocalGenerator* lg); @@ -47,8 +47,8 @@ private: private: const std::string Input; - const CM_AUTO_PTR<cmCompiledGeneratorExpression> OutputFileExpr; - const CM_AUTO_PTR<cmCompiledGeneratorExpression> Condition; + const std::unique_ptr<cmCompiledGeneratorExpression> OutputFileExpr; + const std::unique_ptr<cmCompiledGeneratorExpression> Condition; std::vector<std::string> Files; const bool InputIsContent; cmPolicies::PolicyStatus PolicyStatusCMP0070; diff --git a/Source/cmGeneratorExpressionEvaluator.cxx b/Source/cmGeneratorExpressionEvaluator.cxx index f2dbc26..c73d486 100644 --- a/Source/cmGeneratorExpressionEvaluator.cxx +++ b/Source/cmGeneratorExpressionEvaluator.cxx @@ -25,13 +25,13 @@ std::string GeneratorExpressionContent::ProcessArbitraryContent( const cmGeneratorExpressionNode* node, const std::string& identifier, cmGeneratorExpressionContext* context, cmGeneratorExpressionDAGChecker* dagChecker, - std::vector<std::vector<cmGeneratorExpressionEvaluator*> >::const_iterator + std::vector<std::vector<cmGeneratorExpressionEvaluator*>>::const_iterator pit) const { std::string result; const std::vector< - std::vector<cmGeneratorExpressionEvaluator*> >::const_iterator pend = + std::vector<cmGeneratorExpressionEvaluator*>>::const_iterator pend = this->ParamChildren.end(); for (; pit != pend; ++pit) { std::vector<cmGeneratorExpressionEvaluator*>::const_iterator it = @@ -122,10 +122,10 @@ std::string GeneratorExpressionContent::EvaluateParameters( { const int numExpected = node->NumExpectedParameters(); { - std::vector<std::vector<cmGeneratorExpressionEvaluator*> >::const_iterator + std::vector<std::vector<cmGeneratorExpressionEvaluator*>>::const_iterator pit = this->ParamChildren.begin(); const std::vector< - std::vector<cmGeneratorExpressionEvaluator*> >::const_iterator pend = + std::vector<cmGeneratorExpressionEvaluator*>>::const_iterator pend = this->ParamChildren.end(); const bool acceptsArbitraryContent = node->AcceptsArbitraryContentParameter(); @@ -188,5 +188,5 @@ GeneratorExpressionContent::~GeneratorExpressionContent() { cmDeleteAll(this->IdentifierChildren); std::for_each(this->ParamChildren.begin(), this->ParamChildren.end(), - cmDeleteAll<std::vector<cmGeneratorExpressionEvaluator*> >); + cmDeleteAll<std::vector<cmGeneratorExpressionEvaluator*>>); } diff --git a/Source/cmGeneratorExpressionEvaluator.h b/Source/cmGeneratorExpressionEvaluator.h index a7e5f6f..92dac79 100644 --- a/Source/cmGeneratorExpressionEvaluator.h +++ b/Source/cmGeneratorExpressionEvaluator.h @@ -42,12 +42,12 @@ struct TextContent : public cmGeneratorExpressionEvaluator } std::string Evaluate(cmGeneratorExpressionContext*, - cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE + cmGeneratorExpressionDAGChecker*) const override { return std::string(this->Content, this->Length); } - Type GetType() const CM_OVERRIDE + Type GetType() const override { return cmGeneratorExpressionEvaluator::Text; } @@ -71,23 +71,23 @@ struct GeneratorExpressionContent : public cmGeneratorExpressionEvaluator } void SetParameters( - std::vector<std::vector<cmGeneratorExpressionEvaluator*> > const& + std::vector<std::vector<cmGeneratorExpressionEvaluator*>> const& parameters) { this->ParamChildren = parameters; } - Type GetType() const CM_OVERRIDE + Type GetType() const override { return cmGeneratorExpressionEvaluator::Generator; } std::string Evaluate(cmGeneratorExpressionContext* context, - cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE; + cmGeneratorExpressionDAGChecker*) const override; std::string GetOriginalExpression() const; - ~GeneratorExpressionContent() CM_OVERRIDE; + ~GeneratorExpressionContent() override; private: std::string EvaluateParameters(const cmGeneratorExpressionNode* node, @@ -100,12 +100,12 @@ private: const cmGeneratorExpressionNode* node, const std::string& identifier, cmGeneratorExpressionContext* context, cmGeneratorExpressionDAGChecker* dagChecker, - std::vector<std::vector<cmGeneratorExpressionEvaluator*> >::const_iterator + std::vector<std::vector<cmGeneratorExpressionEvaluator*>>::const_iterator pit) const; private: std::vector<cmGeneratorExpressionEvaluator*> IdentifierChildren; - std::vector<std::vector<cmGeneratorExpressionEvaluator*> > ParamChildren; + std::vector<std::vector<cmGeneratorExpressionEvaluator*>> ParamChildren; const char* StartContent; size_t ContentLength; }; diff --git a/Source/cmGeneratorExpressionNode.cxx b/Source/cmGeneratorExpressionNode.cxx index 7d34293..fea20ba 100644 --- a/Source/cmGeneratorExpressionNode.cxx +++ b/Source/cmGeneratorExpressionNode.cxx @@ -17,7 +17,6 @@ #include "cmStateTypes.h" #include "cmSystemTools.h" #include "cmTarget.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" #include "cmsys/RegularExpression.hxx" @@ -26,6 +25,7 @@ #include <assert.h> #include <errno.h> #include <map> +#include <memory> // IWYU pragma: keep #include <set> #include <sstream> #include <stdlib.h> @@ -39,7 +39,7 @@ std::string cmGeneratorExpressionNode::EvaluateDependentExpression( cmGeneratorExpressionDAGChecker* dagChecker) { cmGeneratorExpression ge(context->Backtrace); - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(prop); + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(prop); cge->SetEvaluateForBuildsystem(context->EvaluateForBuildsystem); std::string result = cge->Evaluate(lg, context->Config, context->Quiet, headTarget, @@ -57,15 +57,15 @@ static const struct ZeroNode : public cmGeneratorExpressionNode { ZeroNode() {} - bool GeneratesContent() const CM_OVERRIDE { return false; } + bool GeneratesContent() const override { return false; } - bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; } + bool AcceptsArbitraryContentParameter() const override { return true; } - std::string Evaluate(const std::vector<std::string>& /*parameters*/, - cmGeneratorExpressionContext* /*context*/, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& /*parameters*/, + cmGeneratorExpressionContext* /*context*/, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { return std::string(); } @@ -75,13 +75,13 @@ static const struct OneNode : public cmGeneratorExpressionNode { OneNode() {} - bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; } + bool AcceptsArbitraryContentParameter() const override { return true; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* /*context*/, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* /*context*/, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { return parameters.front(); } @@ -128,11 +128,11 @@ static const struct NotNode : public cmGeneratorExpressionNode { NotNode() {} - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* context, - const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { if (*parameters.begin() != "0" && *parameters.begin() != "1") { reportError( @@ -148,13 +148,13 @@ static const struct BoolNode : public cmGeneratorExpressionNode { BoolNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return 1; } + int NumExpectedParameters() const override { return 1; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* /*context*/, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* /*context*/, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { return !cmSystemTools::IsOff(parameters.begin()->c_str()) ? "1" : "0"; } @@ -164,12 +164,12 @@ static const struct IfNode : public cmGeneratorExpressionNode { IfNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return 3; } + int NumExpectedParameters() const override { return 3; } std::string Evaluate(const std::vector<std::string>& parameters, cmGeneratorExpressionContext* context, const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE + cmGeneratorExpressionDAGChecker*) const override { if (parameters[0] != "1" && parameters[0] != "0") { reportError(context, content->GetOriginalExpression(), @@ -185,13 +185,13 @@ static const struct StrEqualNode : public cmGeneratorExpressionNode { StrEqualNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return 2; } + int NumExpectedParameters() const override { return 2; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* /*context*/, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* /*context*/, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { return *parameters.begin() == parameters[1] ? "1" : "0"; } @@ -201,13 +201,13 @@ static const struct EqualNode : public cmGeneratorExpressionNode { EqualNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return 2; } + int NumExpectedParameters() const override { return 2; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* context, - const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { char* pEnd; @@ -279,13 +279,13 @@ static const struct LowerCaseNode : public cmGeneratorExpressionNode { LowerCaseNode() {} - bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; } + bool AcceptsArbitraryContentParameter() const override { return true; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* /*context*/, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* /*context*/, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { return cmSystemTools::LowerCase(parameters.front()); } @@ -295,13 +295,13 @@ static const struct UpperCaseNode : public cmGeneratorExpressionNode { UpperCaseNode() {} - bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; } + bool AcceptsArbitraryContentParameter() const override { return true; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* /*context*/, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* /*context*/, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { return cmSystemTools::UpperCase(parameters.front()); } @@ -311,13 +311,13 @@ static const struct MakeCIdentifierNode : public cmGeneratorExpressionNode { MakeCIdentifierNode() {} - bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; } + bool AcceptsArbitraryContentParameter() const override { return true; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* /*context*/, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* /*context*/, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { return cmSystemTools::MakeCidentifier(parameters.front()); } @@ -327,13 +327,13 @@ static const struct Angle_RNode : public cmGeneratorExpressionNode { Angle_RNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return 0; } + int NumExpectedParameters() const override { return 0; } - std::string Evaluate(const std::vector<std::string>& /*parameters*/, - cmGeneratorExpressionContext* /*context*/, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& /*parameters*/, + cmGeneratorExpressionContext* /*context*/, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { return ">"; } @@ -343,13 +343,13 @@ static const struct CommaNode : public cmGeneratorExpressionNode { CommaNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return 0; } + int NumExpectedParameters() const override { return 0; } - std::string Evaluate(const std::vector<std::string>& /*parameters*/, - cmGeneratorExpressionContext* /*context*/, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& /*parameters*/, + cmGeneratorExpressionContext* /*context*/, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { return ","; } @@ -359,13 +359,13 @@ static const struct SemicolonNode : public cmGeneratorExpressionNode { SemicolonNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return 0; } + int NumExpectedParameters() const override { return 0; } - std::string Evaluate(const std::vector<std::string>& /*parameters*/, - cmGeneratorExpressionContext* /*context*/, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& /*parameters*/, + cmGeneratorExpressionContext* /*context*/, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { return ";"; } @@ -375,7 +375,7 @@ struct CompilerIdNode : public cmGeneratorExpressionNode { CompilerIdNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return OneOrZeroParameters; } + int NumExpectedParameters() const override { return OneOrZeroParameters; } std::string EvaluateWithLanguage(const std::vector<std::string>& parameters, cmGeneratorExpressionContext* context, @@ -427,11 +427,11 @@ static const struct CCompilerIdNode : public CompilerIdNode { CCompilerIdNode() {} - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* context, - const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker* dagChecker) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* dagChecker) const override { if (!context->HeadTarget) { reportError( @@ -449,11 +449,11 @@ static const struct CXXCompilerIdNode : public CompilerIdNode { CXXCompilerIdNode() {} - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* context, - const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker* dagChecker) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* dagChecker) const override { if (!context->HeadTarget) { reportError( @@ -471,7 +471,7 @@ struct CompilerVersionNode : public cmGeneratorExpressionNode { CompilerVersionNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return OneOrZeroParameters; } + int NumExpectedParameters() const override { return OneOrZeroParameters; } std::string EvaluateWithLanguage(const std::vector<std::string>& parameters, cmGeneratorExpressionContext* context, @@ -508,11 +508,11 @@ static const struct CCompilerVersionNode : public CompilerVersionNode { CCompilerVersionNode() {} - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* context, - const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker* dagChecker) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* dagChecker) const override { if (!context->HeadTarget) { reportError( @@ -530,11 +530,11 @@ static const struct CxxCompilerVersionNode : public CompilerVersionNode { CxxCompilerVersionNode() {} - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* context, - const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker* dagChecker) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* dagChecker) const override { if (!context->HeadTarget) { reportError( @@ -552,13 +552,13 @@ struct PlatformIdNode : public cmGeneratorExpressionNode { PlatformIdNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return OneOrZeroParameters; } + int NumExpectedParameters() const override { return OneOrZeroParameters; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* context, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { const char* platformId = context->LG->GetMakefile()->GetSafeDefinition("CMAKE_SYSTEM_NAME"); @@ -581,13 +581,13 @@ static const struct VersionGreaterNode : public cmGeneratorExpressionNode { VersionGreaterNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return 2; } + int NumExpectedParameters() const override { return 2; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* /*context*/, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* /*context*/, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER, parameters.front().c_str(), @@ -601,13 +601,13 @@ static const struct VersionGreaterEqNode : public cmGeneratorExpressionNode { VersionGreaterEqNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return 2; } + int NumExpectedParameters() const override { return 2; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* /*context*/, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* /*context*/, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL, parameters.front().c_str(), @@ -621,13 +621,13 @@ static const struct VersionLessNode : public cmGeneratorExpressionNode { VersionLessNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return 2; } + int NumExpectedParameters() const override { return 2; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* /*context*/, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* /*context*/, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { return cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, parameters.front().c_str(), @@ -641,13 +641,13 @@ static const struct VersionLessEqNode : public cmGeneratorExpressionNode { VersionLessEqNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return 2; } + int NumExpectedParameters() const override { return 2; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* /*context*/, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* /*context*/, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { return cmSystemTools::VersionCompare(cmSystemTools::OP_LESS_EQUAL, parameters.front().c_str(), @@ -661,13 +661,13 @@ static const struct VersionEqualNode : public cmGeneratorExpressionNode { VersionEqualNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return 2; } + int NumExpectedParameters() const override { return 2; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* /*context*/, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* /*context*/, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { return cmSystemTools::VersionCompare(cmSystemTools::OP_EQUAL, parameters.front().c_str(), @@ -681,11 +681,11 @@ static const struct LinkOnlyNode : public cmGeneratorExpressionNode { LinkOnlyNode() {} - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* context, - const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker* dagChecker) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* dagChecker) const override { if (!dagChecker) { reportError(context, content->GetOriginalExpression(), @@ -703,13 +703,13 @@ static const struct ConfigurationNode : public cmGeneratorExpressionNode { ConfigurationNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return 0; } + int NumExpectedParameters() const override { return 0; } - std::string Evaluate(const std::vector<std::string>& /*parameters*/, - cmGeneratorExpressionContext* context, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& /*parameters*/, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { context->HadContextSensitiveCondition = true; return context->Config; @@ -720,13 +720,13 @@ static const struct ConfigurationTestNode : public cmGeneratorExpressionNode { ConfigurationTestNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return OneOrZeroParameters; } + int NumExpectedParameters() const override { return OneOrZeroParameters; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* context, - const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { if (parameters.empty()) { return configurationNode.Evaluate(parameters, context, content, nullptr); @@ -779,15 +779,15 @@ static const struct JoinNode : public cmGeneratorExpressionNode { JoinNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return 2; } + int NumExpectedParameters() const override { return 2; } - bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; } + bool AcceptsArbitraryContentParameter() const override { return true; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* /*context*/, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* /*context*/, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { std::vector<std::string> list; cmSystemTools::ExpandListArgument(parameters.front(), list); @@ -799,13 +799,13 @@ static const struct CompileLanguageNode : public cmGeneratorExpressionNode { CompileLanguageNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return OneOrZeroParameters; } + int NumExpectedParameters() const override { return OneOrZeroParameters; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* context, - const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker* dagChecker) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* dagChecker) const override { if (context->Language.empty()) { reportError( @@ -877,13 +877,12 @@ std::string getLinkedTargetsContent( std::string linkedTargetsContent; std::string sep; std::string depString; - for (typename std::vector<T>::const_iterator it = libraries.begin(); - it != libraries.end(); ++it) { + for (T const& l : libraries) { // Broken code can have a target in its own link interface. // Don't follow such link interface entries so as not to create a // self-referencing loop. - if (it->Target && it->Target != target) { - depString += sep + "$<TARGET_PROPERTY:" + it->Target->GetName() + "," + + if (l.Target && l.Target != target) { + depString += sep + "$<TARGET_PROPERTY:" + l.Target->GetName() + "," + interfacePropertyName + ">"; sep = ";"; } @@ -904,13 +903,13 @@ static const struct TargetPropertyNode : public cmGeneratorExpressionNode TargetPropertyNode() {} // This node handles errors on parameter count itself. - int NumExpectedParameters() const CM_OVERRIDE { return OneOrMoreParameters; } + int NumExpectedParameters() const override { return OneOrMoreParameters; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* context, - const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker* dagCheckerParent) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* dagCheckerParent) const override { if (parameters.size() != 1 && parameters.size() != 2) { reportError( @@ -1197,21 +1196,21 @@ static const struct TargetNameNode : public cmGeneratorExpressionNode { TargetNameNode() {} - bool GeneratesContent() const CM_OVERRIDE { return true; } + bool GeneratesContent() const override { return true; } - bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; } - bool RequiresLiteralInput() const CM_OVERRIDE { return true; } + bool AcceptsArbitraryContentParameter() const override { return true; } + bool RequiresLiteralInput() const override { return true; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* /*context*/, - const GeneratorExpressionContent* /*content*/, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* /*context*/, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { return parameters.front(); } - int NumExpectedParameters() const CM_OVERRIDE { return 1; } + int NumExpectedParameters() const override { return 1; } } targetNameNode; @@ -1219,11 +1218,11 @@ static const struct TargetObjectsNode : public cmGeneratorExpressionNode { TargetObjectsNode() {} - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* context, - const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { std::string tgtName = parameters.front(); cmGeneratorTarget* gt = context->LG->FindGeneratorTargetToUse(tgtName); @@ -1281,17 +1280,15 @@ static const struct TargetObjectsNode : public cmGeneratorExpressionNode context->HadContextSensitiveCondition = true; } - for (std::vector<std::string>::iterator oi = objects.begin(); - oi != objects.end(); ++oi) { - *oi = obj_dir + *oi; + for (std::string& o : objects) { + o = obj_dir + o; } } // Create the cmSourceFile instances in the referencing directory. cmMakefile* mf = context->LG->GetMakefile(); - for (std::vector<std::string>::iterator oi = objects.begin(); - oi != objects.end(); ++oi) { - mf->AddTargetObject(tgtName, *oi); + for (std::string& o : objects) { + mf->AddTargetObject(tgtName, o); } return cmJoin(objects, ";"); @@ -1302,13 +1299,13 @@ static const struct CompileFeaturesNode : public cmGeneratorExpressionNode { CompileFeaturesNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return OneOrMoreParameters; } + int NumExpectedParameters() const override { return OneOrMoreParameters; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* context, - const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker* dagChecker) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* dagChecker) const override { cmGeneratorTarget const* target = context->HeadTarget; if (!target) { @@ -1320,21 +1317,20 @@ static const struct CompileFeaturesNode : public cmGeneratorExpressionNode } context->HadHeadSensitiveCondition = true; - typedef std::map<std::string, std::vector<std::string> > LangMap; + typedef std::map<std::string, std::vector<std::string>> LangMap; static LangMap availableFeatures; LangMap testedFeatures; - for (std::vector<std::string>::const_iterator it = parameters.begin(); - it != parameters.end(); ++it) { + for (std::string const& p : parameters) { std::string error; std::string lang; if (!context->LG->GetMakefile()->CompileFeatureKnown( - context->HeadTarget->Target, *it, lang, &error)) { + context->HeadTarget->Target, p, lang, &error)) { reportError(context, content->GetOriginalExpression(), error); return std::string(); } - testedFeatures[lang].push_back(*it); + testedFeatures[lang].push_back(p); if (availableFeatures.find(lang) == availableFeatures.end()) { const char* featuresKnown = @@ -1350,15 +1346,13 @@ static const struct CompileFeaturesNode : public cmGeneratorExpressionNode bool evalLL = dagChecker && dagChecker->EvaluatingLinkLibraries(); - for (LangMap::const_iterator lit = testedFeatures.begin(); - lit != testedFeatures.end(); ++lit) { + for (auto const& lit : testedFeatures) { std::vector<std::string> const& langAvailable = - availableFeatures[lit->first]; + availableFeatures[lit.first]; const char* standardDefault = context->LG->GetMakefile()->GetDefinition( - "CMAKE_" + lit->first + "_STANDARD_DEFAULT"); - for (std::vector<std::string>::const_iterator it = lit->second.begin(); - it != lit->second.end(); ++it) { - if (std::find(langAvailable.begin(), langAvailable.end(), *it) == + "CMAKE_" + lit.first + "_STANDARD_DEFAULT"); + for (std::string const& it : lit.second) { + if (std::find(langAvailable.begin(), langAvailable.end(), it) == langAvailable.end()) { return "0"; } @@ -1368,14 +1362,14 @@ static const struct CompileFeaturesNode : public cmGeneratorExpressionNode continue; } if (!context->LG->GetMakefile()->HaveStandardAvailable( - target->Target, lit->first, *it)) { + target->Target, lit.first, it)) { if (evalLL) { - const char* l = target->GetProperty(lit->first + "_STANDARD"); + const char* l = target->GetProperty(lit.first + "_STANDARD"); if (!l) { l = standardDefault; } assert(l); - context->MaxLanguageStandard[target][lit->first] = l; + context->MaxLanguageStandard[target][lit.first] = l; } else { return "0"; } @@ -1390,7 +1384,7 @@ static const char* targetPolicyWhitelist[] = { nullptr #define TARGET_POLICY_STRING(POLICY) , #POLICY - CM_FOR_EACH_TARGET_POLICY(TARGET_POLICY_STRING) + CM_FOR_EACH_TARGET_POLICY(TARGET_POLICY_STRING) #undef TARGET_POLICY_STRING }; @@ -1430,13 +1424,13 @@ static const struct TargetPolicyNode : public cmGeneratorExpressionNode { TargetPolicyNode() {} - int NumExpectedParameters() const CM_OVERRIDE { return 1; } + int NumExpectedParameters() const override { return 1; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* context, - const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { if (!context->HeadTarget) { reportError( @@ -1491,14 +1485,14 @@ static const struct InstallPrefixNode : public cmGeneratorExpressionNode { InstallPrefixNode() {} - bool GeneratesContent() const CM_OVERRIDE { return true; } - int NumExpectedParameters() const CM_OVERRIDE { return 0; } + bool GeneratesContent() const override { return true; } + int NumExpectedParameters() const override { return 0; } - std::string Evaluate(const std::vector<std::string>& /*parameters*/, - cmGeneratorExpressionContext* context, - const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& /*parameters*/, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { reportError(context, content->GetOriginalExpression(), "INSTALL_PREFIX is a marker for install(EXPORT) only. It " @@ -1711,13 +1705,13 @@ struct TargetFilesystemArtifact : public cmGeneratorExpressionNode { TargetFilesystemArtifact() {} - int NumExpectedParameters() const CM_OVERRIDE { return 1; } + int NumExpectedParameters() const override { return 1; } - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* context, - const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker* dagChecker) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* dagChecker) const override { // Lookup the referenced target. std::string name = *parameters.begin(); @@ -1793,11 +1787,11 @@ static const struct ShellPathNode : public cmGeneratorExpressionNode { ShellPathNode() {} - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext* context, - const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker* /*dagChecker*/) const - CM_OVERRIDE + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { if (!cmSystemTools::FileIsFullPath(parameters.front())) { reportError(context, content->GetOriginalExpression(), diff --git a/Source/cmGeneratorExpressionParser.cxx b/Source/cmGeneratorExpressionParser.cxx index c33349a..278de04 100644 --- a/Source/cmGeneratorExpressionParser.cxx +++ b/Source/cmGeneratorExpressionParser.cxx @@ -97,7 +97,7 @@ void cmGeneratorExpressionParser::ParseGeneratorExpression( return; } - std::vector<std::vector<cmGeneratorExpressionEvaluator*> > parameters; + std::vector<std::vector<cmGeneratorExpressionEvaluator*>> parameters; std::vector<std::vector<cmGeneratorExpressionToken>::const_iterator> commaTokens; std::vector<cmGeneratorExpressionToken>::const_iterator colonToken; diff --git a/Source/cmGeneratorTarget.cxx b/Source/cmGeneratorTarget.cxx index a0a3f4f..ea41204e 100644 --- a/Source/cmGeneratorTarget.cxx +++ b/Source/cmGeneratorTarget.cxx @@ -7,6 +7,7 @@ #include <assert.h> #include <errno.h> #include <iterator> +#include <memory> // IWYU pragma: keep #include <queue> #include <sstream> #include <stdio.h> @@ -32,7 +33,6 @@ #include "cmTarget.h" #include "cmTargetLinkLibraryType.h" #include "cmTargetPropertyComputer.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" class cmMessenger; @@ -64,13 +64,13 @@ class cmGeneratorTarget::TargetPropertyEntry static cmLinkImplItem NoLinkImplItem; public: - TargetPropertyEntry(CM_AUTO_PTR<cmCompiledGeneratorExpression> cge, + TargetPropertyEntry(std::unique_ptr<cmCompiledGeneratorExpression> cge, cmLinkImplItem const& item = NoLinkImplItem) - : ge(cge) + : ge(std::move(cge)) , LinkImplItem(item) { } - const CM_AUTO_PTR<cmCompiledGeneratorExpression> ge; + const std::unique_ptr<cmCompiledGeneratorExpression> ge; cmLinkImplItem const& LinkImplItem; }; cmLinkImplItem cmGeneratorTarget::TargetPropertyEntry::NoLinkImplItem; @@ -84,9 +84,10 @@ void CreatePropertyGeneratorExpressions( for (std::vector<std::string>::const_iterator it = entries.begin(); it != entries.end(); ++it, ++btIt) { cmGeneratorExpression ge(*btIt); - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(*it); + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(*it); cge->SetEvaluateForBuildsystem(evaluateForBuildsystem); - items.push_back(new cmGeneratorTarget::TargetPropertyEntry(cge)); + items.push_back( + new cmGeneratorTarget::TargetPropertyEntry(std::move(cge))); } } @@ -150,15 +151,12 @@ cmGeneratorTarget::~cmGeneratorTarget() const char* cmGeneratorTarget::GetSourcesProperty() const { std::vector<std::string> values; - for (std::vector<cmGeneratorTarget::TargetPropertyEntry *>::const_iterator - it = this->SourceEntries.begin(), - end = this->SourceEntries.end(); - it != end; ++it) { - values.push_back((*it)->ge->GetInput()); + for (TargetPropertyEntry* se : this->SourceEntries) { + values.push_back(se->ge->GetInput()); } static std::string value; value.clear(); - value = cmJoin(values, ""); + value = cmJoin(values, ";"); return value.c_str(); } @@ -299,9 +297,8 @@ std::string cmGeneratorTarget::GetOutputName( props.push_back("OUTPUT_NAME"); std::string outName; - for (std::vector<std::string>::const_iterator it = props.begin(); - it != props.end(); ++it) { - if (const char* outNameProp = this->GetProperty(*it)) { + for (std::string const& p : props) { + if (const char* outNameProp = this->GetProperty(p)) { outName = outNameProp; break; } @@ -313,7 +310,7 @@ std::string cmGeneratorTarget::GetOutputName( // Now evaluate genex and update the previously-prepared map entry. cmGeneratorExpression ge; - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(outName); + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(outName); i->second = cge->Evaluate(this->LocalGenerator, config); } else if (i->second.empty()) { // An empty map entry indicates we have been called recursively @@ -337,9 +334,9 @@ void cmGeneratorTarget::AddSourceCommon(const std::string& src) { cmListFileBacktrace lfbt = this->Makefile->GetBacktrace(); cmGeneratorExpression ge(lfbt); - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(src); + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(src); cge->SetEvaluateForBuildsystem(true); - this->SourceEntries.push_back(new TargetPropertyEntry(cge)); + this->SourceEntries.push_back(new TargetPropertyEntry(std::move(cge))); this->ClearSourcesCache(); } @@ -363,13 +360,14 @@ void cmGeneratorTarget::AddIncludeDirectory(const std::string& src, this->Target->InsertInclude(src, this->Makefile->GetBacktrace(), before); cmListFileBacktrace lfbt = this->Makefile->GetBacktrace(); cmGeneratorExpression ge(lfbt); - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(src); + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(src); cge->SetEvaluateForBuildsystem(true); // Insert before begin/end std::vector<TargetPropertyEntry*>::iterator pos = before ? this->IncludeDirectoriesEntries.begin() : this->IncludeDirectoriesEntries.end(); - this->IncludeDirectoriesEntries.insert(pos, new TargetPropertyEntry(cge)); + this->IncludeDirectoriesEntries.insert( + pos, new TargetPropertyEntry(std::move(cge))); } std::vector<cmSourceFile*> const* cmGeneratorTarget::GetSourceDepends( @@ -414,10 +412,9 @@ static void handleSystemIncludesDep( #define IMPLEMENT_VISIT(KIND) \ { \ KindedSources const& kinded = this->GetKindedSources(config); \ - for (std::vector<SourceAndKind>::const_iterator \ - si = kinded.Sources.begin(); si != kinded.Sources.end(); ++si) { \ - if (si->Kind == KIND) { \ - data.push_back(si->Source); \ + for (SourceAndKind const& s : kinded.Sources) { \ + if (s.Kind == KIND) { \ + data.push_back(s.Source); \ } \ } \ } @@ -432,9 +429,8 @@ void cmGeneratorTarget::GetObjectSources( return; } - for (std::vector<cmSourceFile const*>::const_iterator it = data.begin(); - it != data.end(); ++it) { - this->Objects[*it]; + for (cmSourceFile const* it : data) { + this->Objects[it]; } this->LocalGenerator->ComputeObjectFilenames(this->Objects, this); @@ -451,10 +447,9 @@ void cmGeneratorTarget::ComputeObjectMapping() if (configs.empty()) { configs.push_back(""); } - for (std::vector<std::string>::const_iterator ci = configs.begin(); - ci != configs.end(); ++ci) { + for (std::string const& c : configs) { std::vector<cmSourceFile const*> sourceFiles; - this->GetObjectSources(sourceFiles, *ci); + this->GetObjectSources(sourceFiles, c); } } @@ -655,11 +650,10 @@ std::set<cmLinkItem> const& cmGeneratorTarget::GetUtilityItems() const if (!this->UtilityItemsDone) { this->UtilityItemsDone = true; std::set<std::string> const& utilities = this->GetUtilities(); - for (std::set<std::string>::const_iterator i = utilities.begin(); - i != utilities.end(); ++i) { + for (std::string const& i : utilities) { cmGeneratorTarget* gt = - this->LocalGenerator->FindGeneratorTargetToUse(*i); - this->UtilityItems.insert(cmLinkItem(*i, gt)); + this->LocalGenerator->FindGeneratorTargetToUse(i); + this->UtilityItems.insert(cmLinkItem(i, gt)); } } return this->UtilityItems; @@ -749,7 +743,7 @@ bool cmGeneratorTarget::IsSystemIncludeDirectory( config_upper = cmSystemTools::UpperCase(config); } - typedef std::map<std::string, std::vector<std::string> > IncludeCacheType; + typedef std::map<std::string, std::vector<std::string>> IncludeCacheType; IncludeCacheType::const_iterator iter = this->SystemIncludesCache.find(config_upper); @@ -760,23 +754,18 @@ bool cmGeneratorTarget::IsSystemIncludeDirectory( bool excludeImported = this->GetPropertyAsBool("NO_SYSTEM_FROM_IMPORTED"); std::vector<std::string> result; - for (std::set<std::string>::const_iterator it = - this->Target->GetSystemIncludeDirectories().begin(); - it != this->Target->GetSystemIncludeDirectories().end(); ++it) { + for (std::string const& it : this->Target->GetSystemIncludeDirectories()) { cmGeneratorExpression ge; cmSystemTools::ExpandListArgument( - ge.Parse(*it)->Evaluate(this->LocalGenerator, config, false, this, - &dagChecker), + ge.Parse(it)->Evaluate(this->LocalGenerator, config, false, this, + &dagChecker), result); } std::vector<cmGeneratorTarget const*> const& deps = this->GetLinkImplementationClosure(config); - for (std::vector<cmGeneratorTarget const *>::const_iterator - li = deps.begin(), - le = deps.end(); - li != le; ++li) { - handleSystemIncludesDep(this->LocalGenerator, *li, config, this, + for (cmGeneratorTarget const* dep : deps) { + handleSystemIncludesDep(this->LocalGenerator, dep, config, this, &dagChecker, result, excludeImported); } @@ -804,17 +793,14 @@ static void AddInterfaceEntries( { if (cmLinkImplementationLibraries const* impl = thisTarget->GetLinkImplementationLibraries(config)) { - for (std::vector<cmLinkImplItem>::const_iterator - it = impl->Libraries.begin(), - end = impl->Libraries.end(); - it != end; ++it) { - if (it->Target) { - std::string genex = "$<TARGET_PROPERTY:" + *it + "," + prop + ">"; - cmGeneratorExpression ge(it->Backtrace); - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(genex); + for (cmLinkImplItem const& lib : impl->Libraries) { + if (lib.Target) { + std::string genex = "$<TARGET_PROPERTY:" + lib + "," + prop + ">"; + cmGeneratorExpression ge(lib.Backtrace); + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(genex); cge->SetEvaluateForBuildsystem(true); entries.push_back( - new cmGeneratorTarget::TargetPropertyEntry(cge, *it)); + new cmGeneratorTarget::TargetPropertyEntry(std::move(cge), lib)); } } } @@ -831,25 +817,20 @@ static bool processSources( bool contextDependent = false; - for (std::vector<cmGeneratorTarget::TargetPropertyEntry *>::const_iterator - it = entries.begin(), - end = entries.end(); - it != end; ++it) { - cmLinkImplItem const& item = (*it)->LinkImplItem; + for (cmGeneratorTarget::TargetPropertyEntry* entry : entries) { + cmLinkImplItem const& item = entry->LinkImplItem; std::string const& targetName = item; std::vector<std::string> entrySources; cmSystemTools::ExpandListArgument( - (*it)->ge->Evaluate(tgt->GetLocalGenerator(), config, false, tgt, tgt, + entry->ge->Evaluate(tgt->GetLocalGenerator(), config, false, tgt, tgt, dagChecker), entrySources); - if ((*it)->ge->GetHadContextSensitiveCondition()) { + if (entry->ge->GetHadContextSensitiveCondition()) { contextDependent = true; } - for (std::vector<std::string>::iterator i = entrySources.begin(); - i != entrySources.end(); ++i) { - std::string& src = *i; + for (std::string& src : entrySources) { cmSourceFile* sf = mf->GetOrCreateSource(src); std::string e; std::string fullPath = sf->GetFullPath(&e); @@ -880,10 +861,7 @@ static bool processSources( src = fullPath; } std::string usedSources; - for (std::vector<std::string>::iterator li = entrySources.begin(); - li != entrySources.end(); ++li) { - std::string src = *li; - + for (std::string const& src : entrySources) { if (uniqueSrcs.insert(src).second) { srcs.push_back(src); if (debugSources) { @@ -895,7 +873,7 @@ static bool processSources( tgt->GetLocalGenerator()->GetCMakeInstance()->IssueMessage( cmake::LOG, std::string("Used sources for target ") + tgt->GetName() + ":\n" + usedSources, - (*it)->ge->GetBacktrace()); + entry->ge->GetBacktrace()); } } return contextDependent; @@ -914,19 +892,15 @@ void cmGeneratorTarget::GetSourceFiles(std::vector<std::string>& files, // behavior of CMP0024 and CMP0026 only. cmStringRange sourceEntries = this->Target->GetSourceEntries(); - for (cmStringRange::const_iterator i = sourceEntries.begin(); - i != sourceEntries.end(); ++i) { - std::string const& entry = *i; - + for (std::string const& entry : sourceEntries) { std::vector<std::string> items; cmSystemTools::ExpandListArgument(entry, items); - for (std::vector<std::string>::const_iterator li = items.begin(); - li != items.end(); ++li) { - if (cmHasLiteralPrefix(*li, "$<TARGET_OBJECTS:") && - (*li)[li->size() - 1] == '>') { + for (std::string const& item : items) { + if (cmHasLiteralPrefix(item, "$<TARGET_OBJECTS:") && + item[item.size() - 1] == '>') { continue; } - files.push_back(*li); + files.push_back(item); } } return; @@ -987,9 +961,8 @@ void cmGeneratorTarget::GetSourceFiles(std::vector<cmSourceFile*>& files, std::vector<std::string> srcs; this->GetSourceFiles(srcs, config); std::set<cmSourceFile*> emitted; - for (std::vector<std::string>::const_iterator i = srcs.begin(); - i != srcs.end(); ++i) { - cmSourceFile* sf = this->Makefile->GetOrCreateSource(*i); + for (std::string const& s : srcs) { + cmSourceFile* sf = this->Makefile->GetOrCreateSource(s); if (emitted.insert(sf).second) { files.push_back(sf); } @@ -999,9 +972,8 @@ void cmGeneratorTarget::GetSourceFiles(std::vector<cmSourceFile*>& files, KindedSources const& kinded = this->GetKindedSources(config); files.reserve(kinded.Sources.size()); - for (std::vector<SourceAndKind>::const_iterator si = kinded.Sources.begin(); - si != kinded.Sources.end(); ++si) { - files.push_back(si->Source); + for (SourceAndKind const& si : kinded.Sources) { + files.push_back(si.Source); } } @@ -1010,10 +982,9 @@ void cmGeneratorTarget::GetSourceFilesWithoutObjectLibraries( { KindedSources const& kinded = this->GetKindedSources(config); files.reserve(kinded.Sources.size()); - for (std::vector<SourceAndKind>::const_iterator si = kinded.Sources.begin(); - si != kinded.Sources.end(); ++si) { - if (si->Source->GetObjectLibrary().empty()) { - files.push_back(si->Source); + for (SourceAndKind const& si : kinded.Sources) { + if (si.Source->GetObjectLibrary().empty()) { + files.push_back(si.Source); } } } @@ -1062,10 +1033,9 @@ void cmGeneratorTarget::ComputeKindedSources(KindedSources& files, std::vector<cmSourceFile*> badObjLib; std::set<cmSourceFile*> emitted; - for (std::vector<std::string>::const_iterator i = srcs.begin(); - i != srcs.end(); ++i) { + for (std::string const& s : srcs) { // Create each source at most once. - cmSourceFile* sf = this->Makefile->GetOrCreateSource(*i); + cmSourceFile* sf = this->Makefile->GetOrCreateSource(s); if (!emitted.insert(sf).second) { continue; } @@ -1138,9 +1108,8 @@ void cmGeneratorTarget::ComputeKindedSources(KindedSources& files, if (!badObjLib.empty()) { std::ostringstream e; e << "OBJECT library \"" << this->GetName() << "\" contains:\n"; - for (std::vector<cmSourceFile*>::const_iterator i = badObjLib.begin(); - i != badObjLib.end(); ++i) { - e << " " << (*i)->GetLocation().GetName() << "\n"; + for (cmSourceFile* i : badObjLib) { + e << " " << i->GetLocation().GetName() << "\n"; } e << "but may contain only sources that compile, header files, and " "other files that would not affect linking of a normal library."; @@ -1167,18 +1136,16 @@ void cmGeneratorTarget::ComputeAllConfigSources() const for (size_t ci = 0; ci < configs.size(); ++ci) { KindedSources const& sources = this->GetKindedSources(configs[ci]); - for (std::vector<cmGeneratorTarget::SourceAndKind>::const_iterator si = - sources.Sources.begin(); - si != sources.Sources.end(); ++si) { + for (SourceAndKind const& src : sources.Sources) { std::map<cmSourceFile const*, size_t>::iterator mi = - index.find(si->Source); + index.find(src.Source); if (mi == index.end()) { AllConfigSource acs; - acs.Source = si->Source; - acs.Kind = si->Kind; + acs.Source = src.Source; + acs.Kind = src.Kind; this->AllConfigSources.push_back(acs); std::map<cmSourceFile const*, size_t>::value_type entry( - si->Source, this->AllConfigSources.size() - 1); + src.Source, this->AllConfigSources.size() - 1); mi = index.insert(entry).first; } this->AllConfigSources[mi->second].Configs.push_back(ci); @@ -1781,15 +1748,12 @@ public: return; } - for (std::vector<std::string>::const_iterator li = - iface->Languages.begin(); - li != iface->Languages.end(); ++li) { - this->Languages.insert(*li); + for (std::string const& language : iface->Languages) { + this->Languages.insert(language); } - for (std::vector<cmLinkItem>::const_iterator li = iface->Libraries.begin(); - li != iface->Libraries.end(); ++li) { - this->Visit(*li); + for (cmLinkItem const& lib : iface->Libraries) { + this->Visit(lib); } } @@ -1850,9 +1814,8 @@ public: e << "Target " << this->Target->GetName() << " contains multiple languages with the highest linker preference" << " (" << this->Preference << "):\n"; - for (std::set<std::string>::const_iterator li = this->Preferred.begin(); - li != this->Preferred.end(); ++li) { - e << " " << *li << "\n"; + for (std::string const& li : this->Preferred) { + e << " " << li << "\n"; } e << "Set the LINKER_LANGUAGE property for this target."; cmake* cm = this->Target->GetLocalGenerator()->GetCMakeInstance(); @@ -1870,23 +1833,19 @@ void cmGeneratorTarget::ComputeLinkClosure(const std::string& config, std::unordered_set<std::string> languages; cmLinkImplementation const* impl = this->GetLinkImplementation(config); assert(impl); - for (std::vector<std::string>::const_iterator li = impl->Languages.begin(); - li != impl->Languages.end(); ++li) { - languages.insert(*li); + for (std::string const& li : impl->Languages) { + languages.insert(li); } // Add interface languages from linked targets. cmTargetCollectLinkLanguages cll(this, config, languages, this); - for (std::vector<cmLinkImplItem>::const_iterator li = - impl->Libraries.begin(); - li != impl->Libraries.end(); ++li) { - cll.Visit(*li); + for (cmLinkImplItem const& lib : impl->Libraries) { + cll.Visit(lib); } // Store the transitive closure of languages. - for (std::unordered_set<std::string>::const_iterator li = languages.begin(); - li != languages.end(); ++li) { - lc.Languages.push_back(*li); + for (std::string const& lang : languages) { + lc.Languages.push_back(lang); } // Choose the language whose linker should be used. @@ -1899,19 +1858,16 @@ void cmGeneratorTarget::ComputeLinkClosure(const std::string& config, cmTargetSelectLinker tsl(this); // First select from the languages compiled directly in this target. - for (std::vector<std::string>::const_iterator li = impl->Languages.begin(); - li != impl->Languages.end(); ++li) { - tsl.Consider(li->c_str()); + for (std::string const& l : impl->Languages) { + tsl.Consider(l.c_str()); } // Now consider languages that propagate from linked targets. - for (std::unordered_set<std::string>::const_iterator sit = - languages.begin(); - sit != languages.end(); ++sit) { + for (std::string const& lang : languages) { std::string propagates = - "CMAKE_" + *sit + "_LINKER_PREFERENCE_PROPAGATES"; + "CMAKE_" + lang + "_LINKER_PREFERENCE_PROPAGATES"; if (this->Makefile->IsOn(propagates)) { - tsl.Consider(sit->c_str()); + tsl.Consider(lang.c_str()); } } @@ -2083,10 +2039,8 @@ void processILibs(const std::string& config, tgts.push_back(item.Target); if (cmLinkInterfaceLibraries const* iface = item.Target->GetLinkInterfaceLibraries(config, headTarget, true)) { - for (std::vector<cmLinkItem>::const_iterator it = - iface->Libraries.begin(); - it != iface->Libraries.end(); ++it) { - processILibs(config, headTarget, *it, gg, tgts, emitted); + for (cmLinkItem const& lib : iface->Libraries) { + processILibs(config, headTarget, lib, gg, tgts, emitted); } } } @@ -2104,10 +2058,8 @@ cmGeneratorTarget::GetLinkImplementationClosure( cmLinkImplementationLibraries const* impl = this->GetLinkImplementationLibraries(config); - for (std::vector<cmLinkImplItem>::const_iterator it = - impl->Libraries.begin(); - it != impl->Libraries.end(); ++it) { - processILibs(config, this, *it, + for (cmLinkImplItem const& lib : impl->Libraries) { + processILibs(config, this, lib, this->LocalGenerator->GetGlobalGenerator(), tgts, emitted); } } @@ -2161,13 +2113,10 @@ cmTargetTraceDependencies::cmTargetTraceDependencies(cmGeneratorTarget* target) configs.push_back(""); } std::set<cmSourceFile*> emitted; - for (std::vector<std::string>::const_iterator ci = configs.begin(); - ci != configs.end(); ++ci) { + for (std::string const& c : configs) { std::vector<cmSourceFile*> sources; - this->GeneratorTarget->GetSourceFiles(sources, *ci); - for (std::vector<cmSourceFile*>::const_iterator si = sources.begin(); - si != sources.end(); ++si) { - cmSourceFile* sf = *si; + this->GeneratorTarget->GetSourceFiles(sources, c); + for (cmSourceFile* sf : sources) { const std::set<cmGeneratorTarget const*> tgts = this->GlobalGenerator->GetFilenameTargetDepends(sf); if (tgts.find(this->GeneratorTarget) != tgts.end()) { @@ -2206,10 +2155,9 @@ void cmTargetTraceDependencies::Trace() if (const char* additionalDeps = sf->GetProperty("OBJECT_DEPENDS")) { std::vector<std::string> objDeps; cmSystemTools::ExpandListArgument(additionalDeps, objDeps); - for (std::vector<std::string>::iterator odi = objDeps.begin(); - odi != objDeps.end(); ++odi) { - if (cmSystemTools::FileIsFullPath(*odi)) { - *odi = cmSystemTools::CollapseFullPath(*odi); + for (std::string& objDep : objDeps) { + if (cmSystemTools::FileIsFullPath(objDep)) { + objDep = cmSystemTools::CollapseFullPath(objDep); } } this->FollowNames(objDeps); @@ -2262,9 +2210,8 @@ void cmTargetTraceDependencies::FollowName(std::string const& name) void cmTargetTraceDependencies::FollowNames( std::vector<std::string> const& names) { - for (std::vector<std::string>::const_iterator i = names.begin(); - i != names.end(); ++i) { - this->FollowName(*i); + for (std::string const& name : names) { + this->FollowName(name); } } @@ -2324,9 +2271,8 @@ void cmTargetTraceDependencies::CheckCustomCommand(cmCustomCommand const& cc) // Add target-level dependencies referenced by generator expressions. std::set<cmGeneratorTarget*> targets; - for (cmCustomCommandLines::const_iterator cit = cc.GetCommandLines().begin(); - cit != cc.GetCommandLines().end(); ++cit) { - std::string const& command = *cit->begin(); + for (cmCustomCommandLine const& cCmdLine : cc.GetCommandLines()) { + std::string const& command = *cCmdLine.begin(); // Check for a target with this name. if (cmGeneratorTarget* t = this->LocalGenerator->FindGeneratorTargetToUse(command)) { @@ -2340,18 +2286,16 @@ void cmTargetTraceDependencies::CheckCustomCommand(cmCustomCommand const& cc) } // Check for target references in generator expressions. - for (cmCustomCommandLine::const_iterator cli = cit->begin(); - cli != cit->end(); ++cli) { - const CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(*cli); + for (std::string const& cl : cCmdLine) { + const std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(cl); cge->Evaluate(this->GeneratorTarget->GetLocalGenerator(), "", true); std::set<cmGeneratorTarget*> geTargets = cge->GetTargets(); targets.insert(geTargets.begin(), geTargets.end()); } } - for (std::set<cmGeneratorTarget*>::iterator ti = targets.begin(); - ti != targets.end(); ++ti) { - this->GeneratorTarget->Target->AddUtility((*ti)->GetName()); + for (cmGeneratorTarget* target : targets) { + this->GeneratorTarget->Target->AddUtility(target->GetName()); } // Queue the custom command dependencies. @@ -2361,9 +2305,8 @@ void cmTargetTraceDependencies::CheckCustomCommand(cmCustomCommand const& cc) if (configs.empty()) { configs.push_back(""); } - for (std::vector<std::string>::const_iterator ci = configs.begin(); - ci != configs.end(); ++ci) { - this->FollowCommandDepends(cc, *ci, emitted); + for (std::string const& conf : configs) { + this->FollowCommandDepends(cc, conf, emitted); } } @@ -2376,9 +2319,7 @@ void cmTargetTraceDependencies::FollowCommandDepends( const std::vector<std::string>& depends = ccg.GetDepends(); - for (std::vector<std::string>::const_iterator di = depends.begin(); - di != depends.end(); ++di) { - std::string const& dep = *di; + for (std::string const& dep : depends) { if (emitted.insert(dep).second) { if (!this->IsUtility(dep)) { // The dependency does not name a target and may be a file we @@ -2392,9 +2333,8 @@ void cmTargetTraceDependencies::FollowCommandDepends( void cmTargetTraceDependencies::CheckCustomCommands( const std::vector<cmCustomCommand>& commands) { - for (std::vector<cmCustomCommand>::const_iterator cli = commands.begin(); - cli != commands.end(); ++cli) { - this->CheckCustomCommand(*cli); + for (cmCustomCommand const& command : commands) { + this->CheckCustomCommand(command); } } @@ -2482,24 +2422,20 @@ static void processIncludeDirectories( cmGeneratorExpressionDAGChecker* dagChecker, const std::string& config, bool debugIncludes, const std::string& language) { - for (std::vector<cmGeneratorTarget::TargetPropertyEntry *>::const_iterator - it = entries.begin(), - end = entries.end(); - it != end; ++it) { - cmLinkImplItem const& item = (*it)->LinkImplItem; + for (cmGeneratorTarget::TargetPropertyEntry* entry : entries) { + cmLinkImplItem const& item = entry->LinkImplItem; std::string const& targetName = item; bool const fromImported = item.Target && item.Target->IsImported(); bool const checkCMP0027 = item.FromGenex; std::vector<std::string> entryIncludes; cmSystemTools::ExpandListArgument( - (*it)->ge->Evaluate(tgt->GetLocalGenerator(), config, false, tgt, + entry->ge->Evaluate(tgt->GetLocalGenerator(), config, false, tgt, dagChecker, language), entryIncludes); std::string usedIncludes; - for (std::vector<std::string>::iterator li = entryIncludes.begin(); - li != entryIncludes.end(); ++li) { - if (fromImported && !cmSystemTools::FileExists(li->c_str())) { + for (std::string& entryInclude : entryIncludes) { + if (fromImported && !cmSystemTools::FileExists(entryInclude.c_str())) { std::ostringstream e; cmake::MessageType messageType = cmake::FATAL_ERROR; if (checkCMP0027) { @@ -2518,7 +2454,7 @@ static void processIncludeDirectories( } /* clang-format off */ e << "Imported target \"" << targetName << "\" includes " - "non-existent path\n \"" << *li << "\"\nin its " + "non-existent path\n \"" << entryInclude << "\"\nin its " "INTERFACE_INCLUDE_DIRECTORIES. Possible reasons include:\n" "* The path was deleted, renamed, or moved to another " "location.\n" @@ -2531,7 +2467,7 @@ static void processIncludeDirectories( return; } - if (!cmSystemTools::FileIsFullPath(li->c_str())) { + if (!cmSystemTools::FileIsFullPath(entryInclude.c_str())) { std::ostringstream e; bool noMessage = false; cmake::MessageType messageType = cmake::FATAL_ERROR; @@ -2539,7 +2475,7 @@ static void processIncludeDirectories( /* clang-format off */ e << "Target \"" << targetName << "\" contains relative " "path in its INTERFACE_INCLUDE_DIRECTORIES:\n" - " \"" << *li << "\""; + " \"" << entryInclude << "\""; /* clang-format on */ } else { switch (tgt->GetPolicyStatusCMP0021()) { @@ -2557,7 +2493,7 @@ static void processIncludeDirectories( } e << "Found relative path while evaluating include directories of " "\"" - << tgt->GetName() << "\":\n \"" << *li << "\"\n"; + << tgt->GetName() << "\":\n \"" << entryInclude << "\"\n"; } if (!noMessage) { tgt->GetLocalGenerator()->IssueMessage(messageType, e.str()); @@ -2567,10 +2503,10 @@ static void processIncludeDirectories( } } - if (!cmSystemTools::IsOff(li->c_str())) { - cmSystemTools::ConvertToUnixSlashes(*li); + if (!cmSystemTools::IsOff(entryInclude.c_str())) { + cmSystemTools::ConvertToUnixSlashes(entryInclude); } - std::string inc = *li; + std::string inc = entryInclude; if (uniqueIncludes.insert(inc).second) { includes.push_back(inc); @@ -2583,7 +2519,7 @@ static void processIncludeDirectories( tgt->GetLocalGenerator()->GetCMakeInstance()->IssueMessage( cmake::LOG, std::string("Used includes for target ") + tgt->GetName() + ":\n" + usedIncludes, - (*it)->ge->GetBacktrace()); + entry->ge->GetBacktrace()); } } } @@ -2624,10 +2560,8 @@ std::vector<std::string> cmGeneratorTarget::GetIncludeDirectories( if (this->Makefile->IsOn("APPLE")) { cmLinkImplementationLibraries const* impl = this->GetLinkImplementationLibraries(config); - for (std::vector<cmLinkImplItem>::const_iterator it = - impl->Libraries.begin(); - it != impl->Libraries.end(); ++it) { - std::string libDir = cmSystemTools::CollapseFullPath(*it); + for (cmLinkImplItem const& lib : impl->Libraries) { + std::string libDir = cmSystemTools::CollapseFullPath(lib); static cmsys::RegularExpression frameworkCheck( "(.*\\.framework)(/Versions/[^/]+)?/[^/]+$"); @@ -2638,10 +2572,10 @@ std::vector<std::string> cmGeneratorTarget::GetIncludeDirectories( libDir = frameworkCheck.match(1); cmGeneratorExpression ge; - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(libDir.c_str()); linkInterfaceIncludeDirectoriesEntries.push_back( - new cmGeneratorTarget::TargetPropertyEntry(cge)); + new cmGeneratorTarget::TargetPropertyEntry(std::move(cge))); } } @@ -2662,20 +2596,14 @@ static void processCompileOptionsInternal( cmGeneratorExpressionDAGChecker* dagChecker, const std::string& config, bool debugOptions, const char* logName, std::string const& language) { - for (std::vector<cmGeneratorTarget::TargetPropertyEntry *>::const_iterator - it = entries.begin(), - end = entries.end(); - it != end; ++it) { + for (cmGeneratorTarget::TargetPropertyEntry* entry : entries) { std::vector<std::string> entryOptions; cmSystemTools::ExpandListArgument( - (*it)->ge->Evaluate(tgt->GetLocalGenerator(), config, false, tgt, + entry->ge->Evaluate(tgt->GetLocalGenerator(), config, false, tgt, dagChecker, language), entryOptions); std::string usedOptions; - for (std::vector<std::string>::iterator li = entryOptions.begin(); - li != entryOptions.end(); ++li) { - std::string const& opt = *li; - + for (std::string const& opt : entryOptions) { if (uniqueOptions.insert(opt).second) { options.push_back(opt); if (debugOptions) { @@ -2687,7 +2615,7 @@ static void processCompileOptionsInternal( tgt->GetLocalGenerator()->GetCMakeInstance()->IssueMessage( cmake::LOG, std::string("Used compile ") + logName + std::string(" for target ") + tgt->GetName() + ":\n" + usedOptions, - (*it)->ge->GetBacktrace()); + entry->ge->GetBacktrace()); } } } @@ -2855,10 +2783,10 @@ void cmGeneratorTarget::GetCompileDefinitions( } case cmPolicies::OLD: { cmGeneratorExpression ge; - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(configProp); linkInterfaceCompileDefinitionsEntries.push_back( - new cmGeneratorTarget::TargetPropertyEntry(cge)); + new cmGeneratorTarget::TargetPropertyEntry(std::move(cge))); } break; case cmPolicies::NEW: case cmPolicies::REQUIRED_ALWAYS: @@ -2940,9 +2868,8 @@ bool cmGeneratorTarget::ComputeCompileFeatures(std::string const& config) const { std::vector<std::string> features; this->GetCompileFeatures(features, config); - for (std::vector<std::string>::const_iterator it = features.begin(); - it != features.end(); ++it) { - if (!this->Makefile->AddRequiredTargetFeature(this->Target, *it)) { + for (std::string const& f : features) { + if (!this->Makefile->AddRequiredTargetFeature(this->Target, f)) { return false; } } @@ -3098,7 +3025,7 @@ void cmGeneratorTarget::GetLibraryNames(std::string& name, std::string& soName, impName = this->GetFullNameInternal(config, cmStateEnums::ImportLibraryArtifact); } else { - impName = ""; + impName.clear(); } // The program database file name. @@ -3201,9 +3128,9 @@ void cmGeneratorTarget::GetFullNameInternal( this->GetType() != cmStateEnums::SHARED_LIBRARY && this->GetType() != cmStateEnums::MODULE_LIBRARY && this->GetType() != cmStateEnums::EXECUTABLE) { - outPrefix = ""; + outPrefix.clear(); outBase = this->GetName(); - outSuffix = ""; + outSuffix.clear(); return; } @@ -3214,9 +3141,9 @@ void cmGeneratorTarget::GetFullNameInternal( // does not support import libraries. if (isImportedLibraryArtifact && !this->Makefile->GetDefinition("CMAKE_IMPORT_LIBRARY_SUFFIX")) { - outPrefix = ""; - outBase = ""; - outSuffix = ""; + outPrefix.clear(); + outBase.clear(); + outSuffix.clear(); return; } @@ -3334,9 +3261,8 @@ std::string cmGeneratorTarget::GetPDBName(const std::string& config) const // PDB_NAME props.push_back("PDB_NAME"); - for (std::vector<std::string>::const_iterator i = props.begin(); - i != props.end(); ++i) { - if (const char* outName = this->GetProperty(*i)) { + for (std::string const& p : props) { + if (const char* outName = this->GetProperty(p)) { base = outName; break; } @@ -3364,20 +3290,16 @@ void cmGeneratorTarget::GetTargetObjectNames( this->GetObjectSources(objectSources, config); std::map<cmSourceFile const*, std::string> mapping; - for (std::vector<cmSourceFile const*>::const_iterator it = - objectSources.begin(); - it != objectSources.end(); ++it) { - mapping[*it]; + for (cmSourceFile const* sf : objectSources) { + mapping[sf]; } this->LocalGenerator->ComputeObjectFilenames(mapping, this); - for (std::vector<cmSourceFile const*>::const_iterator it = - objectSources.begin(); - it != objectSources.end(); ++it) { + for (cmSourceFile const* src : objectSources) { // Find the object file name corresponding to this source file. std::map<cmSourceFile const*, std::string>::const_iterator map_it = - mapping.find(*it); + mapping.find(src); // It must exist because we populated the mapping just above. assert(!map_it->second.empty()); objects.push_back(map_it->second); @@ -3440,9 +3362,8 @@ void cmGeneratorTarget::ConstructSourceFileFlags() const if (const char* files = this->GetProperty("PUBLIC_HEADER")) { std::vector<std::string> relFiles; cmSystemTools::ExpandListArgument(files, relFiles); - for (std::vector<std::string>::iterator it = relFiles.begin(); - it != relFiles.end(); ++it) { - if (cmSourceFile* sf = this->Makefile->GetSource(*it)) { + for (std::string const& relFile : relFiles) { + if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) { SourceFileFlags& flags = this->SourceFlagsMap[sf]; flags.MacFolder = "Headers"; flags.Type = cmGeneratorTarget::SourceFileTypePublicHeader; @@ -3455,9 +3376,8 @@ void cmGeneratorTarget::ConstructSourceFileFlags() const if (const char* files = this->GetProperty("PRIVATE_HEADER")) { std::vector<std::string> relFiles; cmSystemTools::ExpandListArgument(files, relFiles); - for (std::vector<std::string>::iterator it = relFiles.begin(); - it != relFiles.end(); ++it) { - if (cmSourceFile* sf = this->Makefile->GetSource(*it)) { + for (std::string const& relFile : relFiles) { + if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) { SourceFileFlags& flags = this->SourceFlagsMap[sf]; flags.MacFolder = "PrivateHeaders"; flags.Type = cmGeneratorTarget::SourceFileTypePrivateHeader; @@ -3469,9 +3389,8 @@ void cmGeneratorTarget::ConstructSourceFileFlags() const if (const char* files = this->GetProperty("RESOURCE")) { std::vector<std::string> relFiles; cmSystemTools::ExpandListArgument(files, relFiles); - for (std::vector<std::string>::iterator it = relFiles.begin(); - it != relFiles.end(); ++it) { - if (cmSourceFile* sf = this->Makefile->GetSource(*it)) { + for (std::string const& relFile : relFiles) { + if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) { SourceFileFlags& flags = this->SourceFlagsMap[sf]; flags.MacFolder = ""; if (!this->GlobalGenerator->ShouldStripResourcePath(this->Makefile)) { @@ -3494,11 +3413,9 @@ cmGeneratorTarget::GetCompatibleInterfaces(std::string const& config) const compat.PropsString.insert("AUTOUIC_OPTIONS"); std::vector<cmGeneratorTarget const*> const& deps = this->GetLinkImplementationClosure(config); - for (std::vector<cmGeneratorTarget const*>::const_iterator li = - deps.begin(); - li != deps.end(); ++li) { + for (cmGeneratorTarget const* li : deps) { #define CM_READ_COMPATIBLE_INTERFACE(X, x) \ - if (const char* prop = (*li)->GetProperty("COMPATIBLE_INTERFACE_" #X)) { \ + if (const char* prop = li->GetProperty("COMPATIBLE_INTERFACE_" #X)) { \ std::vector<std::string> props; \ cmSystemTools::ExpandListArgument(prop, props); \ compat.Props##x.insert(props.begin(), props.end()); \ @@ -3618,13 +3535,12 @@ void checkPropertyConsistency(cmGeneratorTarget const* depender, std::string pdir = cmSystemTools::GetCMakeRoot(); pdir += "/Help/prop_tgt/"; - for (std::vector<std::string>::iterator pi = props.begin(); - pi != props.end(); ++pi) { - std::string pname = cmSystemTools::HelpFileName(*pi); + for (std::string const& p : props) { + std::string pname = cmSystemTools::HelpFileName(p); std::string pfile = pdir + pname + ".rst"; if (cmSystemTools::FileExists(pfile.c_str(), true)) { std::ostringstream e; - e << "Target \"" << dependee->GetName() << "\" has property \"" << *pi + e << "Target \"" << dependee->GetName() << "\" has property \"" << p << "\" listed in its " << propName << " property. " "This is not allowed. Only user-defined properties may appear " @@ -3633,8 +3549,8 @@ void checkPropertyConsistency(cmGeneratorTarget const* depender, depender->GetLocalGenerator()->IssueMessage(cmake::FATAL_ERROR, e.str()); return; } - if (emitted.insert(*pi).second) { - getLinkInterfaceDependentProperty<PropertyType>(depender, *pi, config, t, + if (emitted.insert(p).second) { + getLinkInterfaceDependentProperty<PropertyType>(depender, p, config, t, nullptr); if (cmSystemTools::GetErrorOccuredFlag()) { return; @@ -3706,30 +3622,29 @@ void cmGeneratorTarget::CheckPropertyCompatibility( std::set<std::string> emittedMaxNumbers; static std::string strNumMax = "COMPATIBLE_INTERFACE_NUMBER_MAX"; - for (cmComputeLinkInformation::ItemVector::const_iterator li = deps.begin(); - li != deps.end(); ++li) { - if (!li->Target) { + for (auto const& dep : deps) { + if (!dep.Target) { continue; } - checkPropertyConsistency<bool>(this, li->Target, strBool, emittedBools, + checkPropertyConsistency<bool>(this, dep.Target, strBool, emittedBools, config, BoolType, nullptr); if (cmSystemTools::GetErrorOccuredFlag()) { return; } - checkPropertyConsistency<const char*>(this, li->Target, strString, + checkPropertyConsistency<const char*>(this, dep.Target, strString, emittedStrings, config, StringType, nullptr); if (cmSystemTools::GetErrorOccuredFlag()) { return; } - checkPropertyConsistency<const char*>(this, li->Target, strNumMin, + checkPropertyConsistency<const char*>(this, dep.Target, strNumMin, emittedMinNumbers, config, NumberMinType, nullptr); if (cmSystemTools::GetErrorOccuredFlag()) { return; } - checkPropertyConsistency<const char*>(this, li->Target, strNumMax, + checkPropertyConsistency<const char*>(this, dep.Target, strNumMax, emittedMaxNumbers, config, NumberMaxType, nullptr); if (cmSystemTools::GetErrorOccuredFlag()) { @@ -3961,16 +3876,13 @@ PropertyType checkInterfacePropertyCompatibility(cmGeneratorTarget const* tgt, } std::string interfaceProperty = "INTERFACE_" + p; - for (std::vector<cmGeneratorTarget const*>::const_iterator li = deps.begin(); - li != deps.end(); ++li) { + for (cmGeneratorTarget const* theTarget : deps) { // An error should be reported if one dependency // has INTERFACE_POSITION_INDEPENDENT_CODE ON and the other // has INTERFACE_POSITION_INDEPENDENT_CODE OFF, or if the // target itself has a POSITION_INDEPENDENT_CODE which disagrees // with a dependency. - cmGeneratorTarget const* theTarget = *li; - std::vector<std::string> propKeys = theTarget->GetPropertyKeys(); const bool ifaceIsSet = std::find(propKeys.begin(), propKeys.end(), @@ -4240,9 +4152,8 @@ std::vector<std::string> cmGeneratorTarget::GetPropertyKeys() const cmPropertyMap const& propsObject = this->Target->GetProperties(); std::vector<std::string> props; props.reserve(propsObject.size()); - for (cmPropertyMap::const_iterator it = propsObject.begin(); - it != propsObject.end(); ++it) { - props.push_back(it->first); + for (auto const& it : propsObject) { + props.push_back(it.first); } return props; } @@ -4282,9 +4193,8 @@ void cmGeneratorTarget::ReportPropertyOrigin( void cmGeneratorTarget::LookupLinkItems(std::vector<std::string> const& names, std::vector<cmLinkItem>& items) const { - for (std::vector<std::string>::const_iterator i = names.begin(); - i != names.end(); ++i) { - std::string name = this->CheckCMP0004(*i); + for (std::string const& n : names) { + std::string name = this->CheckCMP0004(n); if (name == this->GetName() || name.empty()) { continue; } @@ -4306,7 +4216,7 @@ void cmGeneratorTarget::ExpandLinkItems( dagChecker.SetTransitivePropertiesOnly(); } std::vector<std::string> libs; - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(value); + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(value); cmSystemTools::ExpandListArgument(cge->Evaluate(this->LocalGenerator, config, false, headTarget, this, &dagChecker), @@ -4365,21 +4275,17 @@ void cmGeneratorTarget::ComputeLinkInterface( // Shared libraries may have runtime implementation dependencies // on other shared libraries that are not in the interface. std::unordered_set<std::string> emitted; - for (std::vector<cmLinkItem>::const_iterator li = - iface.Libraries.begin(); - li != iface.Libraries.end(); ++li) { - emitted.insert(*li); + for (cmLinkItem const& lib : iface.Libraries) { + emitted.insert(lib); } if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY) { cmLinkImplementation const* impl = this->GetLinkImplementation(config); - for (std::vector<cmLinkImplItem>::const_iterator li = - impl->Libraries.begin(); - li != impl->Libraries.end(); ++li) { - if (emitted.insert(*li).second) { - if (li->Target) { + for (cmLinkImplItem const& lib : impl->Libraries) { + if (emitted.insert(lib).second) { + if (lib.Target) { // This is a runtime dependency on another shared library. - if (li->Target->GetType() == cmStateEnums::SHARED_LIBRARY) { - iface.SharedDeps.push_back(*li); + if (lib.Target->GetType() == cmStateEnums::SHARED_LIBRARY) { + iface.SharedDeps.push_back(lib); } } else { // TODO: Recognize shared library file names. Perhaps this @@ -4580,21 +4486,22 @@ bool cmGeneratorTarget::ComputeOutputDir(const std::string& config, if (const char* config_outdir = this->GetProperty(configProp)) { // Use the user-specified per-configuration output directory. cmGeneratorExpression ge; - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(config_outdir); + std::unique_ptr<cmCompiledGeneratorExpression> cge = + ge.Parse(config_outdir); out = cge->Evaluate(this->LocalGenerator, config); // Skip per-configuration subdirectory. - conf = ""; + conf.clear(); } else if (const char* outdir = this->GetProperty(propertyName)) { // Use the user-specified output directory. cmGeneratorExpression ge; - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(outdir); + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(outdir); out = cge->Evaluate(this->LocalGenerator, config); // Skip per-configuration subdirectory if the value contained a // generator expression. if (out != outdir) { - conf = ""; + conf.clear(); } } else if (this->GetType() == cmStateEnums::EXECUTABLE) { // Lookup the output path for executables. @@ -4660,7 +4567,7 @@ bool cmGeneratorTarget::ComputePDBOutputDir(const std::string& kind, out = config_outdir; // Skip per-configuration subdirectory. - conf = ""; + conf.clear(); } else if (const char* outdir = this->GetProperty(propertyName)) { // Use the user-specified output directory. out = outdir; @@ -5091,19 +4998,17 @@ bool cmGeneratorTarget::GetConfigCommonSourceFiles( if (configFiles != files) { std::string firstConfigFiles; const char* sep = ""; - for (std::vector<cmSourceFile*>::const_iterator fi = files.begin(); - fi != files.end(); ++fi) { + for (cmSourceFile* f : files) { firstConfigFiles += sep; - firstConfigFiles += (*fi)->GetFullPath(); + firstConfigFiles += f->GetFullPath(); sep = "\n "; } std::string thisConfigFiles; sep = ""; - for (std::vector<cmSourceFile*>::const_iterator fi = configFiles.begin(); - fi != configFiles.end(); ++fi) { + for (cmSourceFile* f : configFiles) { thisConfigFiles += sep; - thisConfigFiles += (*fi)->GetFullPath(); + thisConfigFiles += f->GetFullPath(); sep = "\n "; } std::ostringstream e; @@ -5134,17 +5039,13 @@ void cmGeneratorTarget::GetObjectLibrariesCMP0026( // for TARGET_OBJECTS instead for backwards compatibility with OLD // behavior of CMP0024 and CMP0026 only. cmStringRange rng = this->Target->GetSourceEntries(); - for (std::vector<std::string>::const_iterator i = rng.begin(); - i != rng.end(); ++i) { - std::string const& entry = *i; - + for (std::string const& entry : rng) { std::vector<std::string> files; cmSystemTools::ExpandListArgument(entry, files); - for (std::vector<std::string>::const_iterator li = files.begin(); - li != files.end(); ++li) { - if (cmHasLiteralPrefix(*li, "$<TARGET_OBJECTS:") && - (*li)[li->size() - 1] == '>') { - std::string objLibName = li->substr(17, li->size() - 18); + for (std::string const& li : files) { + if (cmHasLiteralPrefix(li, "$<TARGET_OBJECTS:") && + li[li.size() - 1] == '>') { + std::string objLibName = li.substr(17, li.size() - 18); if (cmGeneratorExpression::Find(objLibName) != std::string::npos) { continue; @@ -5210,9 +5111,8 @@ void cmGeneratorTarget::GetLanguages(std::set<std::string>& languages, { std::vector<cmSourceFile*> sourceFiles; this->GetSourceFiles(sourceFiles, config); - for (std::vector<cmSourceFile*>::const_iterator i = sourceFiles.begin(); - i != sourceFiles.end(); ++i) { - const std::string& lang = (*i)->GetLanguage(); + for (cmSourceFile* src : sourceFiles) { + const std::string& lang = src->GetLanguage(); if (!lang.empty()) { languages.insert(lang); } @@ -5224,27 +5124,21 @@ void cmGeneratorTarget::GetLanguages(std::set<std::string>& languages, std::vector<cmGeneratorTarget*> objectTargets; this->GetObjectLibrariesCMP0026(objectTargets); objectLibraries.reserve(objectTargets.size()); - for (std::vector<cmGeneratorTarget*>::const_iterator it = - objectTargets.begin(); - it != objectTargets.end(); ++it) { - objectLibraries.push_back(*it); + for (cmGeneratorTarget* gt : objectTargets) { + objectLibraries.push_back(gt); } } else { this->GetExternalObjects(externalObjects, config); - for (std::vector<cmSourceFile const*>::const_iterator i = - externalObjects.begin(); - i != externalObjects.end(); ++i) { - std::string objLib = (*i)->GetObjectLibrary(); + for (cmSourceFile const* extObj : externalObjects) { + std::string objLib = extObj->GetObjectLibrary(); if (cmGeneratorTarget* tgt = this->LocalGenerator->FindGeneratorTargetToUse(objLib)) { objectLibraries.push_back(tgt); } } } - for (std::vector<cmGeneratorTarget*>::const_iterator i = - objectLibraries.begin(); - i != objectLibraries.end(); ++i) { - (*i)->GetLanguages(languages, config); + for (cmGeneratorTarget* objLib : objectLibraries) { + objLib->GetLanguages(languages, config); } } @@ -5331,7 +5225,7 @@ void cmGeneratorTarget::ComputeLinkImplementationLibraries( cmGeneratorExpressionDAGChecker dagChecker( this->GetName(), "LINK_LIBRARIES", nullptr, nullptr); cmGeneratorExpression ge(*btIt); - CM_AUTO_PTR<cmCompiledGeneratorExpression> const cge = ge.Parse(*le); + std::unique_ptr<cmCompiledGeneratorExpression> const cge = ge.Parse(*le); std::string const evaluated = cge->Evaluate(this->LocalGenerator, config, false, head, &dagChecker); cmSystemTools::ExpandListArgument(evaluated, llibs); @@ -5339,10 +5233,9 @@ void cmGeneratorTarget::ComputeLinkImplementationLibraries( impl.HadHeadSensitiveCondition = true; } - for (std::vector<std::string>::const_iterator li = llibs.begin(); - li != llibs.end(); ++li) { + for (std::string const& lib : llibs) { // Skip entries that resolve to the target itself or are empty. - std::string name = this->CheckCMP0004(*li); + std::string name = this->CheckCMP0004(lib); if (name == this->GetName() || name.empty()) { if (name == this->GetName()) { bool noMessage = false; @@ -5380,10 +5273,9 @@ void cmGeneratorTarget::ComputeLinkImplementationLibraries( } std::set<std::string> const& seenProps = cge->GetSeenTargetProperties(); - for (std::set<std::string>::const_iterator it = seenProps.begin(); - it != seenProps.end(); ++it) { - if (!this->GetProperty(*it)) { - this->LinkImplicitNullProperties.insert(*it); + for (std::string const& sp : seenProps) { + if (!this->GetProperty(sp)) { + this->LinkImplicitNullProperties.insert(sp); } } cge->GetMaxLanguageStandard(this, this->MaxLanguageStandards); @@ -5397,10 +5289,9 @@ void cmGeneratorTarget::ComputeLinkImplementationLibraries( CMP0003_ComputeLinkType(config, debugConfigs); cmTarget::LinkLibraryVectorType const& oldllibs = this->Target->GetOriginalLinkLibraries(); - for (cmTarget::LinkLibraryVectorType::const_iterator li = oldllibs.begin(); - li != oldllibs.end(); ++li) { - if (li->second != GENERAL_LibraryType && li->second != linkType) { - std::string name = this->CheckCMP0004(li->first); + for (cmTarget::LibraryID const& oldllib : oldllibs) { + if (oldllib.second != GENERAL_LibraryType && oldllib.second != linkType) { + std::string name = this->CheckCMP0004(oldllib.first); if (name == this->GetName() || name.empty()) { continue; } diff --git a/Source/cmGeneratorTarget.h b/Source/cmGeneratorTarget.h index 85311a7..1ee8a16 100644 --- a/Source/cmGeneratorTarget.h +++ b/Source/cmGeneratorTarget.h @@ -661,7 +661,7 @@ private: SourceEntriesType SourceDepends; mutable std::map<cmSourceFile const*, std::string> Objects; std::set<cmSourceFile const*> ExplicitObjectName; - mutable std::map<std::string, std::vector<std::string> > SystemIncludesCache; + mutable std::map<std::string, std::vector<std::string>> SystemIncludesCache; mutable std::string ExportMacro; diff --git a/Source/cmGetCMakePropertyCommand.h b/Source/cmGetCMakePropertyCommand.h index 803f051..1f29c78 100644 --- a/Source/cmGetCMakePropertyCommand.h +++ b/Source/cmGetCMakePropertyCommand.h @@ -15,14 +15,14 @@ class cmExecutionStatus; class cmGetCMakePropertyCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE { return new cmGetCMakePropertyCommand; } + cmCommand* Clone() override { return new cmGetCMakePropertyCommand; } /** * This is called when the command is first encountered in * the input file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmGetDirectoryPropertyCommand.h b/Source/cmGetDirectoryPropertyCommand.h index f373bc2..02ea056 100644 --- a/Source/cmGetDirectoryPropertyCommand.h +++ b/Source/cmGetDirectoryPropertyCommand.h @@ -15,14 +15,14 @@ class cmExecutionStatus; class cmGetDirectoryPropertyCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE { return new cmGetDirectoryPropertyCommand; } + cmCommand* Clone() override { return new cmGetDirectoryPropertyCommand; } /** * This is called when the command is first encountered in * the input file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: void StoreResult(const std::string& variable, const char* prop); diff --git a/Source/cmGetFilenameComponentCommand.cxx b/Source/cmGetFilenameComponentCommand.cxx index c23684c..1b358ab 100644 --- a/Source/cmGetFilenameComponentCommand.cxx +++ b/Source/cmGetFilenameComponentCommand.cxx @@ -60,7 +60,30 @@ bool cmGetFilenameComponentCommand::InitialPass( } } } - cmSystemTools::SplitProgramFromArgs(filename, result, programArgs); + + // First assume the path to the program was specified with no + // arguments and with no quoting or escaping for spaces. + // Only bother doing this if there is non-whitespace. + if (!cmSystemTools::TrimWhitespace(filename).empty()) { + result = cmSystemTools::FindProgram(filename); + } + + // If that failed then assume a command-line string was given + // and split the program part from the rest of the arguments. + if (result.empty()) { + std::string program; + if (cmSystemTools::SplitProgramFromArgs(filename, program, + programArgs)) { + if (cmSystemTools::FileExists(program)) { + result = program; + } else { + result = cmSystemTools::FindProgram(program); + } + } + if (result.empty()) { + programArgs.clear(); + } + } } else if (args[2] == "EXT") { result = cmSystemTools::GetFilenameExtension(filename); } else if (args[2] == "NAME_WE") { diff --git a/Source/cmGetFilenameComponentCommand.h b/Source/cmGetFilenameComponentCommand.h index b7141b2..8c26655 100644 --- a/Source/cmGetFilenameComponentCommand.h +++ b/Source/cmGetFilenameComponentCommand.h @@ -24,14 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmGetFilenameComponentCommand; } + cmCommand* Clone() override { return new cmGetFilenameComponentCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmGetPropertyCommand.h b/Source/cmGetPropertyCommand.h index 44a3852..c3f653e 100644 --- a/Source/cmGetPropertyCommand.h +++ b/Source/cmGetPropertyCommand.h @@ -17,14 +17,14 @@ class cmGetPropertyCommand : public cmCommand public: cmGetPropertyCommand(); - cmCommand* Clone() CM_OVERRIDE { return new cmGetPropertyCommand; } + cmCommand* Clone() override { return new cmGetPropertyCommand; } /** * This is called when the command is first encountered in * the input file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: enum OutType diff --git a/Source/cmGetSourceFilePropertyCommand.h b/Source/cmGetSourceFilePropertyCommand.h index d4fef01..43bc330 100644 --- a/Source/cmGetSourceFilePropertyCommand.h +++ b/Source/cmGetSourceFilePropertyCommand.h @@ -15,14 +15,14 @@ class cmExecutionStatus; class cmGetSourceFilePropertyCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE { return new cmGetSourceFilePropertyCommand; } + cmCommand* Clone() override { return new cmGetSourceFilePropertyCommand; } /** * This is called when the command is first encountered in * the input file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmGetTargetPropertyCommand.h b/Source/cmGetTargetPropertyCommand.h index e74b7e1..63ee5fd 100644 --- a/Source/cmGetTargetPropertyCommand.h +++ b/Source/cmGetTargetPropertyCommand.h @@ -15,14 +15,14 @@ class cmExecutionStatus; class cmGetTargetPropertyCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE { return new cmGetTargetPropertyCommand; } + cmCommand* Clone() override { return new cmGetTargetPropertyCommand; } /** * This is called when the command is first encountered in * the input file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmGetTestPropertyCommand.h b/Source/cmGetTestPropertyCommand.h index 5a3ef40..4a74f59 100644 --- a/Source/cmGetTestPropertyCommand.h +++ b/Source/cmGetTestPropertyCommand.h @@ -15,14 +15,14 @@ class cmExecutionStatus; class cmGetTestPropertyCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE { return new cmGetTestPropertyCommand; } + cmCommand* Clone() override { return new cmGetTestPropertyCommand; } /** * This is called when the command is first encountered in * the input file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmGhsMultiTargetGenerator.cxx b/Source/cmGhsMultiTargetGenerator.cxx index 7032cd5..a31e415 100644 --- a/Source/cmGhsMultiTargetGenerator.cxx +++ b/Source/cmGhsMultiTargetGenerator.cxx @@ -363,7 +363,7 @@ void cmGhsMultiTargetGenerator::WriteTargetLinkLibraries( this->GeneratorTarget->GetCreateRuleVariable(language, config); bool useWatcomQuote = this->Makefile->IsOn(createRule + "_USE_WATCOM_QUOTE"); - CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer( + std::unique_ptr<cmLinkLineComputer> linkLineComputer( this->GetGlobalGenerator()->CreateLinkLineComputer( this->LocalGenerator, this->LocalGenerator->GetStateSnapshot().GetDirectory())); @@ -439,7 +439,7 @@ cmGhsMultiTargetGenerator::GetObjectNames( cmLocalGhsMultiGenerator* const localGhsMultiGenerator, cmGeneratorTarget* const generatorTarget) { - std::map<std::string, std::vector<cmSourceFile*> > filenameToSource; + std::map<std::string, std::vector<cmSourceFile*>> filenameToSource; std::map<cmSourceFile*, std::string> sourceToFilename; for (std::vector<cmSourceFile*>::const_iterator sf = objectSources->begin(); sf != objectSources->end(); ++sf) { @@ -451,7 +451,7 @@ cmGhsMultiTargetGenerator::GetObjectNames( } std::vector<cmSourceFile*> duplicateSources; - for (std::map<std::string, std::vector<cmSourceFile*> >::const_iterator + for (std::map<std::string, std::vector<cmSourceFile*>>::const_iterator msvSourceI = filenameToSource.begin(); msvSourceI != filenameToSource.end(); ++msvSourceI) { if (msvSourceI->second.size() > 1) { diff --git a/Source/cmGlobalCommonGenerator.h b/Source/cmGlobalCommonGenerator.h index 842a7c4..e19118b 100644 --- a/Source/cmGlobalCommonGenerator.h +++ b/Source/cmGlobalCommonGenerator.h @@ -16,7 +16,7 @@ class cmGlobalCommonGenerator : public cmGlobalGenerator { public: cmGlobalCommonGenerator(cmake* cm); - ~cmGlobalCommonGenerator() CM_OVERRIDE; + ~cmGlobalCommonGenerator() override; }; #endif diff --git a/Source/cmGlobalGenerator.cxx b/Source/cmGlobalGenerator.cxx index ab35593..958aa05 100644 --- a/Source/cmGlobalGenerator.cxx +++ b/Source/cmGlobalGenerator.cxx @@ -244,10 +244,8 @@ bool cmGlobalGenerator::GenerateImportFile(const std::string& file) bool result = it->second->GenerateImportFile(); if (!this->ConfigureDoneCMP0026AndCMP0024) { - for (std::vector<cmMakefile*>::const_iterator mit = - this->Makefiles.begin(); - mit != this->Makefiles.end(); ++mit) { - (*mit)->RemoveExportBuildFileGeneratorCMP0024(it->second); + for (cmMakefile* m : this->Makefiles) { + m->RemoveExportBuildFileGeneratorCMP0024(it->second); } } @@ -383,12 +381,11 @@ void cmGlobalGenerator::EnableLanguage( } std::set<std::string> cur_languages(languages.begin(), languages.end()); - for (std::set<std::string>::iterator li = cur_languages.begin(); - li != cur_languages.end(); ++li) { - if (!this->LanguagesInProgress.insert(*li).second) { + for (std::string const& li : cur_languages) { + if (!this->LanguagesInProgress.insert(li).second) { std::ostringstream e; - e << "Language '" << *li << "' is currently being enabled. " - "Recursive call not allowed."; + e << "Language '" << li << "' is currently being enabled. " + "Recursive call not allowed."; mf->IssueMessage(cmake::FATAL_ERROR, e.str()); cmSystemTools::SetFatalErrorOccured(); return; @@ -397,12 +394,11 @@ void cmGlobalGenerator::EnableLanguage( if (this->TryCompileOuterMakefile) { // In a try-compile we can only enable languages provided by caller. - for (std::vector<std::string>::const_iterator li = languages.begin(); - li != languages.end(); ++li) { - if (*li == "NONE") { + for (std::string const& li : languages) { + if (li == "NONE") { this->SetLanguageEnabled("NONE", mf); } else { - const char* lang = li->c_str(); + const char* lang = li.c_str(); if (this->LanguagesReady.find(lang) == this->LanguagesReady.end()) { std::ostringstream e; e << "The test project needs language " << lang @@ -541,11 +537,10 @@ void cmGlobalGenerator::EnableLanguage( // load the CMakeDetermine(LANG)Compiler.cmake file to find // the compiler - for (std::vector<std::string>::const_iterator l = languages.begin(); - l != languages.end(); ++l) { - const char* lang = l->c_str(); + for (std::string const& l : languages) { + const char* lang = l.c_str(); needSetLanguageEnabledMaps[lang] = false; - if (*l == "NONE") { + if (l == "NONE") { this->SetLanguageEnabled("NONE", mf); continue; } @@ -647,10 +642,9 @@ void cmGlobalGenerator::EnableLanguage( } // loop over languages again loading CMake(LANG)Information.cmake // - for (std::vector<std::string>::const_iterator l = languages.begin(); - l != languages.end(); ++l) { - const char* lang = l->c_str(); - if (*l == "NONE") { + for (std::string const& l : languages) { + const char* lang = l.c_str(); + if (l == "NONE") { this->SetLanguageEnabled("NONE", mf); continue; } @@ -793,9 +787,8 @@ void cmGlobalGenerator::EnableLanguage( cmSystemTools::SetFatalErrorOccured(); } - for (std::set<std::string>::iterator li = cur_languages.begin(); - li != cur_languages.end(); ++li) { - this->LanguagesInProgress.erase(*li); + for (std::string const& lang : cur_languages) { + this->LanguagesInProgress.erase(lang); } } @@ -1020,9 +1013,8 @@ void cmGlobalGenerator::SetLanguageEnabledMaps(const std::string& l, std::string ignoreExts = mf->GetSafeDefinition(ignoreExtensionsVar); std::vector<std::string> extensionList; cmSystemTools::ExpandListArgument(ignoreExts, extensionList); - for (std::vector<std::string>::iterator i = extensionList.begin(); - i != extensionList.end(); ++i) { - this->IgnoreExtensions[*i] = true; + for (std::string const& i : extensionList) { + this->IgnoreExtensions[i] = true; } } @@ -1034,9 +1026,8 @@ void cmGlobalGenerator::FillExtensionToLanguageMap(const std::string& l, std::string exts = mf->GetSafeDefinition(extensionsVar); std::vector<std::string> extensionList; cmSystemTools::ExpandListArgument(exts, extensionList); - for (std::vector<std::string>::iterator i = extensionList.begin(); - i != extensionList.end(); ++i) { - this->ExtensionToLanguage[*i] = l; + for (std::string const& i : extensionList) { + this->ExtensionToLanguage[i] = l; } } @@ -1082,9 +1073,8 @@ void cmGlobalGenerator::CreateLocalGenerators() cmDeleteAll(this->LocalGenerators); this->LocalGenerators.clear(); this->LocalGenerators.reserve(this->Makefiles.size()); - for (std::vector<cmMakefile*>::const_iterator it = this->Makefiles.begin(); - it != this->Makefiles.end(); ++it) { - this->LocalGenerators.push_back(this->CreateLocalGenerator(*it)); + for (cmMakefile* m : this->Makefiles) { + this->LocalGenerators.push_back(this->CreateLocalGenerator(m)); } } @@ -1118,13 +1108,11 @@ void cmGlobalGenerator::Configure() std::vector<GlobalTargetInfo> globalTargets; this->CreateDefaultGlobalTargets(globalTargets); - for (unsigned int i = 0; i < this->Makefiles.size(); ++i) { - cmMakefile* mf = this->Makefiles[i]; + for (cmMakefile* mf : this->Makefiles) { cmTargets* targets = &(mf->GetTargets()); - for (std::vector<GlobalTargetInfo>::iterator gti = globalTargets.begin(); - gti != globalTargets.end(); ++gti) { - targets->insert( - cmTargets::value_type(gti->Name, this->CreateGlobalTarget(*gti, mf))); + for (GlobalTargetInfo const& globalTarget : globalTargets) { + targets->insert(cmTargets::value_type( + globalTarget.Name, this->CreateGlobalTarget(globalTarget, mf))); } } @@ -1177,9 +1165,8 @@ void cmGlobalGenerator::CreateImportedGenerationObjects( std::find(this->Makefiles.begin(), this->Makefiles.end(), mf); cmLocalGenerator* lg = this->LocalGenerators[std::distance(this->Makefiles.begin(), mfit)]; - for (std::vector<std::string>::const_iterator it = targets.begin(); - it != targets.end(); ++it) { - cmGeneratorTarget* gt = lg->FindGeneratorTargetToUse(*it); + for (std::string const& t : targets) { + cmGeneratorTarget* gt = lg->FindGeneratorTargetToUse(t); if (gt) { exports.push_back(gt); } @@ -1229,10 +1216,8 @@ void cmGlobalGenerator::ComputeBuildFileGenerators() for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) { std::vector<cmExportBuildFileGenerator*> gens = this->Makefiles[i]->GetExportBuildFileGenerators(); - for (std::vector<cmExportBuildFileGenerator*>::const_iterator it = - gens.begin(); - it != gens.end(); ++it) { - (*it)->Compute(this->LocalGenerators[i]); + for (cmExportBuildFileGenerator* g : gens) { + g->Compute(this->LocalGenerators[i]); } } } @@ -1263,15 +1248,12 @@ bool cmGlobalGenerator::Compute() #ifdef CMAKE_BUILD_WITH_CMAKE // Iterate through all targets and set up automoc for those which have // the AUTOMOC, AUTOUIC or AUTORCC property set - std::vector<cmGeneratorTarget const*> autogenTargets = - this->CreateQtAutoGeneratorsTargets(); + cmQtAutoGenDigestUPV autogenDigests = this->CreateQtAutoGeneratorsTargets(); #endif - unsigned int i; - // Add generator specific helper commands - for (i = 0; i < this->LocalGenerators.size(); ++i) { - this->LocalGenerators[i]->AddHelperCommands(); + for (cmLocalGenerator* localGen : this->LocalGenerators) { + localGen->AddHelperCommands(); } // Finalize the set of compile features for each target. @@ -1280,26 +1262,23 @@ bool cmGlobalGenerator::Compute() // on the original cmTarget instance. It accumulates features // across all configurations. Some refactoring is needed to // compute a per-config resulta purely during generation. - for (i = 0; i < this->LocalGenerators.size(); ++i) { - if (!this->LocalGenerators[i]->ComputeTargetCompileFeatures()) { + for (cmLocalGenerator* localGen : this->LocalGenerators) { + if (!localGen->ComputeTargetCompileFeatures()) { return false; } } #ifdef CMAKE_BUILD_WITH_CMAKE - for (std::vector<cmGeneratorTarget const*>::iterator it = - autogenTargets.begin(); - it != autogenTargets.end(); ++it) { - cmQtAutoGeneratorInitializer::SetupAutoGenerateTarget(*it); + for (cmQtAutoGenDigestUP const& digest : autogenDigests) { + cmQtAutoGeneratorInitializer::SetupAutoGenerateTarget(*digest); } + autogenDigests.clear(); #endif - for (i = 0; i < this->LocalGenerators.size(); ++i) { - cmMakefile* mf = this->LocalGenerators[i]->GetMakefile(); - std::vector<cmInstallGenerator*>& gens = mf->GetInstallGenerators(); - for (std::vector<cmInstallGenerator*>::const_iterator git = gens.begin(); - git != gens.end(); ++git) { - (*git)->Compute(this->LocalGenerators[i]); + for (cmLocalGenerator* localGen : this->LocalGenerators) { + cmMakefile* mf = localGen->GetMakefile(); + for (cmInstallGenerator* g : mf->GetInstallGenerators()) { + g->Compute(localGen); } } @@ -1307,15 +1286,15 @@ bool cmGlobalGenerator::Compute() // Trace the dependencies, after that no custom commands should be added // because their dependencies might not be handled correctly - for (i = 0; i < this->LocalGenerators.size(); ++i) { - this->LocalGenerators[i]->TraceDependencies(); + for (cmLocalGenerator* localGen : this->LocalGenerators) { + localGen->TraceDependencies(); } this->ForceLinkerLanguages(); // Compute the manifest of main targets generated. - for (i = 0; i < this->LocalGenerators.size(); ++i) { - this->LocalGenerators[i]->ComputeTargetManifest(); + for (cmLocalGenerator* localGen : this->LocalGenerators) { + localGen->ComputeTargetManifest(); } // Compute the inter-target dependencies. @@ -1323,8 +1302,8 @@ bool cmGlobalGenerator::Compute() return false; } - for (i = 0; i < this->LocalGenerators.size(); ++i) { - this->LocalGenerators[i]->ComputeHomeRelativeOutputPath(); + for (cmLocalGenerator* localGen : this->LocalGenerators) { + localGen->ComputeHomeRelativeOutputPath(); } return true; @@ -1358,10 +1337,8 @@ void cmGlobalGenerator::Generate() cmake::FATAL_ERROR, "Could not write CPack properties file."); } - for (std::map<std::string, cmExportBuildFileGenerator*>::iterator it = - this->BuildExportSets.begin(); - it != this->BuildExportSets.end(); ++it) { - if (!it->second->GenerateImportFile()) { + for (auto& buildExpSet : this->BuildExportSets) { + if (!buildExpSet.second->GenerateImportFile()) { if (!cmSystemTools::GetErrorOccuredFlag()) { this->GetCMakeInstance()->IssueMessage(cmake::FATAL_ERROR, "Could not write export file."); @@ -1383,10 +1360,8 @@ void cmGlobalGenerator::Generate() w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0042) << "\n"; w << "MACOSX_RPATH is not specified for" " the following targets:\n"; - for (std::set<std::string>::iterator iter = - this->CMP0042WarnTargets.begin(); - iter != this->CMP0042WarnTargets.end(); ++iter) { - w << " " << *iter << "\n"; + for (std::string const& t : this->CMP0042WarnTargets) { + w << " " << t << "\n"; } this->GetCMakeInstance()->IssueMessage(cmake::AUTHOR_WARNING, w.str()); } @@ -1401,10 +1376,8 @@ void cmGlobalGenerator::Generate() "settings:\n" ; /* clang-format on */ - for (std::set<std::string>::iterator iter = - this->CMP0068WarnTargets.begin(); - iter != this->CMP0068WarnTargets.end(); ++iter) { - w << " " << *iter << "\n"; + for (std::string const& t : this->CMP0068WarnTargets) { + w << " " << t << "\n"; } this->GetCMakeInstance()->IssueMessage(cmake::AUTHOR_WARNING, w.str()); } @@ -1419,32 +1392,22 @@ bool cmGlobalGenerator::ComputeTargetDepends() return false; } std::vector<cmGeneratorTarget const*> const& targets = ctd.GetTargets(); - for (std::vector<cmGeneratorTarget const*>::const_iterator ti = - targets.begin(); - ti != targets.end(); ++ti) { - ctd.GetTargetDirectDepends(*ti, this->TargetDependencies[*ti]); + for (cmGeneratorTarget const* target : targets) { + ctd.GetTargetDirectDepends(target, this->TargetDependencies[target]); } return true; } -std::vector<const cmGeneratorTarget*> -cmGlobalGenerator::CreateQtAutoGeneratorsTargets() +cmQtAutoGenDigestUPV cmGlobalGenerator::CreateQtAutoGeneratorsTargets() { - std::vector<const cmGeneratorTarget*> autogenTargets; + cmQtAutoGenDigestUPV autogenDigests; #ifdef CMAKE_BUILD_WITH_CMAKE - for (std::vector<cmLocalGenerator*>::const_iterator lgit = - this->LocalGenerators.begin(); - lgit != this->LocalGenerators.end(); ++lgit) { - cmLocalGenerator* localGen = *lgit; + for (cmLocalGenerator* localGen : this->LocalGenerators) { const std::vector<cmGeneratorTarget*>& targets = localGen->GetGeneratorTargets(); // Find targets that require AUTOGEN processing - std::vector<cmGeneratorTarget*> filteredTargets; - filteredTargets.reserve(targets.size()); - for (std::vector<cmGeneratorTarget*>::const_iterator ti = targets.begin(); - ti != targets.end(); ++ti) { - cmGeneratorTarget* target = *ti; + for (cmGeneratorTarget* target : targets) { if (target->GetType() == cmStateEnums::GLOBAL_TARGET) { continue; } @@ -1455,33 +1418,43 @@ cmGlobalGenerator::CreateQtAutoGeneratorsTargets() target->GetType() != cmStateEnums::OBJECT_LIBRARY) { continue; } - if ((!target->GetPropertyAsBool("AUTOMOC") && - !target->GetPropertyAsBool("AUTOUIC") && - !target->GetPropertyAsBool("AUTORCC")) || - target->IsImported()) { + if (target->IsImported()) { continue; } - // don't do anything if there is no Qt4 or Qt5Core (which contains moc) - cmMakefile* mf = target->Target->GetMakefile(); - std::string qtMajorVersion = mf->GetSafeDefinition("QT_VERSION_MAJOR"); - if (qtMajorVersion == "") { - qtMajorVersion = mf->GetSafeDefinition("Qt5Core_VERSION_MAJOR"); + + const bool mocEnabled = target->GetPropertyAsBool("AUTOMOC"); + const bool uicEnabled = target->GetPropertyAsBool("AUTOUIC"); + const bool rccEnabled = target->GetPropertyAsBool("AUTORCC"); + if (!mocEnabled && !uicEnabled && !rccEnabled) { + continue; } - if (qtMajorVersion != "4" && qtMajorVersion != "5") { + + std::string qtVersionMajor = + cmQtAutoGeneratorInitializer::GetQtMajorVersion(target); + // don't do anything if there is no Qt4 or Qt5Core (which contains moc) + if (qtVersionMajor != "4" && qtVersionMajor != "5") { continue; } - filteredTargets.push_back(target); - } - // Initialize AUTOGEN targets - for (std::vector<cmGeneratorTarget*>::iterator ti = - filteredTargets.begin(); - ti != filteredTargets.end(); ++ti) { - cmQtAutoGeneratorInitializer::InitializeAutogenTarget(localGen, *ti); - autogenTargets.push_back(*ti); + + { + cmQtAutoGenDigestUP digest(new cmQtAutoGenDigest(target)); + digest->QtVersionMajor = std::move(qtVersionMajor); + digest->QtVersionMinor = + cmQtAutoGeneratorInitializer::GetQtMinorVersion( + target, digest->QtVersionMajor); + digest->MocEnabled = mocEnabled; + digest->UicEnabled = uicEnabled; + digest->RccEnabled = rccEnabled; + autogenDigests.emplace_back(std::move(digest)); + } } } + // Initialize autogen targets + for (const cmQtAutoGenDigestUP& digest : autogenDigests) { + cmQtAutoGeneratorInitializer::InitializeAutogenTarget(*digest); + } #endif - return autogenTargets; + return autogenDigests; } cmLinkLineComputer* cmGlobalGenerator::CreateLinkLineComputer( @@ -1502,17 +1475,15 @@ void cmGlobalGenerator::FinalizeTargetCompileInfo() this->CMakeInstance->GetState()->GetEnabledLanguages(); // Construct per-target generator information. - for (unsigned int i = 0; i < this->Makefiles.size(); ++i) { - cmMakefile* mf = this->Makefiles[i]; - + for (cmMakefile* mf : this->Makefiles) { const cmStringRange noconfig_compile_definitions = mf->GetCompileDefinitionsEntries(); const cmBacktraceRange noconfig_compile_definitions_bts = mf->GetCompileDefinitionsBacktraces(); cmTargets& targets = mf->GetTargets(); - for (cmTargets::iterator ti = targets.begin(); ti != targets.end(); ++ti) { - cmTarget* t = &ti->second; + for (auto& target : targets) { + cmTarget* t = &target.second; if (t->GetType() == cmStateEnums::GLOBAL_TARGET) { continue; } @@ -1537,10 +1508,9 @@ void cmGlobalGenerator::FinalizeTargetCompileInfo() std::vector<std::string> configs; mf->GetConfigurations(configs); - for (std::vector<std::string>::const_iterator ci = configs.begin(); - ci != configs.end(); ++ci) { + for (std::string const& c : configs) { std::string defPropName = "COMPILE_DEFINITIONS_"; - defPropName += cmSystemTools::UpperCase(*ci); + defPropName += cmSystemTools::UpperCase(c); t->AppendProperty(defPropName, mf->GetProperty(defPropName)); } } @@ -1549,10 +1519,9 @@ void cmGlobalGenerator::FinalizeTargetCompileInfo() // The standard include directories for each language // should be treated as system include directories. std::set<std::string> standardIncludesSet; - for (std::vector<std::string>::const_iterator li = langs.begin(); - li != langs.end(); ++li) { + for (std::string const& li : langs) { std::string const standardIncludesVar = - "CMAKE_" + *li + "_STANDARD_INCLUDE_DIRECTORIES"; + "CMAKE_" + li + "_STANDARD_INCLUDE_DIRECTORIES"; std::string const standardIncludesStr = mf->GetSafeDefinition(standardIncludesVar); std::vector<std::string> standardIncludesVec; @@ -1571,8 +1540,8 @@ void cmGlobalGenerator::CreateGeneratorTargets( { if (targetTypes == AllTargets) { cmTargets& targets = mf->GetTargets(); - for (cmTargets::iterator ti = targets.begin(); ti != targets.end(); ++ti) { - cmTarget* t = &ti->second; + for (auto& target : targets) { + cmTarget* t = &target.second; cmGeneratorTarget* gt = new cmGeneratorTarget(t, lg); lg->AddGeneratorTarget(gt); } @@ -1580,9 +1549,8 @@ void cmGlobalGenerator::CreateGeneratorTargets( std::vector<cmTarget*> itgts = mf->GetImportedTargets(); - for (std::vector<cmTarget*>::const_iterator j = itgts.begin(); - j != itgts.end(); ++j) { - lg->AddImportedGeneratorTarget(importedMap.find(*j)->second); + for (cmTarget* t : itgts) { + lg->AddImportedGeneratorTarget(importedMap.find(t)->second); } } @@ -1591,13 +1559,11 @@ void cmGlobalGenerator::CreateGeneratorTargets(TargetTypes targetTypes) std::map<cmTarget*, cmGeneratorTarget*> importedMap; for (unsigned int i = 0; i < this->Makefiles.size(); ++i) { cmMakefile* mf = this->Makefiles[i]; - for (std::vector<cmTarget*>::const_iterator j = - mf->GetOwnedImportedTargets().begin(); - j != mf->GetOwnedImportedTargets().end(); ++j) { + for (cmTarget* ownedImpTgt : mf->GetOwnedImportedTargets()) { cmLocalGenerator* lg = this->LocalGenerators[i]; - cmGeneratorTarget* gt = new cmGeneratorTarget(*j, lg); + cmGeneratorTarget* gt = new cmGeneratorTarget(ownedImpTgt, lg); lg->AddOwnedImportedGeneratorTarget(gt); - importedMap[*j] = gt; + importedMap[ownedImpTgt] = gt; } } @@ -1644,30 +1610,30 @@ void cmGlobalGenerator::CheckTargetProperties() for (unsigned int i = 0; i < this->Makefiles.size(); ++i) { this->Makefiles[i]->ConfigureFinalPass(); cmTargets& targets = this->Makefiles[i]->GetTargets(); - for (cmTargets::iterator l = targets.begin(); l != targets.end(); l++) { - if (l->second.GetType() == cmStateEnums::INTERFACE_LIBRARY) { + for (auto const& target : targets) { + if (target.second.GetType() == cmStateEnums::INTERFACE_LIBRARY) { continue; } const cmTarget::LinkLibraryVectorType& libs = - l->second.GetOriginalLinkLibraries(); - for (cmTarget::LinkLibraryVectorType::const_iterator lib = libs.begin(); - lib != libs.end(); ++lib) { - if (lib->first.size() > 9 && - cmSystemTools::IsNOTFOUND(lib->first.c_str())) { - std::string varName = lib->first.substr(0, lib->first.size() - 9); + target.second.GetOriginalLinkLibraries(); + for (auto const& lib : libs) { + if (lib.first.size() > 9 && + cmSystemTools::IsNOTFOUND(lib.first.c_str())) { + std::string varName = lib.first.substr(0, lib.first.size() - 9); if (state->GetCacheEntryPropertyAsBool(varName, "ADVANCED")) { varName += " (ADVANCED)"; } std::string text = notFoundMap[varName]; text += "\n linked by target \""; - text += l->second.GetName(); + text += target.second.GetName(); text += "\" in directory "; text += this->Makefiles[i]->GetCurrentSourceDirectory(); notFoundMap[varName] = text; } } std::vector<std::string> incs; - const char* incDirProp = l->second.GetProperty("INCLUDE_DIRECTORIES"); + const char* incDirProp = + target.second.GetProperty("INCLUDE_DIRECTORIES"); if (!incDirProp) { continue; } @@ -1677,10 +1643,9 @@ void cmGlobalGenerator::CheckTargetProperties() cmSystemTools::ExpandListArgument(incDirs, incs); - for (std::vector<std::string>::const_iterator incDir = incs.begin(); - incDir != incs.end(); ++incDir) { - if (incDir->size() > 9 && cmSystemTools::IsNOTFOUND(incDir->c_str())) { - std::string varName = incDir->substr(0, incDir->size() - 9); + for (std::string const& incDir : incs) { + if (incDir.size() > 9 && cmSystemTools::IsNOTFOUND(incDir.c_str())) { + std::string varName = incDir.substr(0, incDir.size() - 9); if (state->GetCacheEntryPropertyAsBool(varName, "ADVANCED")) { varName += " (ADVANCED)"; } @@ -1699,11 +1664,9 @@ void cmGlobalGenerator::CheckTargetProperties() if (!notFoundMap.empty()) { std::string notFoundVars; - for (std::map<std::string, std::string>::const_iterator ii = - notFoundMap.begin(); - ii != notFoundMap.end(); ++ii) { - notFoundVars += ii->first; - notFoundVars += ii->second; + for (auto const& notFound : notFoundMap) { + notFoundVars += notFound.first; + notFoundVars += notFound.second; notFoundVars += "\n"; } cmSystemTools::Error("The following variables are used in this project, " @@ -2035,16 +1998,15 @@ int cmGlobalGenerator::GetLinkerPreference(const std::string& lang) const void cmGlobalGenerator::FillProjectMap() { this->ProjectMap.clear(); // make sure we start with a clean map - unsigned int i; - for (i = 0; i < this->LocalGenerators.size(); ++i) { + for (cmLocalGenerator* localGen : this->LocalGenerators) { // for each local generator add all projects - cmStateSnapshot snp = this->LocalGenerators[i]->GetStateSnapshot(); + cmStateSnapshot snp = localGen->GetStateSnapshot(); std::string name; do { std::string snpProjName = snp.GetProjectName(); if (name != snpProjName) { name = snpProjName; - this->ProjectMap[name].push_back(this->LocalGenerators[i]); + this->ProjectMap[name].push_back(localGen); } snp = snp.GetBuildsystemDirectoryParent(); } while (snp.IsValid()); @@ -2064,12 +2026,10 @@ cmMakefile* cmGlobalGenerator::FindMakefile(const std::string& start_dir) const cmLocalGenerator* cmGlobalGenerator::FindLocalGenerator( const std::string& start_dir) const { - for (std::vector<cmLocalGenerator*>::const_iterator it = - this->LocalGenerators.begin(); - it != this->LocalGenerators.end(); ++it) { - std::string sd = (*it)->GetCurrentSourceDirectory(); + for (cmLocalGenerator* lg : this->LocalGenerators) { + std::string sd = lg->GetCurrentSourceDirectory(); if (sd == start_dir) { - return *it; + return lg; } } return nullptr; @@ -2477,9 +2437,8 @@ cmTarget cmGlobalGenerator::CreateGlobalTarget(GlobalTargetInfo const& gti, if (!gti.Message.empty()) { target.SetProperty("EchoString", gti.Message.c_str()); } - for (std::vector<std::string>::const_iterator dit = gti.Depends.begin(); - dit != gti.Depends.end(); ++dit) { - target.AddUtility(*dit); + for (std::string const& d : gti.Depends) { + target.AddUtility(d); } // Organize in the "predefined targets" folder: @@ -2587,18 +2546,16 @@ void cmGlobalGenerator::GetTargetSets(TargetDependSet& projectTargets, GeneratorVector const& generators) { // loop over all local generators - for (std::vector<cmLocalGenerator*>::const_iterator i = generators.begin(); - i != generators.end(); ++i) { + for (cmLocalGenerator* generator : generators) { // check to make sure generator is not excluded - if (this->IsExcluded(root, *i)) { + if (this->IsExcluded(root, generator)) { continue; } // Get the targets in the makefile - const std::vector<cmGeneratorTarget*>& tgts = (*i)->GetGeneratorTargets(); + const std::vector<cmGeneratorTarget*>& tgts = + generator->GetGeneratorTargets(); // loop over all the targets - for (std::vector<cmGeneratorTarget*>::const_iterator l = tgts.begin(); - l != tgts.end(); ++l) { - cmGeneratorTarget* target = *l; + for (cmGeneratorTarget* target : tgts) { if (this->IsRootOnlyTarget(target) && target->GetLocalGenerator() != root) { continue; @@ -2625,8 +2582,8 @@ void cmGlobalGenerator::AddTargetDepends(cmGeneratorTarget const* target, // This is the first time we have encountered the target. // Recursively follow its dependencies. TargetDependSet const& ts = this->GetTargetDirectDepends(target); - for (TargetDependSet::const_iterator i = ts.begin(); i != ts.end(); ++i) { - this->AddTargetDepends(*i, projectTargets); + for (auto const& t : ts) { + this->AddTargetDepends(t, projectTargets); } } } @@ -2771,11 +2728,9 @@ void cmGlobalGenerator::WriteRuleHashes(std::string const& pfile) } else { cmGeneratedFileStream fout(pfile.c_str()); fout << "# Hashes of file build rules.\n"; - for (std::map<std::string, RuleHash>::const_iterator rhi = - this->RuleHashes.begin(); - rhi != this->RuleHashes.end(); ++rhi) { - fout.write(rhi->second.Data, 32); - fout << " " << rhi->first << "\n"; + for (auto const& rh : this->RuleHashes) { + fout.write(rh.second.Data, 32); + fout << " " << rh.first << "\n"; } } } @@ -2788,16 +2743,14 @@ void cmGlobalGenerator::WriteSummary() fname += "/TargetDirectories.txt"; cmGeneratedFileStream fout(fname.c_str()); - for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) { - const std::vector<cmGeneratorTarget*>& tgts = - this->LocalGenerators[i]->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator it = tgts.begin(); - it != tgts.end(); ++it) { - if ((*it)->GetType() == cmStateEnums::INTERFACE_LIBRARY) { + for (cmLocalGenerator* lg : this->LocalGenerators) { + const std::vector<cmGeneratorTarget*>& tgts = lg->GetGeneratorTargets(); + for (cmGeneratorTarget* tgt : tgts) { + if (tgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) { continue; } - this->WriteSummary(*it); - fout << (*it)->GetSupportDirectory() << "\n"; + this->WriteSummary(tgt); + fout << tgt->GetSupportDirectory() << "\n"; } } } @@ -2835,10 +2788,9 @@ void cmGlobalGenerator::WriteSummary(cmGeneratorTarget* target) cmSystemTools::ExpandListArgument(targetLabels, labels); if (!labels.empty()) { fout << "# Target labels\n"; - for (std::vector<std::string>::const_iterator li = labels.begin(); - li != labels.end(); ++li) { - fout << " " << *li << "\n"; - lj_target_labels.append(*li); + for (std::string const& l : labels) { + fout << " " << l << "\n"; + lj_target_labels.append(l); } } } @@ -2860,18 +2812,14 @@ void cmGlobalGenerator::WriteSummary(cmGeneratorTarget* target) fout << "# Directory labels\n"; } - for (std::vector<std::string>::const_iterator li = - directoryLabelsList.begin(); - li != directoryLabelsList.end(); ++li) { - fout << " " << *li << "\n"; - lj_target_labels.append(*li); + for (std::string const& li : directoryLabelsList) { + fout << " " << li << "\n"; + lj_target_labels.append(li); } - for (std::vector<std::string>::const_iterator li = - cmakeDirectoryLabelsList.begin(); - li != cmakeDirectoryLabelsList.end(); ++li) { - fout << " " << *li << "\n"; - lj_target_labels.append(*li); + for (std::string const& li : cmakeDirectoryLabelsList) { + fout << " " << li << "\n"; + lj_target_labels.append(li); } // List the source files with any per-source labels. @@ -2882,9 +2830,8 @@ void cmGlobalGenerator::WriteSummary(cmGeneratorTarget* target) if (configs.empty()) { configs.push_back(""); } - for (std::vector<std::string>::const_iterator ci = configs.begin(); - ci != configs.end(); ++ci) { - target->GetSourceFiles(sources, *ci); + for (std::string const& c : configs) { + target->GetSourceFiles(sources, c); } std::vector<cmSourceFile*>::const_iterator sourcesEnd = cmRemoveDuplicates(sources); @@ -2899,10 +2846,9 @@ void cmGlobalGenerator::WriteSummary(cmGeneratorTarget* target) labels.clear(); Json::Value& lj_source_labels = lj_source["labels"] = Json::arrayValue; cmSystemTools::ExpandListArgument(svalue, labels); - for (std::vector<std::string>::const_iterator li = labels.begin(); - li != labels.end(); ++li) { - fout << " " << *li << "\n"; - lj_source_labels.append(*li); + for (std::string const& label : labels) { + fout << " " << label << "\n"; + lj_source_labels.append(label); } } } @@ -2920,11 +2866,11 @@ void cmGlobalGenerator::WriteSummary(cmGeneratorTarget* target) std::string cmGlobalGenerator::EscapeJSON(const std::string& s) { std::string result; - for (std::string::size_type i = 0; i < s.size(); ++i) { - if (s[i] == '"' || s[i] == '\\') { + for (char i : s) { + if (i == '"' || i == '\\') { result += '\\'; } - result += s[i]; + result += i; } return result; } @@ -2944,18 +2890,16 @@ cmGlobalGenerator::GetFilenameTargetDepends(cmSourceFile* sf) const void cmGlobalGenerator::CreateEvaluationSourceFiles( std::string const& config) const { - unsigned int i; - for (i = 0; i < this->LocalGenerators.size(); ++i) { - this->LocalGenerators[i]->CreateEvaluationFileOutputs(config); + for (cmLocalGenerator* localGen : this->LocalGenerators) { + localGen->CreateEvaluationFileOutputs(config); } } void cmGlobalGenerator::ProcessEvaluationFiles() { std::vector<std::string> generatedFiles; - unsigned int i; - for (i = 0; i < this->LocalGenerators.size(); ++i) { - this->LocalGenerators[i]->ProcessEvaluationFiles(generatedFiles); + for (cmLocalGenerator* localGen : this->LocalGenerators) { + localGen->ProcessEvaluationFiles(generatedFiles); } } @@ -2986,9 +2930,8 @@ bool cmGlobalGenerator::GenerateCPackPropertiesFile() cmGeneratedFileStream file(path.c_str()); file << "# CPack properties\n"; - for (cmake::InstalledFilesMap::const_iterator i = installedFiles.begin(); - i != installedFiles.end(); ++i) { - cmInstalledFile const& installedFile = i->second; + for (auto const& i : installedFiles) { + cmInstalledFile const& installedFile = i.second; cmCPackPropertiesGenerator cpackPropertiesGenerator(lg, installedFile, configs); diff --git a/Source/cmGlobalGenerator.h b/Source/cmGlobalGenerator.h index 7ff141d..18ca682 100644 --- a/Source/cmGlobalGenerator.h +++ b/Source/cmGlobalGenerator.h @@ -15,6 +15,7 @@ #include "cmCustomCommandLines.h" #include "cmExportSetMap.h" +#include "cmQtAutoGenDigest.h" #include "cmStateSnapshot.h" #include "cmSystemTools.h" #include "cmTarget.h" @@ -316,7 +317,7 @@ public: TargetDependSet const& GetTargetDirectDepends( const cmGeneratorTarget* target); - const std::map<std::string, std::vector<cmLocalGenerator*> >& GetProjectMap() + const std::map<std::string, std::vector<cmLocalGenerator*>>& GetProjectMap() const { return this->ProjectMap; @@ -422,7 +423,8 @@ protected: virtual bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const; - std::vector<const cmGeneratorTarget*> CreateQtAutoGeneratorsTargets(); + // Qt auto generators + cmQtAutoGenDigestUPV CreateQtAutoGeneratorsTargets(); std::string SelectMakeProgram(const std::string& makeProgram, const std::string& makeDefault = "") const; @@ -468,7 +470,7 @@ protected: std::vector<cmLocalGenerator*> LocalGenerators; cmMakefile* CurrentConfigureMakefile; // map from project name to vector of local generators in that project - std::map<std::string, std::vector<cmLocalGenerator*> > ProjectMap; + std::map<std::string, std::vector<cmLocalGenerator*>> ProjectMap; // Set of named installation components requested by the project. std::set<std::string> InstallComponents; @@ -580,7 +582,7 @@ private: // track targets to issue CMP0068 warning for. std::set<std::string> CMP0068WarnTargets; - mutable std::map<cmSourceFile*, std::set<cmGeneratorTarget const*> > + mutable std::map<cmSourceFile*, std::set<cmGeneratorTarget const*>> FilenameTargetDepends; #if defined(CMAKE_BUILD_WITH_CMAKE) diff --git a/Source/cmGlobalGeneratorFactory.h b/Source/cmGlobalGeneratorFactory.h index 125a9e2..4e3e770 100644 --- a/Source/cmGlobalGeneratorFactory.h +++ b/Source/cmGlobalGeneratorFactory.h @@ -45,7 +45,7 @@ class cmGlobalGeneratorSimpleFactory : public cmGlobalGeneratorFactory public: /** Create a GlobalGenerator */ cmGlobalGenerator* CreateGlobalGenerator(const std::string& name, - cmake* cm) const CM_OVERRIDE + cmake* cm) const override { if (name != T::GetActualName()) { return nullptr; @@ -54,22 +54,22 @@ public: } /** Get the documentation entry for this factory */ - void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE + void GetDocumentation(cmDocumentationEntry& entry) const override { T::GetDocumentation(entry); } /** Get the names of the current registered generators */ - void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE + void GetGenerators(std::vector<std::string>& names) const override { names.push_back(T::GetActualName()); } /** Determine whether or not this generator supports toolsets */ - bool SupportsToolset() const CM_OVERRIDE { return T::SupportsToolset(); } + bool SupportsToolset() const override { return T::SupportsToolset(); } /** Determine whether or not this generator supports platforms */ - bool SupportsPlatform() const CM_OVERRIDE { return T::SupportsPlatform(); } + bool SupportsPlatform() const override { return T::SupportsPlatform(); } }; #endif diff --git a/Source/cmGlobalGhsMultiGenerator.h b/Source/cmGlobalGhsMultiGenerator.h index 05a3a3c..7d4b2ba 100644 --- a/Source/cmGlobalGhsMultiGenerator.h +++ b/Source/cmGlobalGhsMultiGenerator.h @@ -57,7 +57,7 @@ public: /* * Determine what program to use for building the project. */ - bool FindMakeProgram(cmMakefile* mf) CM_OVERRIDE; + bool FindMakeProgram(cmMakefile* mf) override; cmGeneratedFileStream* GetBuildFileStream() { diff --git a/Source/cmGlobalKdevelopGenerator.cxx b/Source/cmGlobalKdevelopGenerator.cxx index 39ac73a..b1e630e 100644 --- a/Source/cmGlobalKdevelopGenerator.cxx +++ b/Source/cmGlobalKdevelopGenerator.cxx @@ -16,7 +16,6 @@ #include "cmsys/Directory.hxx" #include "cmsys/FStream.hxx" -#include <map> #include <set> #include <string.h> #include <utility> @@ -49,15 +48,13 @@ void cmGlobalKdevelopGenerator::Generate() { // for each sub project in the project create // a kdevelop project - for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator - it = this->GlobalGenerator->GetProjectMap().begin(); - it != this->GlobalGenerator->GetProjectMap().end(); ++it) { - std::string outputDir = it->second[0]->GetCurrentBinaryDirectory(); - std::string projectDir = it->second[0]->GetSourceDirectory(); - std::string projectName = it->second[0]->GetProjectName(); + for (auto const& it : this->GlobalGenerator->GetProjectMap()) { + std::string outputDir = it.second[0]->GetCurrentBinaryDirectory(); + std::string projectDir = it.second[0]->GetSourceDirectory(); + std::string projectName = it.second[0]->GetProjectName(); std::string cmakeFilePattern("CMakeLists.txt;*.cmake;"); std::string fileToOpen; - const std::vector<cmLocalGenerator*>& lgs = it->second; + const std::vector<cmLocalGenerator*>& lgs = it.second; // create the project.kdevelop.filelist file if (!this->CreateFilelistFile(lgs, outputDir, projectDir, projectName, cmakeFilePattern, fileToOpen)) { @@ -67,15 +64,12 @@ void cmGlobalKdevelopGenerator::Generate() // try to find the name of an executable so we have something to // run from kdevelop for now just pick the first executable found std::string executable; - for (std::vector<cmLocalGenerator*>::const_iterator lg = lgs.begin(); - lg != lgs.end(); lg++) { + for (cmLocalGenerator* lg : lgs) { std::vector<cmGeneratorTarget*> const& targets = - (*lg)->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator ti = - targets.begin(); - ti != targets.end(); ti++) { - if ((*ti)->GetType() == cmStateEnums::EXECUTABLE) { - executable = (*ti)->GetLocation(""); + lg->GetGeneratorTargets(); + for (cmGeneratorTarget* target : targets) { + if (target->GetType() == cmStateEnums::EXECUTABLE) { + executable = target->GetLocation(""); break; } } @@ -104,13 +98,11 @@ bool cmGlobalKdevelopGenerator::CreateFilelistFile( std::vector<std::string> const& hdrExts = this->GlobalGenerator->GetCMakeInstance()->GetHeaderExtensions(); - for (std::vector<cmLocalGenerator*>::const_iterator it = lgs.begin(); - it != lgs.end(); it++) { - cmMakefile* makefile = (*it)->GetMakefile(); + for (cmLocalGenerator* lg : lgs) { + cmMakefile* makefile = lg->GetMakefile(); const std::vector<std::string>& listFiles = makefile->GetListFiles(); - for (std::vector<std::string>::const_iterator lt = listFiles.begin(); - lt != listFiles.end(); lt++) { - tmp = *lt; + for (std::string const& listFile : listFiles) { + tmp = listFile; cmSystemTools::ReplaceString(tmp, projectDir.c_str(), ""); // make sure the file is part of this source tree if ((tmp[0] != '/') && @@ -128,17 +120,13 @@ bool cmGlobalKdevelopGenerator::CreateFilelistFile( } // get all sources - const std::vector<cmGeneratorTarget*>& targets = - (*it)->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator ti = targets.begin(); - ti != targets.end(); ti++) { + const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets(); + for (cmGeneratorTarget* gt : targets) { std::vector<cmSourceFile*> sources; - cmGeneratorTarget* gt = *ti; gt->GetSourceFiles(sources, gt->Target->GetMakefile()->GetSafeDefinition( "CMAKE_BUILD_TYPE")); - for (std::vector<cmSourceFile*>::const_iterator si = sources.begin(); - si != sources.end(); si++) { - tmp = (*si)->GetFullPath(); + for (cmSourceFile* sf : sources) { + tmp = sf->GetFullPath(); std::string headerBasename = cmSystemTools::GetFilenamePath(tmp); headerBasename += "/"; headerBasename += cmSystemTools::GetFilenameWithoutExtension(tmp); @@ -152,11 +140,10 @@ bool cmGlobalKdevelopGenerator::CreateFilelistFile( files.insert(tmp); // check if there's a matching header around - for (std::vector<std::string>::const_iterator ext = hdrExts.begin(); - ext != hdrExts.end(); ++ext) { + for (std::string const& hdrExt : hdrExts) { std::string hname = headerBasename; hname += "."; - hname += *ext; + hname += hdrExt; if (cmSystemTools::FileExists(hname.c_str())) { cmSystemTools::ReplaceString(hname, projectDir.c_str(), ""); files.insert(hname); @@ -165,9 +152,8 @@ bool cmGlobalKdevelopGenerator::CreateFilelistFile( } } } - for (std::vector<std::string>::const_iterator lt = listFiles.begin(); - lt != listFiles.end(); lt++) { - tmp = *lt; + for (std::string const& listFile : listFiles) { + tmp = listFile; cmSystemTools::ReplaceString(tmp, projectDir.c_str(), ""); if ((tmp[0] != '/') && (strstr(tmp.c_str(), cmake::GetCMakeFilesDirectoryPostSlash()) == @@ -201,10 +187,9 @@ bool cmGlobalKdevelopGenerator::CreateFilelistFile( } fileToOpen = ""; - for (std::set<std::string>::const_iterator it = files.begin(); - it != files.end(); it++) { + for (std::string const& file : files) { // get the full path to the file - tmp = cmSystemTools::CollapseFullPath(*it, projectDir.c_str()); + tmp = cmSystemTools::CollapseFullPath(file, projectDir.c_str()); // just select the first source file if (fileToOpen.empty()) { std::string ext = cmSystemTools::GetFilenameExtension(tmp); @@ -297,9 +282,8 @@ void cmGlobalKdevelopGenerator::MergeProjectFiles( return; } - for (std::vector<std::string>::const_iterator it = lines.begin(); - it != lines.end(); it++) { - const char* line = (*it).c_str(); + for (std::string const& l : lines) { + const char* line = l.c_str(); // skip these tags as they are always replaced if ((strstr(line, "<projectdirectory>") != nullptr) || (strstr(line, "<projectmanagement>") != nullptr) || @@ -311,7 +295,7 @@ void cmGlobalKdevelopGenerator::MergeProjectFiles( } // output the line from the file if it is not one of the above tags - fout << *it << "\n"; + fout << l << "\n"; // if this is the <general> tag output the stuff that goes in the // general tag if (strstr(line, "<general>")) { @@ -434,10 +418,8 @@ void cmGlobalKdevelopGenerator::CreateNewProjectFile( xml.EndElement(); // make xml.StartElement("blacklist"); - for (std::vector<std::string>::const_iterator dirIt = - this->Blacklist.begin(); - dirIt != this->Blacklist.end(); ++dirIt) { - xml.Element("path", *dirIt); + for (std::string const& dir : this->Blacklist) { + xml.Element("path", dir); } xml.EndElement(); diff --git a/Source/cmGlobalKdevelopGenerator.h b/Source/cmGlobalKdevelopGenerator.h index fd57782..d6c43f3 100644 --- a/Source/cmGlobalKdevelopGenerator.h +++ b/Source/cmGlobalKdevelopGenerator.h @@ -30,7 +30,7 @@ public: static cmExternalMakefileProjectGeneratorFactory* GetFactory(); - void Generate() CM_OVERRIDE; + void Generate() override; private: /*** Create the foo.kdevelop.filelist file, return false if it doesn't diff --git a/Source/cmGlobalNMakeMakefileGenerator.h b/Source/cmGlobalNMakeMakefileGenerator.h index 6eb2124..05ab904 100644 --- a/Source/cmGlobalNMakeMakefileGenerator.h +++ b/Source/cmGlobalNMakeMakefileGenerator.h @@ -27,7 +27,7 @@ public: static std::string GetActualName() { return "NMake Makefiles"; } /** Get encoding used by generator for makefile files */ - codecvt::Encoding GetMakefileEncoding() const CM_OVERRIDE + codecvt::Encoding GetMakefileEncoding() const override { return codecvt::ANSI; } diff --git a/Source/cmGlobalNinjaGenerator.cxx b/Source/cmGlobalNinjaGenerator.cxx index de3546b..d5531cb 100644 --- a/Source/cmGlobalNinjaGenerator.cxx +++ b/Source/cmGlobalNinjaGenerator.cxx @@ -10,6 +10,7 @@ #include <ctype.h> #include <functional> #include <iterator> +#include <memory> // IWYU pragma: keep #include <sstream> #include <stdio.h> @@ -32,7 +33,6 @@ #include "cmTarget.h" #include "cmTargetDepend.h" #include "cmVersion.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" class cmLinkLineComputer; @@ -90,12 +90,12 @@ std::string cmGlobalNinjaGenerator::EncodeRuleName(std::string const& name) // Ninja rule names must match "[a-zA-Z0-9_.-]+". Use ".xx" to encode // "." and all invalid characters as hexadecimal. std::string encoded; - for (std::string::const_iterator i = name.begin(); i != name.end(); ++i) { - if (isalnum(*i) || *i == '_' || *i == '-') { - encoded += *i; + for (char i : name) { + if (isalnum(i) || i == '_' || i == '-') { + encoded += i; } else { char buf[16]; - sprintf(buf, ".%02x", static_cast<unsigned int>(*i)); + sprintf(buf, ".%02x", static_cast<unsigned int>(i)); encoded += buf; } } @@ -177,26 +177,23 @@ void cmGlobalNinjaGenerator::WriteBuild( // TODO: Better formatting for when there are multiple input/output files. // Write explicit dependencies. - for (cmNinjaDeps::const_iterator i = explicitDeps.begin(); - i != explicitDeps.end(); ++i) { - arguments += " " + EncodeIdent(EncodePath(*i), os); + for (std::string const& explicitDep : explicitDeps) { + arguments += " " + EncodeIdent(EncodePath(explicitDep), os); } // Write implicit dependencies. if (!implicitDeps.empty()) { arguments += " |"; - for (cmNinjaDeps::const_iterator i = implicitDeps.begin(); - i != implicitDeps.end(); ++i) { - arguments += " " + EncodeIdent(EncodePath(*i), os); + for (std::string const& implicitDep : implicitDeps) { + arguments += " " + EncodeIdent(EncodePath(implicitDep), os); } } // Write order-only dependencies. if (!orderOnlyDeps.empty()) { arguments += " ||"; - for (cmNinjaDeps::const_iterator i = orderOnlyDeps.begin(); - i != orderOnlyDeps.end(); ++i) { - arguments += " " + EncodeIdent(EncodePath(*i), os); + for (std::string const& orderOnlyDep : orderOnlyDeps) { + arguments += " " + EncodeIdent(EncodePath(orderOnlyDep), os); } } @@ -206,18 +203,16 @@ void cmGlobalNinjaGenerator::WriteBuild( // Write outputs files. build += "build"; - for (cmNinjaDeps::const_iterator i = outputs.begin(); i != outputs.end(); - ++i) { - build += " " + EncodeIdent(EncodePath(*i), os); + for (std::string const& output : outputs) { + build += " " + EncodeIdent(EncodePath(output), os); if (this->ComputingUnknownDependencies) { - this->CombinedBuildOutputs.insert(*i); + this->CombinedBuildOutputs.insert(output); } } if (!implicitOuts.empty()) { build += " |"; - for (cmNinjaDeps::const_iterator i = implicitOuts.begin(); - i != implicitOuts.end(); ++i) { - build += " " + EncodeIdent(EncodePath(*i), os); + for (std::string const& implicitOut : implicitOuts) { + build += " " + EncodeIdent(EncodePath(implicitOut), os); } } build += ":"; @@ -227,20 +222,18 @@ void cmGlobalNinjaGenerator::WriteBuild( // Write the variables bound to this build statement. std::ostringstream variable_assignments; - for (cmNinjaVars::const_iterator i = variables.begin(); i != variables.end(); - ++i) { - cmGlobalNinjaGenerator::WriteVariable(variable_assignments, i->first, - i->second, "", 1); + for (auto const& variable : variables) { + cmGlobalNinjaGenerator::WriteVariable(variable_assignments, variable.first, + variable.second, "", 1); } // check if a response file rule should be used std::string buildstr = build; std::string assignments = variable_assignments.str(); - const std::string& args = arguments; bool useResponseFile = false; if (cmdLineLimit < 0 || (cmdLineLimit > 0 && - (args.size() + buildstr.size() + assignments.size() + 1000) > + (arguments.size() + buildstr.size() + assignments.size() + 1000) > static_cast<size_t>(cmdLineLimit))) { variable_assignments.str(std::string()); cmGlobalNinjaGenerator::WriteVariable(variable_assignments, "RSP_FILE", @@ -252,7 +245,7 @@ void cmGlobalNinjaGenerator::WriteBuild( *usedResponseFile = useResponseFile; } - os << buildstr << args << assignments; + os << buildstr << arguments << assignments; } void cmGlobalNinjaGenerator::WritePhonyBuild( @@ -311,8 +304,8 @@ void cmGlobalNinjaGenerator::WriteCustomCommandBuild( if (this->ComputingUnknownDependencies) { // we need to track every dependency that comes in, since we are trying // to find dependencies that are side effects of build commands - for (cmNinjaDeps::const_iterator i = deps.begin(); i != deps.end(); ++i) { - this->CombinedCustomCommandExplicitDependencies.insert(*i); + for (std::string const& dep : deps) { + this->CombinedCustomCommandExplicitDependencies.insert(dep); } } } @@ -465,9 +458,8 @@ void cmGlobalNinjaGenerator::WriteDefault(std::ostream& os, { cmGlobalNinjaGenerator::WriteComment(os, comment); os << "default"; - for (cmNinjaDeps::const_iterator i = targets.begin(); i != targets.end(); - ++i) { - os << " " << *i; + for (std::string const& target : targets) { + os << " " << target; } os << "\n"; } @@ -670,12 +662,11 @@ void cmGlobalNinjaGenerator::EnableLanguage( std::vector<std::string> const& langs, cmMakefile* mf, bool optional) { this->cmGlobalGenerator::EnableLanguage(langs, mf, optional); - for (std::vector<std::string>::const_iterator l = langs.begin(); - l != langs.end(); ++l) { - if (*l == "NONE") { + for (std::string const& l : langs) { + if (l == "NONE") { continue; } - this->ResolveLanguageCompiler(*l, mf, optional); + this->ResolveLanguageCompiler(l, mf, optional); } #ifdef _WIN32 if (strcmp(mf->GetSafeDefinition("CMAKE_C_SIMULATE_ID"), "MSVC") != 0 && @@ -870,18 +861,24 @@ static void EnsureTrailingSlash(std::string& path) #endif } -std::string cmGlobalNinjaGenerator::ConvertToNinjaPath( +std::string const& cmGlobalNinjaGenerator::ConvertToNinjaPath( const std::string& path) const { + auto const f = ConvertToNinjaPathCache.find(path); + if (f != ConvertToNinjaPathCache.end()) { + return f->second; + } + cmLocalNinjaGenerator* ng = static_cast<cmLocalNinjaGenerator*>(this->LocalGenerators[0]); - std::string convPath = ng->ConvertToRelativePath( - this->LocalGenerators[0]->GetState()->GetBinaryDirectory(), path); + const char* bin_dir = ng->GetState()->GetBinaryDirectory(); + std::string convPath = ng->ConvertToRelativePath(bin_dir, path); convPath = this->NinjaOutputPath(convPath); #ifdef _WIN32 std::replace(convPath.begin(), convPath.end(), '/', '\\'); #endif - return convPath; + return ConvertToNinjaPathCache.emplace(path, std::move(convPath)) + .first->second; } void cmGlobalNinjaGenerator::AddCXXCompileCommand( @@ -952,15 +949,13 @@ void cmGlobalNinjaGenerator::AddDependencyToAll(const std::string& input) void cmGlobalNinjaGenerator::WriteAssumedSourceDependencies() { - for (std::map<std::string, std::set<std::string> >::iterator i = - this->AssumedSourceDependencies.begin(); - i != this->AssumedSourceDependencies.end(); ++i) { + for (auto const& asd : this->AssumedSourceDependencies) { cmNinjaDeps deps; - std::copy(i->second.begin(), i->second.end(), std::back_inserter(deps)); + std::copy(asd.second.begin(), asd.second.end(), std::back_inserter(deps)); WriteCustomCommandBuild(/*command=*/"", /*description=*/"", "Assume dependencies for generated source file.", /*depfile*/ "", /*uses_terminal*/ false, - /*restat*/ true, cmNinjaDeps(1, i->first), deps); + /*restat*/ true, cmNinjaDeps(1, asd.first), deps); } } @@ -1025,22 +1020,20 @@ void cmGlobalNinjaGenerator::AppendTargetDepends( if (target->GetType() == cmStateEnums::GLOBAL_TARGET) { // These depend only on other CMake-provided targets, e.g. "all". std::set<std::string> const& utils = target->GetUtilities(); - for (std::set<std::string>::const_iterator i = utils.begin(); - i != utils.end(); ++i) { + for (std::string const& util : utils) { std::string d = target->GetLocalGenerator()->GetCurrentBinaryDirectory() + - std::string("/") + *i; + std::string("/") + util; outputs.push_back(this->ConvertToNinjaPath(d)); } } else { cmNinjaDeps outs; cmTargetDependSet const& targetDeps = this->GetTargetDirectDepends(target); - for (cmTargetDependSet::const_iterator i = targetDeps.begin(); - i != targetDeps.end(); ++i) { - if ((*i)->GetType() == cmStateEnums::INTERFACE_LIBRARY) { + for (cmTargetDepend const& targetDep : targetDeps) { + if (targetDep->GetType() == cmStateEnums::INTERFACE_LIBRARY) { continue; } - this->AppendTargetOutputs(*i, outs, depends); + this->AppendTargetOutputs(targetDep, outs, depends); } std::sort(outs.begin(), outs.end()); outputs.insert(outputs.end(), outs.begin(), outs.end()); @@ -1050,37 +1043,51 @@ void cmGlobalNinjaGenerator::AppendTargetDepends( void cmGlobalNinjaGenerator::AppendTargetDependsClosure( cmGeneratorTarget const* target, cmNinjaDeps& outputs) { - TargetDependsClosureMap::iterator i = - this->TargetDependsClosures.find(target); - if (i == this->TargetDependsClosures.end()) { - TargetDependsClosureMap::value_type e( - target, std::set<cmGeneratorTarget const*>()); - i = this->TargetDependsClosures.insert(e).first; - this->ComputeTargetDependsClosure(target, i->second); - } - std::set<cmGeneratorTarget const*> const& targets = i->second; - cmNinjaDeps outs; - for (std::set<cmGeneratorTarget const*>::const_iterator ti = targets.begin(); - ti != targets.end(); ++ti) { - this->AppendTargetOutputs(*ti, outs); - } - std::sort(outs.begin(), outs.end()); + cmNinjaOuts outs; + this->AppendTargetDependsClosure(target, outs, true); + outputs.insert(outputs.end(), outs.begin(), outs.end()); } -void cmGlobalNinjaGenerator::ComputeTargetDependsClosure( - cmGeneratorTarget const* target, std::set<cmGeneratorTarget const*>& depends) +void cmGlobalNinjaGenerator::AppendTargetDependsClosure( + cmGeneratorTarget const* target, cmNinjaOuts& outputs, bool omit_self) { - cmTargetDependSet const& targetDeps = this->GetTargetDirectDepends(target); - for (cmTargetDependSet::const_iterator i = targetDeps.begin(); - i != targetDeps.end(); ++i) { - if ((*i)->GetType() == cmStateEnums::INTERFACE_LIBRARY) { - continue; - } - if (depends.insert(*i).second) { - this->ComputeTargetDependsClosure(*i, depends); + + // try to locate the target in the cache + auto find = this->TargetDependsClosures.lower_bound(target); + + if (find == this->TargetDependsClosures.end() || find->first != target) { + // We now calculate the closure outputs by inspecting the dependent + // targets recursively. + // For that we have to distinguish between a local result set that is only + // relevant for filling the cache entries properly isolated and a global + // result set that is relevant for the result of the top level call to + // AppendTargetDependsClosure. + auto const& targetDeps = this->GetTargetDirectDepends(target); + cmNinjaOuts this_outs; // this will be the new cache entry + + for (auto const& dep_target : targetDeps) { + if (dep_target->GetType() == cmStateEnums::INTERFACE_LIBRARY) { + continue; + } + + // Collect the dependent targets for _this_ target + this->AppendTargetDependsClosure(dep_target, this_outs, false); } + find = this->TargetDependsClosures.emplace_hint(find, target, + std::move(this_outs)); } + + // now fill the outputs of the final result from the newly generated cache + // entry + outputs.insert(find->second.begin(), find->second.end()); + + // finally generate the outputs of the target itself, if applicable + cmNinjaDeps outs; + if (!omit_self) { + this->AppendTargetOutputs(target, outs); + } + outputs.insert(outs.begin(), outs.end()); } void cmGlobalNinjaGenerator::AddTargetAlias(const std::string& alias, @@ -1091,8 +1098,8 @@ void cmGlobalNinjaGenerator::AddTargetAlias(const std::string& alias, this->AppendTargetOutputs(target, outputs); // Mark the target's outputs as ambiguous to ensure that no other target uses // the output as an alias. - for (cmNinjaDeps::iterator i = outputs.begin(); i != outputs.end(); ++i) { - TargetAliases[*i] = nullptr; + for (std::string const& output : outputs) { + TargetAliases[output] = nullptr; } // Insert the alias into the map. If the alias was already present in the @@ -1109,17 +1116,16 @@ void cmGlobalNinjaGenerator::WriteTargetAliases(std::ostream& os) cmGlobalNinjaGenerator::WriteDivider(os); os << "# Target aliases.\n\n"; - for (TargetAliasMap::const_iterator i = TargetAliases.begin(); - i != TargetAliases.end(); ++i) { + for (auto const& ta : TargetAliases) { // Don't write ambiguous aliases. - if (!i->second) { + if (!ta.second) { continue; } cmNinjaDeps deps; - this->AppendTargetOutputs(i->second, deps); + this->AppendTargetOutputs(ta.second, deps); - this->WritePhonyBuild(os, "", cmNinjaDeps(1, i->first), deps); + this->WritePhonyBuild(os, "", cmNinjaDeps(1, ta.first), deps); } } @@ -1129,19 +1135,13 @@ void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os) os << "# Folder targets.\n\n"; std::map<std::string, cmNinjaDeps> targetsPerFolder; - for (std::vector<cmLocalGenerator*>::const_iterator lgi = - this->LocalGenerators.begin(); - lgi != this->LocalGenerators.end(); ++lgi) { - cmLocalGenerator const* lg = *lgi; + for (cmLocalGenerator const* lg : this->LocalGenerators) { const std::string currentBinaryFolder( lg->GetStateSnapshot().GetDirectory().GetCurrentBinary()); // The directory-level rule should depend on the target-level rules // for all targets in the directory. targetsPerFolder[currentBinaryFolder] = cmNinjaDeps(); - for (std::vector<cmGeneratorTarget*>::const_iterator ti = - lg->GetGeneratorTargets().begin(); - ti != lg->GetGeneratorTargets().end(); ++ti) { - cmGeneratorTarget const* gt = *ti; + for (auto gt : lg->GetGeneratorTargets()) { cmStateEnums::TargetType const type = gt->GetType(); if ((type == cmStateEnums::EXECUTABLE || type == cmStateEnums::STATIC_LIBRARY || @@ -1158,11 +1158,9 @@ void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os) // rules of the subdirectories. std::vector<cmStateSnapshot> const& children = lg->GetStateSnapshot().GetChildren(); - for (std::vector<cmStateSnapshot>::const_iterator stateIt = - children.begin(); - stateIt != children.end(); ++stateIt) { + for (cmStateSnapshot const& state : children) { std::string const currentBinaryDir = - stateIt->GetDirectory().GetCurrentBinary(); + state.GetDirectory().GetCurrentBinary(); targetsPerFolder[currentBinaryFolder].push_back( this->ConvertToNinjaPath(currentBinaryDir + "/all")); @@ -1171,11 +1169,9 @@ void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os) std::string const rootBinaryDir = this->LocalGenerators[0]->GetBinaryDirectory(); - for (std::map<std::string, cmNinjaDeps>::const_iterator it = - targetsPerFolder.begin(); - it != targetsPerFolder.end(); ++it) { + for (auto const& it : targetsPerFolder) { cmGlobalNinjaGenerator::WriteDivider(os); - std::string const& currentBinaryDir = it->first; + std::string const& currentBinaryDir = it.first; // Do not generate a rule for the root binary dir. if (rootBinaryDir.length() >= currentBinaryDir.length()) { @@ -1186,7 +1182,7 @@ void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os) cmNinjaDeps output(1); output.push_back(this->ConvertToNinjaPath(currentBinaryDir + "/all")); - this->WritePhonyBuild(os, comment, output, it->second); + this->WritePhonyBuild(os, comment, output, it.second); } } @@ -1220,50 +1216,40 @@ void cmGlobalNinjaGenerator::WriteUnknownExplicitDependencies(std::ostream& os) // get the list of files that cmake itself has generated as a // product of configuration. - for (std::vector<cmLocalGenerator*>::const_iterator i = - this->LocalGenerators.begin(); - i != this->LocalGenerators.end(); ++i) { + for (cmLocalGenerator* lg : this->LocalGenerators) { // get the vector of files created by this makefile and convert them // to ninja paths, which are all relative in respect to the build directory const std::vector<std::string>& files = - (*i)->GetMakefile()->GetOutputFiles(); - typedef std::vector<std::string>::const_iterator vect_it; - for (vect_it j = files.begin(); j != files.end(); ++j) { - knownDependencies.insert(this->ConvertToNinjaPath(*j)); + lg->GetMakefile()->GetOutputFiles(); + for (std::string const& file : files) { + knownDependencies.insert(this->ConvertToNinjaPath(file)); } // get list files which are implicit dependencies as well and will be phony // for rebuild manifest - std::vector<std::string> const& lf = (*i)->GetMakefile()->GetListFiles(); - typedef std::vector<std::string>::const_iterator vect_it; - for (vect_it j = lf.begin(); j != lf.end(); ++j) { - knownDependencies.insert(this->ConvertToNinjaPath(*j)); + std::vector<std::string> const& lf = lg->GetMakefile()->GetListFiles(); + for (std::string const& j : lf) { + knownDependencies.insert(this->ConvertToNinjaPath(j)); } std::vector<cmGeneratorExpressionEvaluationFile*> const& ef = - (*i)->GetMakefile()->GetEvaluationFiles(); - for (std::vector<cmGeneratorExpressionEvaluationFile*>::const_iterator li = - ef.begin(); - li != ef.end(); ++li) { + lg->GetMakefile()->GetEvaluationFiles(); + for (cmGeneratorExpressionEvaluationFile* li : ef) { // get all the files created by generator expressions and convert them // to ninja paths - std::vector<std::string> evaluationFiles = (*li)->GetFiles(); - for (vect_it j = evaluationFiles.begin(); j != evaluationFiles.end(); - ++j) { - knownDependencies.insert(this->ConvertToNinjaPath(*j)); + std::vector<std::string> evaluationFiles = li->GetFiles(); + for (std::string const& evaluationFile : evaluationFiles) { + knownDependencies.insert(this->ConvertToNinjaPath(evaluationFile)); } } } knownDependencies.insert(this->CMakeCacheFile); - for (TargetAliasMap::const_iterator i = this->TargetAliases.begin(); - i != this->TargetAliases.end(); ++i) { - knownDependencies.insert(this->ConvertToNinjaPath(i->first)); + for (auto const& ta : this->TargetAliases) { + knownDependencies.insert(this->ConvertToNinjaPath(ta.first)); } // remove all source files we know will exist. - typedef std::map<std::string, std::set<std::string> >::const_iterator map_it; - for (map_it i = this->AssumedSourceDependencies.begin(); - i != this->AssumedSourceDependencies.end(); ++i) { - knownDependencies.insert(this->ConvertToNinjaPath(i->first)); + for (auto const& i : this->AssumedSourceDependencies) { + knownDependencies.insert(this->ConvertToNinjaPath(i.first)); } // now we difference with CombinedCustomCommandExplicitDependencies to find @@ -1285,20 +1271,18 @@ void cmGlobalNinjaGenerator::WriteUnknownExplicitDependencies(std::ostream& os) bool const inSourceBuild = (rootBuildDirectory == this->GetCMakeInstance()->GetHomeDirectory()); std::vector<std::string> warnExplicitDepends; - for (std::vector<std::string>::const_iterator i = - unknownExplicitDepends.begin(); - i != unknownExplicitDepends.end(); ++i) { + for (std::string const& i : unknownExplicitDepends) { // verify the file is in the build directory std::string const absDepPath = - cmSystemTools::CollapseFullPath(*i, rootBuildDirectory.c_str()); + cmSystemTools::CollapseFullPath(i, rootBuildDirectory.c_str()); bool const inBuildDir = cmSystemTools::IsSubDirectory(absDepPath, rootBuildDirectory); if (inBuildDir) { - cmNinjaDeps deps(1, *i); + cmNinjaDeps deps(1, i); this->WritePhonyBuild(os, "", deps, cmNinjaDeps()); if (this->PolicyCMP0058 == cmPolicies::WARN && !inSourceBuild && warnExplicitDepends.size() < 10) { - warnExplicitDepends.push_back(*i); + warnExplicitDepends.push_back(i); } } } @@ -1373,13 +1357,11 @@ void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os) /*generator=*/true); cmNinjaDeps implicitDeps; - for (std::vector<cmLocalGenerator*>::const_iterator i = - this->LocalGenerators.begin(); - i != this->LocalGenerators.end(); ++i) { - std::vector<std::string> const& lf = (*i)->GetMakefile()->GetListFiles(); - for (std::vector<std::string>::const_iterator fi = lf.begin(); - fi != lf.end(); ++fi) { - implicitDeps.push_back(this->ConvertToNinjaPath(*fi)); + for (cmLocalGenerator* localGen : this->LocalGenerators) { + std::vector<std::string> const& lf = + localGen->GetMakefile()->GetListFiles(); + for (std::string const& fi : lf) { + implicitDeps.push_back(this->ConvertToNinjaPath(fi)); } } implicitDeps.push_back(this->CMakeCacheFile); @@ -1636,9 +1618,8 @@ int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg, Json::Value const& tdi_include_dirs = tdi["include-dirs"]; if (tdi_include_dirs.isArray()) { - for (Json::Value::const_iterator i = tdi_include_dirs.begin(); - i != tdi_include_dirs.end(); ++i) { - includes.push_back(i->asString()); + for (auto const& tdi_include_dir : tdi_include_dirs) { + includes.push_back(tdi_include_dir.asString()); } } } @@ -1659,9 +1640,8 @@ int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg, { cmGeneratedFileStream depfile(arg_dep.c_str()); depfile << cmSystemTools::ConvertToUnixOutputPath(arg_pp) << ":"; - for (std::set<std::string>::iterator i = info.Includes.begin(); - i != info.Includes.end(); ++i) { - depfile << " \\\n " << cmSystemTools::ConvertToUnixOutputPath(*i); + for (std::string const& include : info.Includes) { + depfile << " \\\n " << cmSystemTools::ConvertToUnixOutputPath(include); } depfile << "\n"; } @@ -1670,16 +1650,14 @@ int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg, ddi["object"] = arg_obj; Json::Value& ddi_provides = ddi["provides"] = Json::arrayValue; - for (std::set<std::string>::iterator i = info.Provides.begin(); - i != info.Provides.end(); ++i) { - ddi_provides.append(*i); + for (std::string const& provide : info.Provides) { + ddi_provides.append(provide); } Json::Value& ddi_requires = ddi["requires"] = Json::arrayValue; - for (std::set<std::string>::iterator i = info.Requires.begin(); - i != info.Requires.end(); ++i) { + for (std::string const& r : info.Requires) { // Require modules not provided in the same source. - if (!info.Provides.count(*i)) { - ddi_requires.append(*i); + if (!info.Provides.count(r)) { + ddi_requires.append(r); } } @@ -1714,24 +1692,24 @@ bool cmGlobalNinjaGenerator::WriteDyndepFile( snapshot.GetDirectory().SetCurrentBinary(dir_cur_bld); snapshot.GetDirectory().SetRelativePathTopSource(dir_top_src.c_str()); snapshot.GetDirectory().SetRelativePathTopBinary(dir_top_bld.c_str()); - CM_AUTO_PTR<cmMakefile> mfd(new cmMakefile(this, snapshot)); - CM_AUTO_PTR<cmLocalNinjaGenerator> lgd(static_cast<cmLocalNinjaGenerator*>( - this->CreateLocalGenerator(mfd.get()))); + auto mfd = cm::make_unique<cmMakefile>(this, snapshot); + std::unique_ptr<cmLocalNinjaGenerator> lgd( + static_cast<cmLocalNinjaGenerator*>( + this->CreateLocalGenerator(mfd.get()))); this->Makefiles.push_back(mfd.release()); this->LocalGenerators.push_back(lgd.release()); } std::vector<cmFortranObjectInfo> objects; - for (std::vector<std::string>::const_iterator ddii = arg_ddis.begin(); - ddii != arg_ddis.end(); ++ddii) { + for (std::string const& arg_ddi : arg_ddis) { // Load the ddi file and compute the module file paths it provides. Json::Value ddio; Json::Value const& ddi = ddio; - cmsys::ifstream ddif(ddii->c_str(), std::ios::in | std::ios::binary); + cmsys::ifstream ddif(arg_ddi.c_str(), std::ios::in | std::ios::binary); Json::Reader reader; if (!reader.parse(ddif, ddio, false)) { cmSystemTools::Error("-E cmake_ninja_dyndep failed to parse ", - ddii->c_str(), + arg_ddi.c_str(), reader.getFormattedErrorMessages().c_str()); return false; } @@ -1740,16 +1718,14 @@ bool cmGlobalNinjaGenerator::WriteDyndepFile( info.Object = ddi["object"].asString(); Json::Value const& ddi_provides = ddi["provides"]; if (ddi_provides.isArray()) { - for (Json::Value::const_iterator i = ddi_provides.begin(); - i != ddi_provides.end(); ++i) { - info.Provides.push_back(i->asString()); + for (auto const& ddi_provide : ddi_provides) { + info.Provides.push_back(ddi_provide.asString()); } } Json::Value const& ddi_requires = ddi["requires"]; if (ddi_requires.isArray()) { - for (Json::Value::const_iterator i = ddi_requires.begin(); - i != ddi_requires.end(); ++i) { - info.Requires.push_back(i->asString()); + for (auto const& ddi_require : ddi_requires) { + info.Requires.push_back(ddi_require.asString()); } } objects.push_back(info); @@ -1759,16 +1735,14 @@ bool cmGlobalNinjaGenerator::WriteDyndepFile( std::map<std::string, std::string> mod_files; // Populate the module map with those provided by linked targets first. - for (std::vector<std::string>::const_iterator di = - linked_target_dirs.begin(); - di != linked_target_dirs.end(); ++di) { - std::string const ltmn = *di + "/FortranModules.json"; + for (std::string const& linked_target_dir : linked_target_dirs) { + std::string const ltmn = linked_target_dir + "/FortranModules.json"; Json::Value ltm; cmsys::ifstream ltmf(ltmn.c_str(), std::ios::in | std::ios::binary); Json::Reader reader; if (ltmf && !reader.parse(ltmf, ltm, false)) { cmSystemTools::Error("-E cmake_ninja_dyndep failed to parse ", - di->c_str(), + linked_target_dir.c_str(), reader.getFormattedErrorMessages().c_str()); return false; } @@ -1783,21 +1757,18 @@ bool cmGlobalNinjaGenerator::WriteDyndepFile( // We do this after loading the modules provided by linked targets // in case we have one of the same name that must be preferred. Json::Value tm = Json::objectValue; - for (std::vector<cmFortranObjectInfo>::iterator oi = objects.begin(); - oi != objects.end(); ++oi) { - for (std::vector<std::string>::iterator i = oi->Provides.begin(); - i != oi->Provides.end(); ++i) { - std::string const mod = module_dir + *i + ".mod"; - mod_files[*i] = mod; - tm[*i] = mod; + for (cmFortranObjectInfo const& object : objects) { + for (std::string const& p : object.Provides) { + std::string const mod = module_dir + p + ".mod"; + mod_files[p] = mod; + tm[p] = mod; } } cmGeneratedFileStream ddf(arg_dd.c_str()); ddf << "ninja_dyndep_version = 1.0\n"; - for (std::vector<cmFortranObjectInfo>::iterator oi = objects.begin(); - oi != objects.end(); ++oi) { + for (cmFortranObjectInfo const& object : objects) { std::string const ddComment; std::string const ddRule = "dyndep"; cmNinjaDeps ddOutputs; @@ -1807,19 +1778,17 @@ bool cmGlobalNinjaGenerator::WriteDyndepFile( cmNinjaDeps ddOrderOnlyDeps; cmNinjaVars ddVars; - ddOutputs.push_back(oi->Object); - for (std::vector<std::string>::iterator i = oi->Provides.begin(); - i != oi->Provides.end(); ++i) { - ddImplicitOuts.push_back(this->ConvertToNinjaPath(mod_files[*i])); + ddOutputs.push_back(object.Object); + for (std::string const& p : object.Provides) { + ddImplicitOuts.push_back(this->ConvertToNinjaPath(mod_files[p])); } - for (std::vector<std::string>::iterator i = oi->Requires.begin(); - i != oi->Requires.end(); ++i) { - std::map<std::string, std::string>::iterator m = mod_files.find(*i); + for (std::string const& r : object.Requires) { + std::map<std::string, std::string>::iterator m = mod_files.find(r); if (m != mod_files.end()) { ddImplicitDeps.push_back(this->ConvertToNinjaPath(m->second)); } } - if (!oi->Provides.empty()) { + if (!object.Provides.empty()) { ddVars["restat"] = "1"; } @@ -1846,9 +1815,7 @@ int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg, std::string arg_dd; std::string arg_tdi; std::vector<std::string> arg_ddis; - for (std::vector<std::string>::const_iterator a = arg_full.begin(); - a != arg_full.end(); ++a) { - std::string const& arg = *a; + for (std::string const& arg : arg_full) { if (cmHasLiteralPrefix(arg, "--tdi=")) { arg_tdi = arg.substr(6); } else if (cmHasLiteralPrefix(arg, "--dd=")) { @@ -1895,16 +1862,15 @@ int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg, std::vector<std::string> linked_target_dirs; Json::Value const& tdi_linked_target_dirs = tdi["linked-target-dirs"]; if (tdi_linked_target_dirs.isArray()) { - for (Json::Value::const_iterator i = tdi_linked_target_dirs.begin(); - i != tdi_linked_target_dirs.end(); ++i) { - linked_target_dirs.push_back(i->asString()); + for (auto const& tdi_linked_target_dir : tdi_linked_target_dirs) { + linked_target_dirs.push_back(tdi_linked_target_dir.asString()); } } cmake cm(cmake::RoleInternal); cm.SetHomeDirectory(dir_top_src); cm.SetHomeOutputDirectory(dir_top_bld); - CM_AUTO_PTR<cmGlobalNinjaGenerator> ggd( + std::unique_ptr<cmGlobalNinjaGenerator> ggd( static_cast<cmGlobalNinjaGenerator*>(cm.CreateGlobalGenerator("Ninja"))); if (!ggd.get() || !ggd->WriteDyndepFile(dir_top_src, dir_top_bld, dir_cur_src, dir_cur_bld, diff --git a/Source/cmGlobalNinjaGenerator.h b/Source/cmGlobalNinjaGenerator.h index 87affdc..7f80d08 100644 --- a/Source/cmGlobalNinjaGenerator.h +++ b/Source/cmGlobalNinjaGenerator.h @@ -9,6 +9,7 @@ #include <map> #include <set> #include <string> +#include <unordered_map> #include <utility> #include <vector> @@ -78,7 +79,7 @@ public: cmLinkLineComputer* CreateLinkLineComputer( cmOutputConverter* outputConverter, - cmStateDirectory const& stateDir) const CM_OVERRIDE; + cmStateDirectory const& stateDir) const override; /** * Write the given @a comment to the output stream @a os. It @@ -98,7 +99,7 @@ public: */ static bool SupportsPlatform() { return false; } - bool IsIPOSupported() const CM_OVERRIDE { return true; } + bool IsIPOSupported() const override { return true; } /** * Write a build statement to @a os with the @a comment using @@ -183,11 +184,11 @@ public: return new cmGlobalGeneratorSimpleFactory<cmGlobalNinjaGenerator>(); } - ~cmGlobalNinjaGenerator() CM_OVERRIDE {} + ~cmGlobalNinjaGenerator() override {} - cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) CM_OVERRIDE; + cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) override; - std::string GetName() const CM_OVERRIDE + std::string GetName() const override { return cmGlobalNinjaGenerator::GetActualName(); } @@ -195,12 +196,12 @@ public: static std::string GetActualName() { return "Ninja"; } /** Get encoding used by generator for ninja files */ - codecvt::Encoding GetMakefileEncoding() const CM_OVERRIDE; + codecvt::Encoding GetMakefileEncoding() const override; static void GetDocumentation(cmDocumentationEntry& entry); void EnableLanguage(std::vector<std::string> const& languages, - cmMakefile* mf, bool optional) CM_OVERRIDE; + cmMakefile* mf, bool optional) override; void GenerateBuildCommand(std::vector<std::string>& makeCommand, const std::string& makeProgram, @@ -209,34 +210,31 @@ public: const std::string& targetName, const std::string& config, bool fast, bool verbose, std::vector<std::string> const& makeOptions = - std::vector<std::string>()) CM_OVERRIDE; + std::vector<std::string>()) override; // Setup target names - const char* GetAllTargetName() const CM_OVERRIDE { return "all"; } - const char* GetInstallTargetName() const CM_OVERRIDE { return "install"; } - const char* GetInstallLocalTargetName() const CM_OVERRIDE + const char* GetAllTargetName() const override { return "all"; } + const char* GetInstallTargetName() const override { return "install"; } + const char* GetInstallLocalTargetName() const override { return "install/local"; } - const char* GetInstallStripTargetName() const CM_OVERRIDE + const char* GetInstallStripTargetName() const override { return "install/strip"; } - const char* GetTestTargetName() const CM_OVERRIDE { return "test"; } - const char* GetPackageTargetName() const CM_OVERRIDE { return "package"; } - const char* GetPackageSourceTargetName() const CM_OVERRIDE + const char* GetTestTargetName() const override { return "test"; } + const char* GetPackageTargetName() const override { return "package"; } + const char* GetPackageSourceTargetName() const override { return "package_source"; } - const char* GetEditCacheTargetName() const CM_OVERRIDE - { - return "edit_cache"; - } - const char* GetRebuildCacheTargetName() const CM_OVERRIDE + const char* GetEditCacheTargetName() const override { return "edit_cache"; } + const char* GetRebuildCacheTargetName() const override { return "rebuild_cache"; } - const char* GetCleanTargetName() const CM_OVERRIDE { return "clean"; } + const char* GetCleanTargetName() const override { return "clean"; } cmGeneratedFileStream* GetBuildFileStream() const { @@ -248,7 +246,7 @@ public: return this->RulesFileStream; } - std::string ConvertToNinjaPath(const std::string& path) const; + std::string const& ConvertToNinjaPath(const std::string& path) const; struct MapToNinjaPathImpl { @@ -323,6 +321,8 @@ public: cmNinjaTargetDepends depends = DependOnTargetArtifact); void AppendTargetDependsClosure(cmGeneratorTarget const* target, cmNinjaDeps& outputs); + void AppendTargetDependsClosure(cmGeneratorTarget const* target, + cmNinjaOuts& outputs, bool omit_self); void AddDependencyToAll(cmGeneratorTarget* target); void AddDependencyToAll(const std::string& input); @@ -340,7 +340,7 @@ public: void AddTargetAlias(const std::string& alias, cmGeneratorTarget* target); - void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const CM_OVERRIDE; + void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const override; // Ninja generator uses 'deps' and 'msvc_deps_prefix' introduced in 1.3 static std::string RequiredNinjaVersion() { return "1.3"; } @@ -363,16 +363,16 @@ public: std::vector<std::string> const& linked_target_dirs); protected: - void Generate() CM_OVERRIDE; + void Generate() override; - bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const CM_OVERRIDE { return true; } + bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const override { return true; } private: - std::string GetEditCacheCommand() const CM_OVERRIDE; - bool FindMakeProgram(cmMakefile* mf) CM_OVERRIDE; + std::string GetEditCacheCommand() const override; + bool FindMakeProgram(cmMakefile* mf) override; void CheckNinjaFeatures(); bool CheckLanguages(std::vector<std::string> const& languages, - cmMakefile* mf) const CM_OVERRIDE; + cmMakefile* mf) const override; bool CheckFortran(cmMakefile* mf) const; void OpenBuildFileStream(); @@ -446,15 +446,15 @@ private: std::set<std::string> CombinedBuildOutputs; /// The mapping from source file to assumed dependencies. - std::map<std::string, std::set<std::string> > AssumedSourceDependencies; + std::map<std::string, std::set<std::string>> AssumedSourceDependencies; typedef std::map<std::string, cmGeneratorTarget*> TargetAliasMap; TargetAliasMap TargetAliases; - typedef std::map<cmGeneratorTarget const*, - std::set<cmGeneratorTarget const*> > - TargetDependsClosureMap; - TargetDependsClosureMap TargetDependsClosures; + std::map<cmGeneratorTarget const*, cmNinjaOuts> TargetDependsClosures; + + /// the local cache for calls to ConvertToNinjaPath + mutable std::unordered_map<std::string, std::string> ConvertToNinjaPathCache; std::string NinjaCommand; std::string NinjaVersion; diff --git a/Source/cmGlobalUnixMakefileGenerator3.cxx b/Source/cmGlobalUnixMakefileGenerator3.cxx index 05c9ce0..be40126 100644 --- a/Source/cmGlobalUnixMakefileGenerator3.cxx +++ b/Source/cmGlobalUnixMakefileGenerator3.cxx @@ -50,12 +50,11 @@ void cmGlobalUnixMakefileGenerator3::EnableLanguage( std::vector<std::string> const& languages, cmMakefile* mf, bool optional) { this->cmGlobalGenerator::EnableLanguage(languages, mf, optional); - for (std::vector<std::string>::const_iterator l = languages.begin(); - l != languages.end(); ++l) { - if (*l == "NONE") { + for (std::string const& language : languages) { + if (language == "NONE") { continue; } - this->ResolveLanguageCompiler(*l, mf, optional); + this->ResolveLanguageCompiler(language, mf, optional); } } @@ -130,9 +129,8 @@ void cmGlobalUnixMakefileGenerator3::Generate() // initialize progress unsigned long total = 0; - for (ProgressMapType::const_iterator pmi = this->ProgressMap.begin(); - pmi != this->ProgressMap.end(); ++pmi) { - total += pmi->second.NumberOfActions; + for (auto const& pmi : this->ProgressMap) { + total += pmi.second.NumberOfActions; } // write each target's progress.make this loop is done twice. Bascially the @@ -143,12 +141,10 @@ void cmGlobalUnixMakefileGenerator3::Generate() // well. This is because the all targets require more information that is // computed in the first loop. unsigned long current = 0; - for (ProgressMapType::iterator pmi = this->ProgressMap.begin(); - pmi != this->ProgressMap.end(); ++pmi) { - pmi->second.WriteProgressVariables(total, current); + for (auto& pmi : this->ProgressMap) { + pmi.second.WriteProgressVariables(total, current); } - for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) { - cmLocalGenerator* lg = this->LocalGenerators[i]; + for (cmLocalGenerator* lg : this->LocalGenerators) { std::string markFileName = lg->GetCurrentBinaryDirectory(); markFileName += "/"; markFileName += cmake::GetCMakeFilesDirectory(); @@ -234,7 +230,7 @@ void cmGlobalUnixMakefileGenerator3::WriteMainMakefile2() // The all and preinstall rules might never have any dependencies // added to them. - if (this->EmptyRuleHackDepends != "") { + if (!this->EmptyRuleHackDepends.empty()) { depends.push_back(this->EmptyRuleHackDepends); } @@ -250,9 +246,8 @@ void cmGlobalUnixMakefileGenerator3::WriteMainMakefile2() lg->WriteSpecialTargetsTop(makefileStream); // write the target convenience rules - unsigned int i; - for (i = 0; i < this->LocalGenerators.size(); ++i) { - lg = static_cast<cmLocalUnixMakefileGenerator3*>(this->LocalGenerators[i]); + for (cmLocalGenerator* localGen : this->LocalGenerators) { + lg = static_cast<cmLocalUnixMakefileGenerator3*>(localGen); this->WriteConvenienceRules2(makefileStream, lg); } @@ -292,8 +287,8 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile() // for each cmMakefile get its list of dependencies std::vector<std::string> lfiles; - for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) { - lg = static_cast<cmLocalUnixMakefileGenerator3*>(this->LocalGenerators[i]); + for (cmLocalGenerator* localGen : this->LocalGenerators) { + lg = static_cast<cmLocalUnixMakefileGenerator3*>(localGen); // Get the list of files contributing to this generation step. lfiles.insert(lfiles.end(), lg->GetMakefile()->GetListFiles().begin(), @@ -316,9 +311,8 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile() << "# The top level Makefile was generated from the following files:\n" << "set(CMAKE_MAKEFILE_DEPENDS\n" << " \"CMakeCache.txt\"\n"; - for (std::vector<std::string>::const_iterator i = lfiles.begin(); - i != lfiles.end(); ++i) { - cmakefileStream << " \"" << lg->ConvertToRelativePath(currentBinDir, *i) + for (std::string const& f : lfiles) { + cmakefileStream << " \"" << lg->ConvertToRelativePath(currentBinDir, f) << "\"\n"; } cmakefileStream << " )\n\n"; @@ -346,17 +340,15 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile() << "set(CMAKE_MAKEFILE_PRODUCTS\n"; const std::vector<std::string>& outfiles = lg->GetMakefile()->GetOutputFiles(); - for (std::vector<std::string>::const_iterator k = outfiles.begin(); - k != outfiles.end(); ++k) { - cmakefileStream << " \"" << lg->ConvertToRelativePath(binDir, *k) + for (std::string const& outfile : outfiles) { + cmakefileStream << " \"" << lg->ConvertToRelativePath(binDir, outfile) << "\"\n"; } // add in all the directory information files std::string tmpStr; - for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) { - lg = - static_cast<cmLocalUnixMakefileGenerator3*>(this->LocalGenerators[i]); + for (cmLocalGenerator* localGen : this->LocalGenerators) { + lg = static_cast<cmLocalUnixMakefileGenerator3*>(localGen); tmpStr = lg->GetCurrentBinaryDirectory(); tmpStr += cmake::GetCMakeFilesDirectory(); tmpStr += "/CMakeDirectoryInformation.cmake"; @@ -379,19 +371,18 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefileLanguageRules( // now list all the target info files cmakefileStream << "# Dependency information for all targets:\n"; cmakefileStream << "set(CMAKE_DEPEND_INFO_FILES\n"; - for (unsigned int i = 0; i < lGenerators.size(); ++i) { - lg = static_cast<cmLocalUnixMakefileGenerator3*>(lGenerators[i]); + for (cmLocalGenerator* lGenerator : lGenerators) { + lg = static_cast<cmLocalUnixMakefileGenerator3*>(lGenerator); // for all of out targets const std::vector<cmGeneratorTarget*>& tgts = lg->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator l = tgts.begin(); - l != tgts.end(); l++) { - if (((*l)->GetType() == cmStateEnums::EXECUTABLE) || - ((*l)->GetType() == cmStateEnums::STATIC_LIBRARY) || - ((*l)->GetType() == cmStateEnums::SHARED_LIBRARY) || - ((*l)->GetType() == cmStateEnums::MODULE_LIBRARY) || - ((*l)->GetType() == cmStateEnums::OBJECT_LIBRARY) || - ((*l)->GetType() == cmStateEnums::UTILITY)) { - cmGeneratorTarget* gt = *l; + for (cmGeneratorTarget* tgt : tgts) { + if ((tgt->GetType() == cmStateEnums::EXECUTABLE) || + (tgt->GetType() == cmStateEnums::STATIC_LIBRARY) || + (tgt->GetType() == cmStateEnums::SHARED_LIBRARY) || + (tgt->GetType() == cmStateEnums::MODULE_LIBRARY) || + (tgt->GetType() == cmStateEnums::OBJECT_LIBRARY) || + (tgt->GetType() == cmStateEnums::UTILITY)) { + cmGeneratorTarget* gt = tgt; std::string tname = lg->GetRelativeTargetDirectory(gt); tname += "/DependInfo.cmake"; cmSystemTools::ConvertToUnixSlashes(tname); @@ -415,9 +406,7 @@ void cmGlobalUnixMakefileGenerator3::WriteDirectoryRule2( // for all targets in the directory. std::vector<std::string> depends; const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator l = targets.begin(); - l != targets.end(); ++l) { - cmGeneratorTarget* gtarget = *l; + for (cmGeneratorTarget* gtarget : targets) { int type = gtarget->GetType(); if ((type == cmStateEnums::EXECUTABLE) || (type == cmStateEnums::STATIC_LIBRARY) || @@ -440,9 +429,8 @@ void cmGlobalUnixMakefileGenerator3::WriteDirectoryRule2( // The directory-level rule should depend on the directory-level // rules of the subdirectories. std::vector<cmStateSnapshot> children = lg->GetStateSnapshot().GetChildren(); - for (std::vector<cmStateSnapshot>::const_iterator ci = children.begin(); - ci != children.end(); ++ci) { - std::string subdir = ci->GetDirectory().GetCurrentBinary(); + for (cmStateSnapshot const& c : children) { + std::string subdir = c.GetDirectory().GetCurrentBinary(); subdir += "/"; subdir += pass; depends.push_back(subdir); @@ -450,7 +438,7 @@ void cmGlobalUnixMakefileGenerator3::WriteDirectoryRule2( // Work-around for makes that drop rules that have no dependencies // or commands. - if (depends.empty() && this->EmptyRuleHackDepends != "") { + if (depends.empty() && !this->EmptyRuleHackDepends.empty()) { depends.push_back(this->EmptyRuleHackDepends); } @@ -542,15 +530,12 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules( depends.push_back("cmake_check_build_system"); // write the target convenience rules - unsigned int i; - cmLocalUnixMakefileGenerator3* lg; - for (i = 0; i < this->LocalGenerators.size(); ++i) { - lg = static_cast<cmLocalUnixMakefileGenerator3*>(this->LocalGenerators[i]); + for (cmLocalGenerator* localGen : this->LocalGenerators) { + cmLocalUnixMakefileGenerator3* lg = + static_cast<cmLocalUnixMakefileGenerator3*>(localGen); // for each target Generate the rule files for each target. const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator t = targets.begin(); - t != targets.end(); ++t) { - cmGeneratorTarget* gtarget = *t; + for (cmGeneratorTarget* gtarget : targets) { // Don't emit the same rule twice (e.g. two targets with the same // simple name) int type = gtarget->GetType(); @@ -630,9 +615,7 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2( // for each target Generate the rule files for each target. const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator t = targets.begin(); - t != targets.end(); ++t) { - cmGeneratorTarget* gtarget = *t; + for (cmGeneratorTarget* gtarget : targets) { int type = gtarget->GetType(); std::string name = gtarget->GetName(); if (!name.empty() && ((type == cmStateEnums::EXECUTABLE) || @@ -680,11 +663,10 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2( { std::ostringstream progressArg; const char* sep = ""; - std::vector<unsigned long>& progFiles = + std::vector<unsigned long> const& progFiles = this->ProgressMap[gtarget].Marks; - for (std::vector<unsigned long>::iterator i = progFiles.begin(); - i != progFiles.end(); ++i) { - progressArg << sep << *i; + for (unsigned long progFile : progFiles) { + progressArg << sep << progFile; sep = ","; } progress.Arg = progressArg.str(); @@ -803,15 +785,9 @@ void cmGlobalUnixMakefileGenerator3::InitializeProgressMarks() { this->DirectoryTargetsMap.clear(); // Loop over all targets in all local generators. - for (std::vector<cmLocalGenerator*>::const_iterator lgi = - this->LocalGenerators.begin(); - lgi != this->LocalGenerators.end(); ++lgi) { - cmLocalGenerator* lg = *lgi; + for (cmLocalGenerator* lg : this->LocalGenerators) { const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator t = targets.begin(); - t != targets.end(); ++t) { - cmGeneratorTarget* gt = *t; - + for (cmGeneratorTarget* gt : targets) { cmLocalGenerator* tlg = gt->GetLocalGenerator(); if (gt->GetType() == cmStateEnums::INTERFACE_LIBRARY || @@ -835,9 +811,8 @@ void cmGlobalUnixMakefileGenerator3::InitializeProgressMarks() // target may still be included if it is a dependency of a // non-excluded target. TargetDependSet const& tgtdeps = this->GetTargetDirectDepends(gt); - for (TargetDependSet::const_iterator ti = tgtdeps.begin(); - ti != tgtdeps.end(); ++ti) { - targetSet.insert(*ti); + for (cmTargetDepend const& tgtdep : tgtdeps) { + targetSet.insert(tgtdep); } } } @@ -851,12 +826,11 @@ size_t cmGlobalUnixMakefileGenerator3::CountProgressMarksInTarget( if (emitted.insert(target).second) { count = this->ProgressMap[target].Marks.size(); TargetDependSet const& depends = this->GetTargetDirectDepends(target); - for (TargetDependSet::const_iterator di = depends.begin(); - di != depends.end(); ++di) { - if ((*di)->GetType() == cmStateEnums::INTERFACE_LIBRARY) { + for (cmTargetDepend const& depend : depends) { + if (depend->GetType() == cmStateEnums::INTERFACE_LIBRARY) { continue; } - count += this->CountProgressMarksInTarget(*di, emitted); + count += this->CountProgressMarksInTarget(depend, emitted); } } return count; @@ -869,9 +843,8 @@ size_t cmGlobalUnixMakefileGenerator3::CountProgressMarksInAll( std::set<cmGeneratorTarget const*> emitted; std::set<cmGeneratorTarget const*> const& targets = this->DirectoryTargetsMap[lg->GetStateSnapshot()]; - for (std::set<cmGeneratorTarget const*>::const_iterator t = targets.begin(); - t != targets.end(); ++t) { - count += this->CountProgressMarksInTarget(*t, emitted); + for (cmGeneratorTarget const* target : targets) { + count += this->CountProgressMarksInTarget(target, emitted); } return count; } @@ -910,10 +883,9 @@ void cmGlobalUnixMakefileGenerator3::AppendGlobalTargetDepends( std::vector<std::string>& depends, cmGeneratorTarget* target) { TargetDependSet const& depends_set = this->GetTargetDirectDepends(target); - for (TargetDependSet::const_iterator i = depends_set.begin(); - i != depends_set.end(); ++i) { + for (cmTargetDepend const& i : depends_set) { // Create the target-level dependency. - cmGeneratorTarget const* dep = *i; + cmGeneratorTarget const* dep = i; if (dep->GetType() == cmStateEnums::INTERFACE_LIBRARY) { continue; } @@ -943,20 +915,16 @@ void cmGlobalUnixMakefileGenerator3::WriteHelpRule( std::set<std::string> emittedTargets; // for each local generator - unsigned int i; - cmLocalUnixMakefileGenerator3* lg2; - for (i = 0; i < this->LocalGenerators.size(); ++i) { - lg2 = - static_cast<cmLocalUnixMakefileGenerator3*>(this->LocalGenerators[i]); + for (cmLocalGenerator* localGen : this->LocalGenerators) { + cmLocalUnixMakefileGenerator3* lg2 = + static_cast<cmLocalUnixMakefileGenerator3*>(localGen); // for the passed in makefile or if this is the top Makefile wripte out // the targets if (lg2 == lg || lg->IsRootMakefile()) { // for each target Generate the rule files for each target. const std::vector<cmGeneratorTarget*>& targets = lg2->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator t = targets.begin(); - t != targets.end(); ++t) { - cmGeneratorTarget* target = *t; + for (cmGeneratorTarget* target : targets) { cmStateEnums::TargetType type = target->GetType(); if ((type == cmStateEnums::EXECUTABLE) || (type == cmStateEnums::STATIC_LIBRARY) || @@ -975,11 +943,9 @@ void cmGlobalUnixMakefileGenerator3::WriteHelpRule( } } } - std::vector<std::string> const& localHelp = lg->GetLocalHelp(); - for (std::vector<std::string>::const_iterator o = localHelp.begin(); - o != localHelp.end(); ++o) { + for (std::string const& o : lg->GetLocalHelp()) { path = "... "; - path += *o; + path += o; lg->AppendEcho(commands, path); } lg->WriteMakeRule(ruleFileStream, "Help Target", "help", no_depends, @@ -994,10 +960,9 @@ bool cmGlobalUnixMakefileGenerator3::NeedRequiresStep( target->GetLanguages( languages, target->Target->GetMakefile()->GetSafeDefinition("CMAKE_BUILD_TYPE")); - for (std::set<std::string>::const_iterator l = languages.begin(); - l != languages.end(); ++l) { + for (std::string const& l : languages) { std::string var = "CMAKE_NEEDS_REQUIRES_STEP_"; - var += *l; + var += l; var += "_FLAG"; if (target->Target->GetMakefile()->GetDefinition(var)) { return true; diff --git a/Source/cmGlobalUnixMakefileGenerator3.h b/Source/cmGlobalUnixMakefileGenerator3.h index bc03c44..d601f88 100644 --- a/Source/cmGlobalUnixMakefileGenerator3.h +++ b/Source/cmGlobalUnixMakefileGenerator3.h @@ -68,7 +68,7 @@ public: } ///! Get the name for the generator. - std::string GetName() const CM_OVERRIDE + std::string GetName() const override { return cmGlobalUnixMakefileGenerator3::GetActualName(); } @@ -89,23 +89,23 @@ public: /** Get the documentation entry for this generator. */ static void GetDocumentation(cmDocumentationEntry& entry); - cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) CM_OVERRIDE; + cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) override; /** * Try to determine system information such as shared library * extension, pthreads, byte order etc. */ void EnableLanguage(std::vector<std::string> const& languages, cmMakefile*, - bool optional) CM_OVERRIDE; + bool optional) override; - void Configure() CM_OVERRIDE; + void Configure() override; /** * Generate the all required files for building this project/tree. This * basically creates a series of LocalGenerators for each directory and * requests that they Generate. */ - void Generate() CM_OVERRIDE; + void Generate() override; void WriteMainCMakefileLanguageRules(cmGeneratedFileStream& cmakefileStream, std::vector<cmLocalGenerator*>&); @@ -134,7 +134,7 @@ public: const std::string& targetName, const std::string& config, bool fast, bool verbose, std::vector<std::string> const& makeOptions = - std::vector<std::string>()) CM_OVERRIDE; + std::vector<std::string>()) override; /** Record per-target progress information. */ void RecordTargetProgress(cmMakefileTargetGenerator* tg); @@ -149,9 +149,9 @@ public: /** Does the make tool tolerate .DELETE_ON_ERROR? */ virtual bool AllowDeleteOnError() const { return true; } - bool IsIPOSupported() const CM_OVERRIDE { return true; } + bool IsIPOSupported() const override { return true; } - void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const CM_OVERRIDE; + void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const override; std::string IncludeDirective; bool DefineWindowsNULL; @@ -178,37 +178,31 @@ protected: bool NeedRequiresStep(cmGeneratorTarget const*); // Target name hooks for superclass. - const char* GetAllTargetName() const CM_OVERRIDE { return "all"; } - const char* GetInstallTargetName() const CM_OVERRIDE { return "install"; } - const char* GetInstallLocalTargetName() const CM_OVERRIDE + const char* GetAllTargetName() const override { return "all"; } + const char* GetInstallTargetName() const override { return "install"; } + const char* GetInstallLocalTargetName() const override { return "install/local"; } - const char* GetInstallStripTargetName() const CM_OVERRIDE + const char* GetInstallStripTargetName() const override { return "install/strip"; } - const char* GetPreinstallTargetName() const CM_OVERRIDE - { - return "preinstall"; - } - const char* GetTestTargetName() const CM_OVERRIDE { return "test"; } - const char* GetPackageTargetName() const CM_OVERRIDE { return "package"; } - const char* GetPackageSourceTargetName() const CM_OVERRIDE + const char* GetPreinstallTargetName() const override { return "preinstall"; } + const char* GetTestTargetName() const override { return "test"; } + const char* GetPackageTargetName() const override { return "package"; } + const char* GetPackageSourceTargetName() const override { return "package_source"; } - const char* GetEditCacheTargetName() const CM_OVERRIDE - { - return "edit_cache"; - } - const char* GetRebuildCacheTargetName() const CM_OVERRIDE + const char* GetEditCacheTargetName() const override { return "edit_cache"; } + const char* GetRebuildCacheTargetName() const override { return "rebuild_cache"; } - const char* GetCleanTargetName() const CM_OVERRIDE { return "clean"; } + const char* GetCleanTargetName() const override { return "clean"; } - bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const CM_OVERRIDE { return true; } + bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const override { return true; } // Some make programs (Borland) do not keep a rule if there are no // dependencies or commands. This is a problem for creating rules @@ -247,13 +241,13 @@ protected: cmGeneratedFileStream* CommandDatabase; private: - const char* GetBuildIgnoreErrorsFlag() const CM_OVERRIDE { return "-i"; } - std::string GetEditCacheCommand() const CM_OVERRIDE; + const char* GetBuildIgnoreErrorsFlag() const override { return "-i"; } + std::string GetEditCacheCommand() const override; std::map<cmStateSnapshot, std::set<cmGeneratorTarget const*>, cmStateSnapshot::StrictWeakOrder> DirectoryTargetsMap; - void InitializeProgressMarks() CM_OVERRIDE; + void InitializeProgressMarks() override; }; #endif diff --git a/Source/cmGlobalVisualStudio10Generator.cxx b/Source/cmGlobalVisualStudio10Generator.cxx index 1c0953a..8c9e461 100644 --- a/Source/cmGlobalVisualStudio10Generator.cxx +++ b/Source/cmGlobalVisualStudio10Generator.cxx @@ -51,7 +51,7 @@ class cmGlobalVisualStudio10Generator::Factory { public: cmGlobalGenerator* CreateGlobalGenerator(const std::string& name, - cmake* cm) const CM_OVERRIDE + cmake* cm) const override { std::string genName; const char* p = cmVS10GenName(name, genName); @@ -73,22 +73,22 @@ public: return 0; } - void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE + void GetDocumentation(cmDocumentationEntry& entry) const override { entry.Name = std::string(vs10generatorName) + " [arch]"; entry.Brief = "Generates Visual Studio 2010 project files. " "Optional [arch] can be \"Win64\" or \"IA64\"."; } - void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE + void GetGenerators(std::vector<std::string>& names) const override { names.push_back(vs10generatorName); names.push_back(vs10generatorName + std::string(" IA64")); names.push_back(vs10generatorName + std::string(" Win64")); } - bool SupportsToolset() const CM_OVERRIDE { return true; } - bool SupportsPlatform() const CM_OVERRIDE { return true; } + bool SupportsToolset() const override { return true; } + bool SupportsPlatform() const override { return true; } }; cmGlobalGeneratorFactory* cmGlobalVisualStudio10Generator::NewFactory() @@ -407,14 +407,14 @@ bool cmGlobalVisualStudio10Generator::InitializeWindowsStore(cmMakefile* mf) bool cmGlobalVisualStudio10Generator::SelectWindowsPhoneToolset( std::string& toolset) const { - toolset = ""; + toolset.clear(); return false; } bool cmGlobalVisualStudio10Generator::SelectWindowsStoreToolset( std::string& toolset) const { - toolset = ""; + toolset.clear(); return false; } @@ -695,7 +695,12 @@ bool cmGlobalVisualStudio10Generator::FindVCTargetsPath(cmMakefile* mf) xw.Content(this->WindowsTargetPlatformVersion); xw.EndElement(); // WindowsTargetPlatformVersion } - if (this->GetPlatformName() == "ARM") { + if (this->GetPlatformName() == "ARM64") { + xw.StartElement("WindowsSDKDesktopARM64Support"); + xw.Content("true"); + xw.EndElement(); // WindowsSDK64DesktopARMSupport + } + else if (this->GetPlatformName() == "ARM") { xw.StartElement("WindowsSDKDesktopARMSupport"); xw.Content("true"); xw.EndElement(); // WindowsSDKDesktopARMSupport diff --git a/Source/cmGlobalVisualStudio10Generator.h b/Source/cmGlobalVisualStudio10Generator.h index 4a5c245..5f80c73 100644 --- a/Source/cmGlobalVisualStudio10Generator.h +++ b/Source/cmGlobalVisualStudio10Generator.h @@ -98,7 +98,7 @@ public: virtual const char* GetToolsVersion() { return "4.0"; } - bool FindMakeProgram(cmMakefile* mf) CM_OVERRIDE; + bool FindMakeProgram(cmMakefile* mf) override; static std::string GetInstalledNsightTegraVersion(); diff --git a/Source/cmGlobalVisualStudio11Generator.cxx b/Source/cmGlobalVisualStudio11Generator.cxx index d37d4b0..cb3b047 100644 --- a/Source/cmGlobalVisualStudio11Generator.cxx +++ b/Source/cmGlobalVisualStudio11Generator.cxx @@ -35,7 +35,7 @@ class cmGlobalVisualStudio11Generator::Factory { public: cmGlobalGenerator* CreateGlobalGenerator(const std::string& name, - cmake* cm) const CM_OVERRIDE + cmake* cm) const override { std::string genName; const char* p = cmVS11GenName(name, genName); @@ -68,14 +68,14 @@ public: return ret; } - void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE + void GetDocumentation(cmDocumentationEntry& entry) const override { entry.Name = std::string(vs11generatorName) + " [arch]"; entry.Brief = "Generates Visual Studio 2012 project files. " "Optional [arch] can be \"Win64\" or \"ARM\"."; } - void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE + void GetGenerators(std::vector<std::string>& names) const override { names.push_back(vs11generatorName); names.push_back(vs11generatorName + std::string(" ARM")); @@ -89,8 +89,8 @@ public: } } - bool SupportsToolset() const CM_OVERRIDE { return true; } - bool SupportsPlatform() const CM_OVERRIDE { return true; } + bool SupportsToolset() const override { return true; } + bool SupportsPlatform() const override { return true; } }; cmGlobalGeneratorFactory* cmGlobalVisualStudio11Generator::NewFactory() diff --git a/Source/cmGlobalVisualStudio12Generator.cxx b/Source/cmGlobalVisualStudio12Generator.cxx index de62ff0..a9c605c 100644 --- a/Source/cmGlobalVisualStudio12Generator.cxx +++ b/Source/cmGlobalVisualStudio12Generator.cxx @@ -35,7 +35,7 @@ class cmGlobalVisualStudio12Generator::Factory { public: cmGlobalGenerator* CreateGlobalGenerator(const std::string& name, - cmake* cm) const CM_OVERRIDE + cmake* cm) const override { std::string genName; const char* p = cmVS12GenName(name, genName); @@ -57,22 +57,22 @@ public: return 0; } - void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE + void GetDocumentation(cmDocumentationEntry& entry) const override { entry.Name = std::string(vs12generatorName) + " [arch]"; entry.Brief = "Generates Visual Studio 2013 project files. " "Optional [arch] can be \"Win64\" or \"ARM\"."; } - void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE + void GetGenerators(std::vector<std::string>& names) const override { names.push_back(vs12generatorName); names.push_back(vs12generatorName + std::string(" ARM")); names.push_back(vs12generatorName + std::string(" Win64")); } - bool SupportsToolset() const CM_OVERRIDE { return true; } - bool SupportsPlatform() const CM_OVERRIDE { return true; } + bool SupportsToolset() const override { return true; } + bool SupportsPlatform() const override { return true; } }; cmGlobalGeneratorFactory* cmGlobalVisualStudio12Generator::NewFactory() diff --git a/Source/cmGlobalVisualStudio12Generator.h b/Source/cmGlobalVisualStudio12Generator.h index d032782..5ba21a6 100644 --- a/Source/cmGlobalVisualStudio12Generator.h +++ b/Source/cmGlobalVisualStudio12Generator.h @@ -32,7 +32,7 @@ public: virtual const char* GetToolsVersion() { return "12.0"; } protected: bool ProcessGeneratorToolsetField(std::string const& key, - std::string const& value) CM_OVERRIDE; + std::string const& value) override; virtual bool InitializeWindowsPhone(cmMakefile* mf); virtual bool InitializeWindowsStore(cmMakefile* mf); diff --git a/Source/cmGlobalVisualStudio14Generator.cxx b/Source/cmGlobalVisualStudio14Generator.cxx index e2120b8..97d5313 100644 --- a/Source/cmGlobalVisualStudio14Generator.cxx +++ b/Source/cmGlobalVisualStudio14Generator.cxx @@ -35,7 +35,7 @@ class cmGlobalVisualStudio14Generator::Factory { public: cmGlobalGenerator* CreateGlobalGenerator(const std::string& name, - cmake* cm) const CM_OVERRIDE + cmake* cm) const override { std::string genName; const char* p = cmVS14GenName(name, genName); @@ -57,22 +57,22 @@ public: return 0; } - void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE + void GetDocumentation(cmDocumentationEntry& entry) const override { entry.Name = std::string(vs14generatorName) + " [arch]"; entry.Brief = "Generates Visual Studio 2015 project files. " "Optional [arch] can be \"Win64\" or \"ARM\"."; } - void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE + void GetGenerators(std::vector<std::string>& names) const override { names.push_back(vs14generatorName); names.push_back(vs14generatorName + std::string(" ARM")); names.push_back(vs14generatorName + std::string(" Win64")); } - bool SupportsToolset() const CM_OVERRIDE { return true; } - bool SupportsPlatform() const CM_OVERRIDE { return true; } + bool SupportsToolset() const override { return true; } + bool SupportsPlatform() const override { return true; } }; cmGlobalGeneratorFactory* cmGlobalVisualStudio14Generator::NewFactory() diff --git a/Source/cmGlobalVisualStudio15Generator.cxx b/Source/cmGlobalVisualStudio15Generator.cxx index ce1ba00..d2bf7cc 100644 --- a/Source/cmGlobalVisualStudio15Generator.cxx +++ b/Source/cmGlobalVisualStudio15Generator.cxx @@ -69,8 +69,8 @@ public: names.push_back(vs15generatorName + std::string(" Win64")); } - bool SupportsToolset() const CM_OVERRIDE { return true; } - bool SupportsPlatform() const CM_OVERRIDE { return true; } + bool SupportsToolset() const override { return true; } + bool SupportsPlatform() const override { return true; } }; cmGlobalGeneratorFactory* cmGlobalVisualStudio15Generator::NewFactory() diff --git a/Source/cmGlobalVisualStudio15Generator.h b/Source/cmGlobalVisualStudio15Generator.h index 730784b..e934882 100644 --- a/Source/cmGlobalVisualStudio15Generator.h +++ b/Source/cmGlobalVisualStudio15Generator.h @@ -28,7 +28,7 @@ public: virtual const char* GetToolsVersion() { return "15.0"; } protected: - bool InitializeWindows(cmMakefile* mf) CM_OVERRIDE; + bool InitializeWindows(cmMakefile* mf) override; virtual bool SelectWindowsStoreToolset(std::string& toolset) const; virtual const char* GetIDEVersion() { return "15.0"; } @@ -44,8 +44,8 @@ protected: // Check for a Win 8 SDK known to the registry or VS installer tool. bool IsWin81SDKInstalled() const; - std::string FindMSBuildCommand() CM_OVERRIDE; - std::string FindDevEnvCommand() CM_OVERRIDE; + std::string FindMSBuildCommand() override; + std::string FindDevEnvCommand() override; private: class Factory; diff --git a/Source/cmGlobalVisualStudio71Generator.cxx b/Source/cmGlobalVisualStudio71Generator.cxx index 624f9e5..3b45c90 100644 --- a/Source/cmGlobalVisualStudio71Generator.cxx +++ b/Source/cmGlobalVisualStudio71Generator.cxx @@ -200,10 +200,16 @@ void cmGlobalVisualStudio71Generator::WriteProjectConfigurations( std::string guid = this->GetGUID(name); for (std::vector<std::string>::const_iterator i = configs.begin(); i != configs.end(); ++i) { - const char* dstConfig = target.GetProperty("MAP_IMPORTED_CONFIG_" + - cmSystemTools::UpperCase(*i)); - if (dstConfig == nullptr) { - dstConfig = i->c_str(); + std::vector<std::string> mapConfig; + const char* dstConfig = i->c_str(); + if (target.GetProperty("EXTERNAL_MSPROJECT")) { + if (const char* m = target.GetProperty("MAP_IMPORTED_CONFIG_" + + cmSystemTools::UpperCase(*i))) { + cmSystemTools::ExpandListArgument(m, mapConfig); + if (!mapConfig.empty()) { + dstConfig = mapConfig[0].c_str(); + } + } } fout << "\t\t{" << guid << "}." << *i << ".ActiveCfg = " << dstConfig << "|" << platformName << std::endl; diff --git a/Source/cmGlobalVisualStudio7Generator.cxx b/Source/cmGlobalVisualStudio7Generator.cxx index b155f5b..a14b5f7 100644 --- a/Source/cmGlobalVisualStudio7Generator.cxx +++ b/Source/cmGlobalVisualStudio7Generator.cxx @@ -334,7 +334,7 @@ void cmGlobalVisualStudio7Generator::OutputSLNFile( // output the SLN file void cmGlobalVisualStudio7Generator::OutputSLNFile() { - std::map<std::string, std::vector<cmLocalGenerator*> >::iterator it; + std::map<std::string, std::vector<cmLocalGenerator*>>::iterator it; for (it = this->ProjectMap.begin(); it != this->ProjectMap.end(); ++it) { this->OutputSLNFile(it->second[0], it->second); } @@ -403,7 +403,7 @@ void cmGlobalVisualStudio7Generator::WriteTargetsToSolution( std::string dir = lg->GetCurrentBinaryDirectory(); dir = root->ConvertToRelativePath(rootBinaryDir, dir.c_str()); if (dir == ".") { - dir = ""; // msbuild cannot handle ".\" prefix + dir.clear(); // msbuild cannot handle ".\" prefix } this->WriteProject(fout, vcprojName, dir.c_str(), target); written = true; @@ -418,7 +418,7 @@ void cmGlobalVisualStudio7Generator::WriteTargetsToSolution( std::vector<cmsys::String> tokens = cmSystemTools::SplitString(targetFolder, '/', false); - std::string cumulativePath = ""; + std::string cumulativePath; for (std::vector<cmsys::String>::iterator iter = tokens.begin(); iter != tokens.end(); ++iter) { @@ -467,7 +467,7 @@ void cmGlobalVisualStudio7Generator::WriteFolders(std::ostream& fout) const char* prefix = "CMAKE_FOLDER_GUID_"; const std::string::size_type skip_prefix = strlen(prefix); std::string guidProjectTypeFolder = "2150E333-8FDC-42A3-9474-1A3956D46DE8"; - for (std::map<std::string, std::set<std::string> >::iterator iter = + for (std::map<std::string, std::set<std::string>>::iterator iter = VisualStudioFolders.begin(); iter != VisualStudioFolders.end(); ++iter) { std::string fullName = iter->first; @@ -487,7 +487,7 @@ void cmGlobalVisualStudio7Generator::WriteFolders(std::ostream& fout) void cmGlobalVisualStudio7Generator::WriteFoldersContent(std::ostream& fout) { - for (std::map<std::string, std::set<std::string> >::iterator iter = + for (std::map<std::string, std::set<std::string>>::iterator iter = VisualStudioFolders.begin(); iter != VisualStudioFolders.end(); ++iter) { std::string key(iter->first); @@ -708,7 +708,7 @@ std::set<std::string> cmGlobalVisualStudio7Generator::IsPartOfDefaultBuild( const char* propertyValue = target->Target->GetMakefile()->GetDefinition(propertyName); cmGeneratorExpression ge; - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(propertyValue); if (cmSystemTools::IsOn( cge->Evaluate(target->GetLocalGenerator(), *i))) { diff --git a/Source/cmGlobalVisualStudio7Generator.h b/Source/cmGlobalVisualStudio7Generator.h index 32a8d60..c5aced4 100644 --- a/Source/cmGlobalVisualStudio7Generator.h +++ b/Source/cmGlobalVisualStudio7Generator.h @@ -91,7 +91,7 @@ public: const char* GetIntelProjectVersion(); - bool FindMakeProgram(cmMakefile* mf) CM_OVERRIDE; + bool FindMakeProgram(cmMakefile* mf) override; /** Is the Microsoft Assembler enabled? */ bool IsMasmEnabled() const { return this->MasmEnabled; } @@ -156,7 +156,7 @@ protected: virtual void WriteFolders(std::ostream& fout); virtual void WriteFoldersContent(std::ostream& fout); - std::map<std::string, std::set<std::string> > VisualStudioFolders; + std::map<std::string, std::set<std::string>> VisualStudioFolders; // Set during OutputSLNFile with the name of the current project. // There is one SLN file per project. diff --git a/Source/cmGlobalVisualStudio8Generator.cxx b/Source/cmGlobalVisualStudio8Generator.cxx index 728ad2d..cc1d1a2 100644 --- a/Source/cmGlobalVisualStudio8Generator.cxx +++ b/Source/cmGlobalVisualStudio8Generator.cxx @@ -17,7 +17,7 @@ class cmGlobalVisualStudio8Generator::Factory : public cmGlobalGeneratorFactory { public: cmGlobalGenerator* CreateGlobalGenerator(const std::string& name, - cmake* cm) const CM_OVERRIDE + cmake* cm) const override { if (strncmp(name.c_str(), vs8generatorName, sizeof(vs8generatorName) - 1) != 0) { @@ -51,14 +51,14 @@ public: return ret; } - void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE + void GetDocumentation(cmDocumentationEntry& entry) const override { entry.Name = std::string(vs8generatorName) + " [arch]"; entry.Brief = "Deprecated. Generates Visual Studio 2005 project files. " "Optional [arch] can be \"Win64\"."; } - void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE + void GetGenerators(std::vector<std::string>& names) const override { names.push_back(vs8generatorName); names.push_back(vs8generatorName + std::string(" Win64")); @@ -73,8 +73,8 @@ public: } } - bool SupportsToolset() const CM_OVERRIDE { return false; } - bool SupportsPlatform() const CM_OVERRIDE { return true; } + bool SupportsToolset() const override { return false; } + bool SupportsPlatform() const override { return true; } }; cmGlobalGeneratorFactory* cmGlobalVisualStudio8Generator::NewFactory() @@ -301,7 +301,7 @@ bool cmGlobalVisualStudio8Generator::AddCheckTarget() // file as the main dependency because it would get // overwritten by the CreateVCProjBuildRule. // (this could be avoided with per-target source files) - std::string no_main_dependency = ""; + std::string no_main_dependency; std::vector<std::string> no_byproducts; if (cmSourceFile* file = mf->AddCustomCommandToOutput( stamps, no_byproducts, listFiles, no_main_dependency, commandLines, @@ -354,10 +354,16 @@ void cmGlobalVisualStudio8Generator::WriteProjectConfigurations( std::string guid = this->GetGUID(name); for (std::vector<std::string>::const_iterator i = configs.begin(); i != configs.end(); ++i) { - const char* dstConfig = target.GetProperty("MAP_IMPORTED_CONFIG_" + - cmSystemTools::UpperCase(*i)); - if (dstConfig == nullptr) { - dstConfig = i->c_str(); + std::vector<std::string> mapConfig; + const char* dstConfig = i->c_str(); + if (target.GetProperty("EXTERNAL_MSPROJECT")) { + if (const char* m = target.GetProperty("MAP_IMPORTED_CONFIG_" + + cmSystemTools::UpperCase(*i))) { + cmSystemTools::ExpandListArgument(m, mapConfig); + if (!mapConfig.empty()) { + dstConfig = mapConfig[0].c_str(); + } + } } fout << "\t\t{" << guid << "}." << *i << "|" << this->GetPlatformName() << ".ActiveCfg = " << dstConfig << "|" diff --git a/Source/cmGlobalVisualStudio9Generator.cxx b/Source/cmGlobalVisualStudio9Generator.cxx index b1634e2..0abb348 100644 --- a/Source/cmGlobalVisualStudio9Generator.cxx +++ b/Source/cmGlobalVisualStudio9Generator.cxx @@ -14,7 +14,7 @@ class cmGlobalVisualStudio9Generator::Factory : public cmGlobalGeneratorFactory { public: cmGlobalGenerator* CreateGlobalGenerator(const std::string& name, - cmake* cm) const CM_OVERRIDE + cmake* cm) const override { if (strncmp(name.c_str(), vs9generatorName, sizeof(vs9generatorName) - 1) != 0) { @@ -52,14 +52,14 @@ public: return ret; } - void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE + void GetDocumentation(cmDocumentationEntry& entry) const override { entry.Name = std::string(vs9generatorName) + " [arch]"; entry.Brief = "Generates Visual Studio 2008 project files. " "Optional [arch] can be \"Win64\" or \"IA64\"."; } - void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE + void GetGenerators(std::vector<std::string>& names) const override { names.push_back(vs9generatorName); names.push_back(vs9generatorName + std::string(" Win64")); @@ -75,8 +75,8 @@ public: } } - bool SupportsToolset() const CM_OVERRIDE { return false; } - bool SupportsPlatform() const CM_OVERRIDE { return true; } + bool SupportsToolset() const override { return false; } + bool SupportsPlatform() const override { return true; } }; cmGlobalGeneratorFactory* cmGlobalVisualStudio9Generator::NewFactory() diff --git a/Source/cmGlobalVisualStudioGenerator.cxx b/Source/cmGlobalVisualStudioGenerator.cxx index f85e409..0651536 100644 --- a/Source/cmGlobalVisualStudioGenerator.cxx +++ b/Source/cmGlobalVisualStudioGenerator.cxx @@ -58,7 +58,7 @@ void cmGlobalVisualStudioGenerator::AddExtraIDETargets() const char* no_working_dir = 0; std::vector<std::string> no_depends; cmCustomCommandLines no_commands; - std::map<std::string, std::vector<cmLocalGenerator*> >::iterator it; + std::map<std::string, std::vector<cmLocalGenerator*>>::iterator it; for (it = this->ProjectMap.begin(); it != this->ProjectMap.end(); ++it) { std::vector<cmLocalGenerator*>& gen = it->second; // add the ALL_BUILD to the first local generator of each project @@ -150,7 +150,7 @@ void cmGlobalVisualStudioGenerator::ConfigureCMakeVisualStudioMacros() { std::string dir = this->GetUserMacrosDirectory(); - if (dir != "") { + if (!dir.empty()) { std::string src = cmSystemTools::GetCMakeRoot(); src += "/Templates/" CMAKE_VSMACROS_FILENAME; @@ -190,7 +190,7 @@ void cmGlobalVisualStudioGenerator::CallVisualStudioMacro( // - the CMake vsmacros file is registered // - there were .sln/.vcproj files changed during generation // - if (dir != "") { + if (!dir.empty()) { std::string macrosFile = dir + "/CMakeMacros/" CMAKE_VSMACROS_FILENAME; std::string nextSubkeyName; if (cmSystemTools::FileExists(macrosFile.c_str()) && @@ -295,7 +295,7 @@ bool cmGlobalVisualStudioGenerator::ComputeTargetDepends() if (!this->cmGlobalGenerator::ComputeTargetDepends()) { return false; } - std::map<std::string, std::vector<cmLocalGenerator*> >::iterator it; + std::map<std::string, std::vector<cmLocalGenerator*>>::iterator it; for (it = this->ProjectMap.begin(); it != this->ProjectMap.end(); ++it) { std::vector<cmLocalGenerator*>& gen = it->second; for (std::vector<cmLocalGenerator*>::iterator i = gen.begin(); @@ -782,6 +782,19 @@ bool cmGlobalVisualStudioGenerator::TargetIsCSharpOnly( return false; } +bool cmGlobalVisualStudioGenerator::TargetCanBeReferenced( + cmGeneratorTarget const* gt) +{ + if (this->TargetIsCSharpOnly(gt)) { + return true; + } + if (gt->GetType() != cmStateEnums::SHARED_LIBRARY && + gt->GetType() != cmStateEnums::EXECUTABLE) { + return false; + } + return true; +} + bool cmGlobalVisualStudioGenerator::TargetCompare::operator()( cmGeneratorTarget const* l, cmGeneratorTarget const* r) const { diff --git a/Source/cmGlobalVisualStudioGenerator.h b/Source/cmGlobalVisualStudioGenerator.h index 04d97c5..62bfd3b 100644 --- a/Source/cmGlobalVisualStudioGenerator.h +++ b/Source/cmGlobalVisualStudioGenerator.h @@ -85,6 +85,9 @@ public: // return true if target is C# only static bool TargetIsCSharpOnly(cmGeneratorTarget const* gt); + // return true if target can be referenced by C# targets + bool TargetCanBeReferenced(cmGeneratorTarget const* gt); + /** Get the top-level registry key for this VS version. */ std::string GetRegistryBase(); @@ -115,7 +118,7 @@ public: }; class OrderedTargetDependSet; - bool FindMakeProgram(cmMakefile*) CM_OVERRIDE; + bool FindMakeProgram(cmMakefile*) override; virtual std::string ExpandCFGIntDir(const std::string& str, const std::string& config) const; diff --git a/Source/cmGlobalWatcomWMakeGenerator.h b/Source/cmGlobalWatcomWMakeGenerator.h index bd09715..e8b3a73 100644 --- a/Source/cmGlobalWatcomWMakeGenerator.h +++ b/Source/cmGlobalWatcomWMakeGenerator.h @@ -29,7 +29,7 @@ public: return new cmGlobalGeneratorSimpleFactory<cmGlobalWatcomWMakeGenerator>(); } ///! Get the name for the generator. - std::string GetName() const CM_OVERRIDE + std::string GetName() const override { return cmGlobalWatcomWMakeGenerator::GetActualName(); } @@ -43,10 +43,10 @@ public: * extension, pthreads, byte order etc. */ void EnableLanguage(std::vector<std::string> const& languages, cmMakefile*, - bool optional) CM_OVERRIDE; + bool optional) override; - bool AllowNotParallel() const CM_OVERRIDE { return false; } - bool AllowDeleteOnError() const CM_OVERRIDE { return false; } + bool AllowNotParallel() const override { return false; } + bool AllowDeleteOnError() const override { return false; } }; #endif diff --git a/Source/cmGlobalXCodeGenerator.cxx b/Source/cmGlobalXCodeGenerator.cxx index 9dbb173..9375f60 100644 --- a/Source/cmGlobalXCodeGenerator.cxx +++ b/Source/cmGlobalXCodeGenerator.cxx @@ -5,10 +5,12 @@ #include "cmsys/RegularExpression.hxx" #include <assert.h> #include <iomanip> +#include <memory> // IWYU pragma: keep #include <sstream> #include <stdio.h> #include <string.h> +#include "cmAlgorithms.h" #include "cmComputeLinkInformation.h" #include "cmCustomCommandGenerator.h" #include "cmDocumentationEntry.h" @@ -29,7 +31,6 @@ #include "cmXCode21Object.h" #include "cmXCodeObject.h" #include "cmXCodeScheme.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" struct cmLinkImplementation; @@ -79,7 +80,7 @@ class cmGlobalXCodeGenerator::BuildObjectListOrString public: BuildObjectListOrString(cmGlobalXCodeGenerator* gen, bool buildObjectList) : Generator(gen) - , Group(0) + , Group(nullptr) , Empty(true) { if (buildObjectList) { @@ -117,20 +118,20 @@ class cmGlobalXCodeGenerator::Factory : public cmGlobalGeneratorFactory { public: cmGlobalGenerator* CreateGlobalGenerator(const std::string& name, - cmake* cm) const CM_OVERRIDE; + cmake* cm) const override; - void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE + void GetDocumentation(cmDocumentationEntry& entry) const override { cmGlobalXCodeGenerator::GetDocumentation(entry); } - void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE + void GetGenerators(std::vector<std::string>& names) const override { names.push_back(cmGlobalXCodeGenerator::GetActualName()); } - bool SupportsToolset() const CM_OVERRIDE { return true; } - bool SupportsPlatform() const CM_OVERRIDE { return false; } + bool SupportsToolset() const override { return true; } + bool SupportsPlatform() const override { return false; } }; cmGlobalXCodeGenerator::cmGlobalXCodeGenerator( @@ -140,10 +141,10 @@ cmGlobalXCodeGenerator::cmGlobalXCodeGenerator( this->VersionString = version_string; this->XcodeVersion = version_number; - this->RootObject = 0; - this->MainGroupChildren = 0; - this->CurrentMakefile = 0; - this->CurrentLocalGenerator = 0; + this->RootObject = nullptr; + this->MainGroupChildren = nullptr; + this->CurrentMakefile = nullptr; + this->CurrentLocalGenerator = nullptr; this->XcodeBuildCommandInitialized = false; this->ObjectDirArchDefault = "$(CURRENT_ARCH)"; @@ -161,15 +162,16 @@ cmGlobalGenerator* cmGlobalXCodeGenerator::Factory::CreateGlobalGenerator( const std::string& name, cmake* cm) const { if (name != GetActualName()) - return 0; + return nullptr; #if defined(CMAKE_BUILD_WITH_CMAKE) cmXcodeVersionParser parser; std::string versionFile; { std::string out; std::string::size_type pos; - if (cmSystemTools::RunSingleCommand("xcode-select --print-path", &out, 0, - 0, 0, cmSystemTools::OUTPUT_NONE) && + if (cmSystemTools::RunSingleCommand("xcode-select --print-path", &out, + nullptr, nullptr, nullptr, + cmSystemTools::OUTPUT_NONE) && (pos = out.find(".app/"), pos != std::string::npos)) { versionFile = out.substr(0, pos + 5) + "Contents/version.plist"; } @@ -196,8 +198,8 @@ cmGlobalGenerator* cmGlobalXCodeGenerator::Factory::CreateGlobalGenerator( return nullptr; } - CM_AUTO_PTR<cmGlobalXCodeGenerator> gg( - new cmGlobalXCodeGenerator(cm, version_string, version_number)); + auto gg = cm::make_unique<cmGlobalXCodeGenerator>(cm, version_string, + version_number); return gg.release(); #else std::cerr << "CMake should be built with cmake to use Xcode, " @@ -330,7 +332,7 @@ cmLocalGenerator* cmGlobalXCodeGenerator::CreateLocalGenerator(cmMakefile* mf) void cmGlobalXCodeGenerator::AddExtraIDETargets() { - std::map<std::string, std::vector<cmLocalGenerator*> >::iterator it; + std::map<std::string, std::vector<cmLocalGenerator*>>::iterator it; // make sure extra targets are added before calling // the parent generate which will call trace depends for (it = this->ProjectMap.begin(); it != this->ProjectMap.end(); ++it) { @@ -347,7 +349,7 @@ void cmGlobalXCodeGenerator::Generate() if (cmSystemTools::GetErrorOccuredFlag()) { return; } - std::map<std::string, std::vector<cmLocalGenerator*> >::iterator it; + std::map<std::string, std::vector<cmLocalGenerator*>>::iterator it; for (it = this->ProjectMap.begin(); it != this->ProjectMap.end(); ++it) { cmLocalGenerator* root = it->second[0]; this->SetGenerationRoot(root); @@ -391,7 +393,7 @@ void cmGlobalXCodeGenerator::AddExtraTargets( cmMakefile* mf = root->GetMakefile(); // Add ALL_BUILD - const char* no_working_directory = 0; + const char* no_working_directory = nullptr; std::vector<std::string> no_depends; cmTarget* allbuild = mf->AddUtilityCommand("ALL_BUILD", true, no_depends, no_working_directory, @@ -668,7 +670,8 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeSourceFile( if (const char* cflags = sf->GetProperty("COMPILE_FLAGS")) { cmGeneratorExpression ge; std::string configName = "NO-PER-CONFIG-SUPPORT-IN-XCODE"; - CM_AUTO_PTR<cmCompiledGeneratorExpression> compiledExpr = ge.Parse(cflags); + std::unique_ptr<cmCompiledGeneratorExpression> compiledExpr = + ge.Parse(cflags); const char* processed = compiledExpr->Evaluate(lg, configName); if (compiledExpr->GetHadContextSensitiveCondition()) { std::ostringstream e; @@ -1018,7 +1021,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets( } std::string const& obj = (*oi)->GetFullPath(); cmXCodeObject* xsf = - this->CreateXCodeSourceFileFromPath(obj, gtgt, "", 0); + this->CreateXCodeSourceFileFromPath(obj, gtgt, "", nullptr); externalObjFiles.push_back(xsf); } } @@ -1028,10 +1031,10 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets( bool isBundleTarget = gtgt->GetPropertyAsBool("MACOSX_BUNDLE"); bool isCFBundleTarget = gtgt->IsCFBundleOnApple(); - cmXCodeObject* buildFiles = 0; + cmXCodeObject* buildFiles = nullptr; // create source build phase - cmXCodeObject* sourceBuildPhase = 0; + cmXCodeObject* sourceBuildPhase = nullptr; if (!sourceFiles.empty()) { sourceBuildPhase = this->CreateObject(cmXCodeObject::PBXSourcesBuildPhase); @@ -1049,7 +1052,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets( } // create header build phase - only for framework targets - cmXCodeObject* headerBuildPhase = 0; + cmXCodeObject* headerBuildPhase = nullptr; if (!headerFiles.empty() && isFrameworkTarget) { headerBuildPhase = this->CreateObject(cmXCodeObject::PBXHeadersBuildPhase); @@ -1067,7 +1070,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets( } // create resource build phase - only for framework or bundle targets - cmXCodeObject* resourceBuildPhase = 0; + cmXCodeObject* resourceBuildPhase = nullptr; if (!resourceFiles.empty() && (isFrameworkTarget || isBundleTarget || isCFBundleTarget)) { resourceBuildPhase = @@ -1089,7 +1092,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets( // framework or bundle targets std::vector<cmXCodeObject*> contentBuildPhases; if (isFrameworkTarget || isBundleTarget || isCFBundleTarget) { - typedef std::map<std::string, std::vector<cmSourceFile*> > + typedef std::map<std::string, std::vector<cmSourceFile*>> mapOfVectorOfSourceFiles; mapOfVectorOfSourceFiles bundleFiles; for (std::vector<cmSourceFile*>::const_iterator i = classes.begin(); @@ -1140,7 +1143,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets( // create vector of "resource content file" build phases - only for // framework or bundle targets if (isFrameworkTarget || isBundleTarget || isCFBundleTarget) { - typedef std::map<std::string, std::vector<cmSourceFile*> > + typedef std::map<std::string, std::vector<cmSourceFile*>> mapOfVectorOfSourceFiles; mapOfVectorOfSourceFiles bundleFiles; for (std::vector<cmSourceFile*>::const_iterator i = classes.begin(); @@ -1177,7 +1180,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets( } // create framework build phase - cmXCodeObject* frameworkBuildPhase = 0; + cmXCodeObject* frameworkBuildPhase = nullptr; if (!externalObjFiles.empty()) { frameworkBuildPhase = this->CreateObject(cmXCodeObject::PBXFrameworksBuildPhase); @@ -1278,7 +1281,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateBuildPhase( const std::vector<cmCustomCommand>& commands) { if (commands.size() == 0 && strcmp(name, "CMake ReRun") != 0) { - return 0; + return nullptr; } cmXCodeObject* buildPhase = this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase); @@ -1754,8 +1757,8 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt, const char* version = gtgt->GetProperty("VERSION"); const char* soversion = gtgt->GetProperty("SOVERSION"); if (!gtgt->HasSOName(configName) || gtgt->IsFrameworkOnApple()) { - version = 0; - soversion = 0; + version = nullptr; + soversion = nullptr; } if (version && !soversion) { soversion = version; @@ -2038,7 +2041,7 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt, bool same_gflags = true; std::map<std::string, std::string> gflags; - std::string const* last_gflag = 0; + std::string const* last_gflag = nullptr; std::string optLevel = "0"; // Minimal map of flags to build settings. @@ -2108,7 +2111,7 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt, } // Add Fortran source format attribute if property is set. - const char* format = 0; + const char* format = nullptr; const char* tgtfmt = gtgt->GetProperty("Fortran_FORMAT"); switch (cmOutputConverter::GetFortranFormat(tgtfmt)) { case cmOutputConverter::FortranFormatFixed: @@ -2268,8 +2271,8 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateUtilityTarget( target->SetComment(gtgt->GetName()); cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST); std::vector<cmXCodeObject*> emptyContentVector; - this->CreateCustomCommands(buildPhases, 0, 0, 0, emptyContentVector, 0, - gtgt); + this->CreateCustomCommands(buildPhases, nullptr, nullptr, nullptr, + emptyContentVector, nullptr, gtgt); target->AddAttribute("buildPhases", buildPhases); this->AddConfigurations(target, gtgt); cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST); @@ -2283,7 +2286,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateUtilityTarget( if (gtgt->GetType() == cmStateEnums::UTILITY) { std::vector<cmSourceFile*> sources; if (!gtgt->GetConfigCommonSourceFiles(sources)) { - return 0; + return nullptr; } for (std::vector<cmSourceFile*>::const_iterator i = sources.begin(); @@ -2383,7 +2386,7 @@ const char* cmGlobalXCodeGenerator::GetTargetFileType( default: break; } - return 0; + return nullptr; } const char* cmGlobalXCodeGenerator::GetTargetProductType( @@ -2418,14 +2421,14 @@ const char* cmGlobalXCodeGenerator::GetTargetProductType( default: break; } - return 0; + return nullptr; } cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget( cmGeneratorTarget* gtgt, cmXCodeObject* buildPhases) { if (gtgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) { - return 0; + return nullptr; } cmXCodeObject* target = this->CreateObject(cmXCodeObject::PBXNativeTarget); target->AddAttribute("buildPhases", buildPhases); @@ -2469,13 +2472,13 @@ cmXCodeObject* cmGlobalXCodeGenerator::FindXCodeTarget( cmGeneratorTarget const* t) { if (!t) { - return 0; + return nullptr; } std::map<cmGeneratorTarget const*, cmXCodeObject*>::const_iterator const i = this->XCodeObjectMap.find(t); if (i == this->XCodeObjectMap.end()) { - return 0; + return nullptr; } return i->second; } @@ -2747,7 +2750,7 @@ bool cmGlobalXCodeGenerator::CreateGroups( cmXCodeObject* cmGlobalXCodeGenerator::CreatePBXGroup(cmXCodeObject* parent, std::string name) { - cmXCodeObject* parentChildren = NULL; + cmXCodeObject* parentChildren = nullptr; if (parent) parentChildren = parent->GetObject("children"); cmXCodeObject* group = this->CreateObject(cmXCodeObject::PBXGroup); @@ -2781,7 +2784,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateOrGetPBXGroup( } it = this->TargetGroup.find(target); - cmXCodeObject* tgroup = 0; + cmXCodeObject* tgroup = nullptr; if (it != this->TargetGroup.end()) { tgroup = it->second; } else { @@ -2847,8 +2850,8 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects( cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators) { this->ClearXCodeObjects(); - this->RootObject = 0; - this->MainGroupChildren = 0; + this->RootObject = nullptr; + this->MainGroupChildren = nullptr; cmXCodeObject* group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP); group->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO")); cmXCodeObject* listObjs = this->CreateObject(cmXCodeObject::OBJECT_LIST); @@ -2924,7 +2927,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects( this->CreateObject(cmXCodeObject::XCConfigurationList); cmXCodeObject* buildConfigurations = this->CreateObject(cmXCodeObject::OBJECT_LIST); - typedef std::vector<std::pair<std::string, cmXCodeObject*> > Configs; + typedef std::vector<std::pair<std::string, cmXCodeObject*>> Configs; Configs configs; const char* defaultConfigName = "Debug"; for (unsigned int i = 0; i < this->CurrentConfigurationTypes.size(); ++i) { diff --git a/Source/cmGlobalXCodeGenerator.h b/Source/cmGlobalXCodeGenerator.h index 7f57335..81d1bd0 100644 --- a/Source/cmGlobalXCodeGenerator.h +++ b/Source/cmGlobalXCodeGenerator.h @@ -37,7 +37,7 @@ public: static cmGlobalGeneratorFactory* NewFactory(); ///! Get the name for the generator. - std::string GetName() const CM_OVERRIDE + std::string GetName() const override { return cmGlobalXCodeGenerator::GetActualName(); } @@ -47,14 +47,14 @@ public: static void GetDocumentation(cmDocumentationEntry& entry); ///! Create a local generator appropriate to this Global Generator - cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) CM_OVERRIDE; + cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) override; /** * Try to determine system information such as shared library * extension, pthreads, byte order etc. */ void EnableLanguage(std::vector<std::string> const& languages, cmMakefile*, - bool optional) CM_OVERRIDE; + bool optional) override; /** * Try running cmake and building a file. This is used for dynalically * loaded commands, not as part of the usual build process. @@ -66,42 +66,42 @@ public: const std::string& targetName, const std::string& config, bool fast, bool verbose, std::vector<std::string> const& makeOptions = - std::vector<std::string>()) CM_OVERRIDE; + std::vector<std::string>()) override; /** Append the subdirectory for the given configuration. */ void AppendDirectoryForConfig(const std::string& prefix, const std::string& config, const std::string& suffix, - std::string& dir) CM_OVERRIDE; + std::string& dir) override; - bool FindMakeProgram(cmMakefile*) CM_OVERRIDE; + bool FindMakeProgram(cmMakefile*) override; ///! What is the configurations directory variable called? - const char* GetCMakeCFGIntDir() const CM_OVERRIDE; + const char* GetCMakeCFGIntDir() const override; ///! expand CFGIntDir std::string ExpandCFGIntDir(const std::string& str, - const std::string& config) const CM_OVERRIDE; + const std::string& config) const override; void SetCurrentLocalGenerator(cmLocalGenerator*); /** Return true if the generated build tree may contain multiple builds. i.e. "Can I build Debug and Release in the same tree?" */ - bool IsMultiConfig() const CM_OVERRIDE; + bool IsMultiConfig() const override; - bool HasKnownObjectFileLocation(std::string* reason) const CM_OVERRIDE; + bool HasKnownObjectFileLocation(std::string* reason) const override; - bool IsIPOSupported() const CM_OVERRIDE { return true; } + bool IsIPOSupported() const override { return true; } - bool UseEffectivePlatformName(cmMakefile* mf) const CM_OVERRIDE; + bool UseEffectivePlatformName(cmMakefile* mf) const override; - bool ShouldStripResourcePath(cmMakefile*) const CM_OVERRIDE; + bool ShouldStripResourcePath(cmMakefile*) const override; - bool SetGeneratorToolset(std::string const& ts, cmMakefile* mf) CM_OVERRIDE; + bool SetGeneratorToolset(std::string const& ts, cmMakefile* mf) override; void AppendFlag(std::string& flags, std::string const& flag); protected: - void AddExtraIDETargets() CM_OVERRIDE; - void Generate() CM_OVERRIDE; + void AddExtraIDETargets() override; + void Generate() override; private: cmXCodeObject* CreateOrGetPBXGroup(cmGeneratorTarget* gtgt, @@ -144,7 +144,7 @@ private: cmXCodeObject* CreateFlatClone(cmXCodeObject*); cmXCodeObject* CreateXCodeTarget(cmGeneratorTarget* gtgt, cmXCodeObject* buildPhases); - void ForceLinkerLanguages() CM_OVERRIDE; + void ForceLinkerLanguages() override; void ForceLinkerLanguage(cmGeneratorTarget* gtgt); const char* GetTargetLinkFlagsVar(const cmGeneratorTarget* target) const; const char* GetTargetFileType(cmGeneratorTarget* target); @@ -219,11 +219,11 @@ private: std::vector<std::string> const& defines, bool dflag = false); - void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const CM_OVERRIDE; + void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const override; protected: - const char* GetInstallTargetName() const CM_OVERRIDE { return "install"; } - const char* GetPackageTargetName() const CM_OVERRIDE { return "package"; } + const char* GetInstallTargetName() const override { return "install"; } + const char* GetPackageTargetName() const override { return "package"; } unsigned int XcodeVersion; std::string VersionString; @@ -238,7 +238,7 @@ private: bool XcodeBuildCommandInitialized; void PrintCompilerAdvice(std::ostream&, std::string const&, - const char*) const CM_OVERRIDE + const char*) const override { } diff --git a/Source/cmGraphVizWriter.cxx b/Source/cmGraphVizWriter.cxx index b334f41..dd2993d 100644 --- a/Source/cmGraphVizWriter.cxx +++ b/Source/cmGraphVizWriter.cxx @@ -2,7 +2,9 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmGraphVizWriter.h" +#include <cstddef> #include <iostream> +#include <memory> // IWYU pragma: keep #include <sstream> #include <utility> @@ -14,10 +16,20 @@ #include "cmStateSnapshot.h" #include "cmSystemTools.h" #include "cmTarget.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" -static const char* getShapeForTarget(const cmGeneratorTarget* target) +namespace { +enum LinkLibraryScopeType +{ + LLT_SCOPE_PUBLIC, + LLT_SCOPE_PRIVATE, + LLT_SCOPE_INTERFACE +}; + +const char* const GRAPHVIZ_PRIVATE_EDEGE_STYLE = "dashed"; +const char* const GRAPHVIZ_INTERFACE_EDEGE_STYLE = "dotted"; + +const char* getShapeForTarget(const cmGeneratorTarget* target) { if (!target) { return "ellipse"; @@ -39,6 +51,76 @@ static const char* getShapeForTarget(const cmGeneratorTarget* target) return "box"; } +std::map<std::string, LinkLibraryScopeType> getScopedLinkLibrariesFromTarget( + cmTarget* Target) +{ + char sep = ';'; + std::map<std::string, LinkLibraryScopeType> tokens; + size_t start = 0, end = 0; + + const char* pInterfaceLinkLibraries = + Target->GetProperty("INTERFACE_LINK_LIBRARIES"); + const char* pLinkLibraries = Target->GetProperty("LINK_LIBRARIES"); + + if (!pInterfaceLinkLibraries && !pLinkLibraries) { + return tokens; // target is not linked against any other libraries + } + + // make sure we don't touch a null-ptr + auto interfaceLinkLibraries = + std::string(pInterfaceLinkLibraries ? pInterfaceLinkLibraries : ""); + auto linkLibraries = std::string(pLinkLibraries ? pLinkLibraries : ""); + + // first extract interfaceLinkLibraries + while (start < interfaceLinkLibraries.length()) { + + if ((end = interfaceLinkLibraries.find(sep, start)) == std::string::npos) { + end = interfaceLinkLibraries.length(); + } + + std::string element = interfaceLinkLibraries.substr(start, end - start); + if (std::string::npos == element.find("$<LINK_ONLY:", 0)) { + // we assume first, that this library is an interface library. + // if we find it again in the linklibraries property, we promote it to an + // public library. + tokens[element] = LLT_SCOPE_INTERFACE; + } else { + // this is an private linked static library. + // we take care of this case in the second iterator. + } + start = end + 1; + } + + // second extract linkLibraries + start = 0; + while (start < linkLibraries.length()) { + + if ((end = linkLibraries.find(sep, start)) == std::string::npos) { + end = linkLibraries.length(); + } + + std::string element = linkLibraries.substr(start, end - start); + + if (tokens.find(element) == tokens.end()) { + // this library is not found in interfaceLinkLibraries but in + // linkLibraries. + // this results in a private linked library. + tokens[element] = LLT_SCOPE_PRIVATE; + } else if (LLT_SCOPE_INTERFACE == tokens[element]) { + // this library is found in interfaceLinkLibraries and linkLibraries. + // this results in a public linked library. + tokens[element] = LLT_SCOPE_PUBLIC; + } else { + // private and public linked libraries should not be changed anymore. + } + + start = end + 1; + } + + return tokens; +} +} + cmGraphVizWriter::cmGraphVizWriter( const std::vector<cmLocalGenerator*>& localGenerators) : GraphType("digraph") @@ -65,8 +147,8 @@ void cmGraphVizWriter::ReadSettings(const char* settingsFileName, cm.SetHomeOutputDirectory(""); cm.GetCurrentSnapshot().SetDefaultDefinitions(); cmGlobalGenerator ggi(&cm); - CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&ggi, cm.GetCurrentSnapshot())); - CM_AUTO_PTR<cmLocalGenerator> lg(ggi.CreateLocalGenerator(mf.get())); + cmMakefile mf(&ggi, cm.GetCurrentSnapshot()); + std::unique_ptr<cmLocalGenerator> lg(ggi.CreateLocalGenerator(&mf)); const char* inFileName = settingsFileName; @@ -77,7 +159,7 @@ void cmGraphVizWriter::ReadSettings(const char* settingsFileName, } } - if (!mf->ReadListFile(inFileName)) { + if (!mf.ReadListFile(inFileName)) { cmSystemTools::Error("Problem opening GraphViz options file: ", inFileName); return; @@ -87,7 +169,7 @@ void cmGraphVizWriter::ReadSettings(const char* settingsFileName, #define __set_if_set(var, cmakeDefinition) \ { \ - const char* value = mf->GetDefinition(cmakeDefinition); \ + const char* value = mf.GetDefinition(cmakeDefinition); \ if (value) { \ (var) = value; \ } \ @@ -100,9 +182,9 @@ void cmGraphVizWriter::ReadSettings(const char* settingsFileName, #define __set_bool_if_set(var, cmakeDefinition) \ { \ - const char* value = mf->GetDefinition(cmakeDefinition); \ + const char* value = mf.GetDefinition(cmakeDefinition); \ if (value) { \ - (var) = mf->IsOn(cmakeDefinition); \ + (var) = mf.IsOn(cmakeDefinition); \ } \ } @@ -122,10 +204,7 @@ void cmGraphVizWriter::ReadSettings(const char* settingsFileName, std::vector<std::string> ignoreTargetsRegExVector; cmSystemTools::ExpandListArgument(ignoreTargetsRegexes, ignoreTargetsRegExVector); - for (std::vector<std::string>::const_iterator itvIt = - ignoreTargetsRegExVector.begin(); - itvIt != ignoreTargetsRegExVector.end(); ++itvIt) { - std::string currentRegexString(*itvIt); + for (std::string const& currentRegexString : ignoreTargetsRegExVector) { cmsys::RegularExpression currentRegex; if (!currentRegex.compile(currentRegexString.c_str())) { std::cerr << "Could not compile bad regex \"" << currentRegexString @@ -146,20 +225,18 @@ void cmGraphVizWriter::WriteTargetDependersFiles(const char* fileName) this->CollectTargetsAndLibs(); - for (std::map<std::string, const cmGeneratorTarget*>::const_iterator ptrIt = - this->TargetPtrs.begin(); - ptrIt != this->TargetPtrs.end(); ++ptrIt) { - if (ptrIt->second == nullptr) { + for (auto const& ptr : this->TargetPtrs) { + if (ptr.second == nullptr) { continue; } - if (!this->GenerateForTargetType(ptrIt->second->GetType())) { + if (!this->GenerateForTargetType(ptr.second->GetType())) { continue; } std::string currentFilename = fileName; currentFilename += "."; - currentFilename += ptrIt->first; + currentFilename += ptr.first; currentFilename += ".dependers"; cmGeneratedFileStream str(currentFilename.c_str()); @@ -173,7 +250,7 @@ void cmGraphVizWriter::WriteTargetDependersFiles(const char* fileName) std::cout << "Writing " << currentFilename << "..." << std::endl; this->WriteHeader(str); - this->WriteDependerConnections(ptrIt->first, insertedNodes, + this->WriteDependerConnections(ptr.first, insertedNodes, insertedConnections, str); this->WriteFooter(str); @@ -190,14 +267,12 @@ void cmGraphVizWriter::WritePerTargetFiles(const char* fileName) this->CollectTargetsAndLibs(); - for (std::map<std::string, const cmGeneratorTarget*>::const_iterator ptrIt = - this->TargetPtrs.begin(); - ptrIt != this->TargetPtrs.end(); ++ptrIt) { - if (ptrIt->second == nullptr) { + for (auto const& ptr : this->TargetPtrs) { + if (ptr.second == nullptr) { continue; } - if (!this->GenerateForTargetType(ptrIt->second->GetType())) { + if (!this->GenerateForTargetType(ptr.second->GetType())) { continue; } @@ -206,7 +281,7 @@ void cmGraphVizWriter::WritePerTargetFiles(const char* fileName) std::string currentFilename = fileName; currentFilename += "."; - currentFilename += ptrIt->first; + currentFilename += ptr.first; cmGeneratedFileStream str(currentFilename.c_str()); if (!str) { return; @@ -215,8 +290,7 @@ void cmGraphVizWriter::WritePerTargetFiles(const char* fileName) std::cout << "Writing " << currentFilename << "..." << std::endl; this->WriteHeader(str); - this->WriteConnections(ptrIt->first, insertedNodes, insertedConnections, - str); + this->WriteConnections(ptr.first, insertedNodes, insertedConnections, str); this->WriteFooter(str); } } @@ -236,19 +310,16 @@ void cmGraphVizWriter::WriteGlobalFile(const char* fileName) std::set<std::string> insertedConnections; std::set<std::string> insertedNodes; - for (std::map<std::string, const cmGeneratorTarget*>::const_iterator ptrIt = - this->TargetPtrs.begin(); - ptrIt != this->TargetPtrs.end(); ++ptrIt) { - if (ptrIt->second == nullptr) { + for (auto const& ptr : this->TargetPtrs) { + if (ptr.second == nullptr) { continue; } - if (!this->GenerateForTargetType(ptrIt->second->GetType())) { + if (!this->GenerateForTargetType(ptr.second->GetType())) { continue; } - this->WriteConnections(ptrIt->first, insertedNodes, insertedConnections, - str); + this->WriteConnections(ptr.first, insertedNodes, insertedConnections, str); } this->WriteFooter(str); } @@ -284,13 +355,11 @@ void cmGraphVizWriter::WriteConnections( } std::string myNodeName = this->TargetNamesNodes.find(targetName)->second; + std::map<std::string, LinkLibraryScopeType> ll = + getScopedLinkLibrariesFromTarget(targetPtrIt->second->Target); - const cmTarget::LinkLibraryVectorType* ll = - &(targetPtrIt->second->Target->GetOriginalLinkLibraries()); - - for (cmTarget::LinkLibraryVectorType::const_iterator llit = ll->begin(); - llit != ll->end(); ++llit) { - const char* libName = llit->first.c_str(); + for (auto const& llit : ll) { + const char* libName = llit.first.c_str(); std::map<std::string, std::string>::const_iterator libNameIt = this->TargetNamesNodes.find(libName); @@ -309,6 +378,18 @@ void cmGraphVizWriter::WriteConnections( insertedNodes, str); str << " \"" << myNodeName << "\" -> \"" << libNameIt->second << "\""; + + switch (llit.second) { + case LLT_SCOPE_PRIVATE: + str << "[style = " << GRAPHVIZ_PRIVATE_EDEGE_STYLE << "]"; + break; + case LLT_SCOPE_INTERFACE: + str << "[style = " << GRAPHVIZ_INTERFACE_EDEGE_STYLE << "]"; + break; + default: + break; + } + str << " // " << targetName << " -> " << libName << std::endl; this->WriteConnections(libName, insertedNodes, insertedConnections, str); } @@ -337,29 +418,26 @@ void cmGraphVizWriter::WriteDependerConnections( std::string myNodeName = this->TargetNamesNodes.find(targetName)->second; // now search who links against me - for (std::map<std::string, const cmGeneratorTarget*>::const_iterator - dependerIt = this->TargetPtrs.begin(); - dependerIt != this->TargetPtrs.end(); ++dependerIt) { - if (dependerIt->second == nullptr) { + for (auto const& tptr : this->TargetPtrs) { + if (tptr.second == nullptr) { continue; } - if (!this->GenerateForTargetType(dependerIt->second->GetType())) { + if (!this->GenerateForTargetType(tptr.second->GetType())) { continue; } // Now we have a target, check whether it links against targetName. // If so, draw a connection, and then continue with dependers on that one. const cmTarget::LinkLibraryVectorType* ll = - &(dependerIt->second->Target->GetOriginalLinkLibraries()); + &(tptr.second->Target->GetOriginalLinkLibraries()); - for (cmTarget::LinkLibraryVectorType::const_iterator llit = ll->begin(); - llit != ll->end(); ++llit) { - std::string libName = llit->first; + for (auto const& llit : *ll) { + std::string libName = llit.first; if (libName == targetName) { // So this target links against targetName. std::map<std::string, std::string>::const_iterator dependerNodeNameIt = - this->TargetNamesNodes.find(dependerIt->first); + this->TargetNamesNodes.find(tptr.first); if (dependerNodeNameIt != this->TargetNamesNodes.end()) { std::string connectionName = dependerNodeNameIt->second; @@ -369,14 +447,12 @@ void cmGraphVizWriter::WriteDependerConnections( if (insertedConnections.find(connectionName) == insertedConnections.end()) { insertedConnections.insert(connectionName); - this->WriteNode(dependerIt->first, dependerIt->second, - insertedNodes, str); + this->WriteNode(tptr.first, tptr.second, insertedNodes, str); str << " \"" << dependerNodeNameIt->second << "\" -> \"" << myNodeName << "\""; - str << " // " << targetName << " -> " << dependerIt->first - << std::endl; - this->WriteDependerConnections(dependerIt->first, insertedNodes, + str << " // " << targetName << " -> " << tptr.first << std::endl; + this->WriteDependerConnections(tptr.first, insertedNodes, insertedConnections, str); } } @@ -416,14 +492,10 @@ int cmGraphVizWriter::CollectAllTargets() { int cnt = 0; // First pass get the list of all cmake targets - for (std::vector<cmLocalGenerator*>::const_iterator lit = - this->LocalGenerators.begin(); - lit != this->LocalGenerators.end(); ++lit) { - const std::vector<cmGeneratorTarget*>& targets = - (*lit)->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator it = targets.begin(); - it != targets.end(); ++it) { - const char* realTargetName = (*it)->GetName().c_str(); + for (cmLocalGenerator* lg : this->LocalGenerators) { + const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets(); + for (cmGeneratorTarget* target : targets) { + const char* realTargetName = target->GetName().c_str(); if (this->IgnoreThisTarget(realTargetName)) { // Skip ignored targets continue; @@ -432,7 +504,7 @@ int cmGraphVizWriter::CollectAllTargets() std::ostringstream ostr; ostr << this->GraphNodePrefix << cnt++; this->TargetNamesNodes[realTargetName] = ostr.str(); - this->TargetPtrs[realTargetName] = *it; + this->TargetPtrs[realTargetName] = target; } } @@ -442,23 +514,18 @@ int cmGraphVizWriter::CollectAllTargets() int cmGraphVizWriter::CollectAllExternalLibs(int cnt) { // Ok, now find all the stuff we link to that is not in cmake - for (std::vector<cmLocalGenerator*>::const_iterator lit = - this->LocalGenerators.begin(); - lit != this->LocalGenerators.end(); ++lit) { - const std::vector<cmGeneratorTarget*>& targets = - (*lit)->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator it = targets.begin(); - it != targets.end(); ++it) { - const char* realTargetName = (*it)->GetName().c_str(); + for (cmLocalGenerator* lg : this->LocalGenerators) { + const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets(); + for (cmGeneratorTarget* target : targets) { + const char* realTargetName = target->GetName().c_str(); if (this->IgnoreThisTarget(realTargetName)) { // Skip ignored targets continue; } const cmTarget::LinkLibraryVectorType* ll = - &((*it)->Target->GetOriginalLinkLibraries()); - for (cmTarget::LinkLibraryVectorType::const_iterator llit = ll->begin(); - llit != ll->end(); ++llit) { - const char* libName = llit->first.c_str(); + &(target->Target->GetOriginalLinkLibraries()); + for (auto const& llit : *ll) { + const char* libName = llit.first.c_str(); if (this->IgnoreThisTarget(libName)) { // Skip ignored targets continue; @@ -482,10 +549,7 @@ int cmGraphVizWriter::CollectAllExternalLibs(int cnt) bool cmGraphVizWriter::IgnoreThisTarget(const std::string& name) { - for (std::vector<cmsys::RegularExpression>::iterator itvIt = - this->TargetsToIgnoreRegex.begin(); - itvIt != this->TargetsToIgnoreRegex.end(); ++itvIt) { - cmsys::RegularExpression& regEx = *itvIt; + for (cmsys::RegularExpression& regEx : this->TargetsToIgnoreRegex) { if (regEx.is_valid()) { if (regEx.find(name)) { return true; diff --git a/Source/cmIfCommand.cxx b/Source/cmIfCommand.cxx index 0972664..4926f22 100644 --- a/Source/cmIfCommand.cxx +++ b/Source/cmIfCommand.cxx @@ -8,17 +8,17 @@ #include "cmMakefile.h" #include "cmOutputConverter.h" #include "cmSystemTools.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" +#include <memory> // IWYU pragma: keep + static std::string cmIfCommandError( std::vector<cmExpandedCommandArgument> const& args) { std::string err = "given arguments:\n "; - for (std::vector<cmExpandedCommandArgument>::const_iterator i = args.begin(); - i != args.end(); ++i) { + for (cmExpandedCommandArgument const& i : args) { err += " "; - err += cmOutputConverter::EscapeForCMake(i->GetValue()); + err += cmOutputConverter::EscapeForCMake(i.GetValue()); } err += "\n"; return err; @@ -37,7 +37,8 @@ bool cmIfFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff, // if this is the endif for this if statement, then start executing if (!this->ScopeDepth) { // Remove the function blocker for this scope or bail. - CM_AUTO_PTR<cmFunctionBlocker> fb(mf.RemoveFunctionBlocker(this, lff)); + std::unique_ptr<cmFunctionBlocker> fb( + mf.RemoveFunctionBlocker(this, lff)); if (!fb.get()) { return false; } @@ -45,21 +46,20 @@ bool cmIfFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff, // execute the functions for the true parts of the if statement cmExecutionStatus status; int scopeDepth = 0; - for (unsigned int c = 0; c < this->Functions.size(); ++c) { + for (cmListFileFunction const& func : this->Functions) { // keep track of scope depth - if (!cmSystemTools::Strucmp(this->Functions[c].Name.c_str(), "if")) { + if (!cmSystemTools::Strucmp(func.Name.c_str(), "if")) { scopeDepth++; } - if (!cmSystemTools::Strucmp(this->Functions[c].Name.c_str(), - "endif")) { + if (!cmSystemTools::Strucmp(func.Name.c_str(), "endif")) { scopeDepth--; } // watch for our state change if (scopeDepth == 0 && - !cmSystemTools::Strucmp(this->Functions[c].Name.c_str(), "else")) { + !cmSystemTools::Strucmp(func.Name.c_str(), "else")) { if (this->ElseSeen) { - cmListFileBacktrace bt = mf.GetBacktrace(this->Functions[c]); + cmListFileBacktrace bt = mf.GetBacktrace(func); mf.GetCMakeInstance()->IssueMessage( cmake::FATAL_ERROR, "A duplicate ELSE command was found inside an IF block.", bt); @@ -74,13 +74,12 @@ bool cmIfFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff, // if trace is enabled, print a (trivially) evaluated "else" // statement if (!this->IsBlocking && mf.GetCMakeInstance()->GetTrace()) { - mf.PrintCommandTrace(this->Functions[c]); + mf.PrintCommandTrace(func); } } else if (scopeDepth == 0 && - !cmSystemTools::Strucmp(this->Functions[c].Name.c_str(), - "elseif")) { + !cmSystemTools::Strucmp(func.Name.c_str(), "elseif")) { if (this->ElseSeen) { - cmListFileBacktrace bt = mf.GetBacktrace(this->Functions[c]); + cmListFileBacktrace bt = mf.GetBacktrace(func); mf.GetCMakeInstance()->IssueMessage( cmake::FATAL_ERROR, "An ELSEIF command was found after an ELSE command.", bt); @@ -93,23 +92,22 @@ bool cmIfFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff, } else { // if trace is enabled, print the evaluated "elseif" statement if (mf.GetCMakeInstance()->GetTrace()) { - mf.PrintCommandTrace(this->Functions[c]); + mf.PrintCommandTrace(func); } std::string errorString; std::vector<cmExpandedCommandArgument> expandedArguments; - mf.ExpandArguments(this->Functions[c].Arguments, - expandedArguments); + mf.ExpandArguments(func.Arguments, expandedArguments); cmake::MessageType messType; cmListFileContext conditionContext = cmListFileContext::FromCommandContext( - this->Functions[c], this->GetStartingContext().FilePath); + func, this->GetStartingContext().FilePath); - cmConditionEvaluator conditionEvaluator( - mf, conditionContext, mf.GetBacktrace(this->Functions[c])); + cmConditionEvaluator conditionEvaluator(mf, conditionContext, + mf.GetBacktrace(func)); bool isTrue = conditionEvaluator.IsTrue(expandedArguments, errorString, messType); @@ -117,7 +115,7 @@ bool cmIfFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff, if (!errorString.empty()) { std::string err = cmIfCommandError(expandedArguments); err += errorString; - cmListFileBacktrace bt = mf.GetBacktrace(this->Functions[c]); + cmListFileBacktrace bt = mf.GetBacktrace(func); mf.GetCMakeInstance()->IssueMessage(messType, err, bt); if (messType == cmake::FATAL_ERROR) { cmSystemTools::SetFatalErrorOccured(); @@ -135,7 +133,7 @@ bool cmIfFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff, // should we execute? else if (!this->IsBlocking) { status.Clear(); - mf.ExecuteCommand(this->Functions[c], status); + mf.ExecuteCommand(func, status); if (status.GetReturnInvoked()) { inStatus.SetReturnInvoked(); return true; diff --git a/Source/cmIfCommand.h b/Source/cmIfCommand.h index da2fce9..e3d30dd 100644 --- a/Source/cmIfCommand.h +++ b/Source/cmIfCommand.h @@ -25,10 +25,10 @@ public: this->ElseSeen = false; this->ScopeDepth = 0; } - ~cmIfFunctionBlocker() CM_OVERRIDE {} + ~cmIfFunctionBlocker() override {} bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf, - cmExecutionStatus&) CM_OVERRIDE; - bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf) CM_OVERRIDE; + cmExecutionStatus&) override; + bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf) override; std::vector<cmListFileArgument> Args; std::vector<cmListFileFunction> Functions; @@ -45,21 +45,21 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmIfCommand; } + cmCommand* Clone() override { return new cmIfCommand; } /** * This overrides the default InvokeInitialPass implementation. * It records the arguments before expansion. */ bool InvokeInitialPass(const std::vector<cmListFileArgument>& args, - cmExecutionStatus&) CM_OVERRIDE; + cmExecutionStatus&) override; /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const&, - cmExecutionStatus&) CM_OVERRIDE + cmExecutionStatus&) override { return false; } diff --git a/Source/cmIncludeCommand.h b/Source/cmIncludeCommand.h index ceda931..3b843b2 100644 --- a/Source/cmIncludeCommand.h +++ b/Source/cmIncludeCommand.h @@ -24,14 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmIncludeCommand; } + cmCommand* Clone() override { return new cmIncludeCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmIncludeDirectoryCommand.cxx b/Source/cmIncludeDirectoryCommand.cxx index b81f7cb..4c30607 100644 --- a/Source/cmIncludeDirectoryCommand.cxx +++ b/Source/cmIncludeDirectoryCommand.cxx @@ -116,7 +116,7 @@ void cmIncludeDirectoryCommand::NormalizeInclude(std::string& inc) if ((b != std::string::npos) && (e != std::string::npos)) { inc.assign(inc, b, 1 + e - b); // copy the remaining substring } else { - inc = ""; + inc.clear(); return; } diff --git a/Source/cmIncludeDirectoryCommand.h b/Source/cmIncludeDirectoryCommand.h index a7b3685..01d98db 100644 --- a/Source/cmIncludeDirectoryCommand.h +++ b/Source/cmIncludeDirectoryCommand.h @@ -24,14 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmIncludeDirectoryCommand; } + cmCommand* Clone() override { return new cmIncludeDirectoryCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; protected: // used internally diff --git a/Source/cmIncludeExternalMSProjectCommand.cxx b/Source/cmIncludeExternalMSProjectCommand.cxx index 03388c7..bd16b1d 100644 --- a/Source/cmIncludeExternalMSProjectCommand.cxx +++ b/Source/cmIncludeExternalMSProjectCommand.cxx @@ -91,9 +91,8 @@ bool cmIncludeExternalMSProjectCommand::InitialPass( if (!platformMapping.empty()) target->SetProperty("VS_PLATFORM_MAPPING", platformMapping.c_str()); - for (std::vector<std::string>::const_iterator it = depends.begin(); - it != depends.end(); ++it) { - target->AddUtility(it->c_str()); + for (std::string const& d : depends) { + target->AddUtility(d.c_str()); } } #endif diff --git a/Source/cmIncludeExternalMSProjectCommand.h b/Source/cmIncludeExternalMSProjectCommand.h index 88ee2f8..945acdc 100644 --- a/Source/cmIncludeExternalMSProjectCommand.h +++ b/Source/cmIncludeExternalMSProjectCommand.h @@ -25,17 +25,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE - { - return new cmIncludeExternalMSProjectCommand; - } + cmCommand* Clone() override { return new cmIncludeExternalMSProjectCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmIncludeGuardCommand.h b/Source/cmIncludeGuardCommand.h index 4dc3d90..eaad9b8 100644 --- a/Source/cmIncludeGuardCommand.h +++ b/Source/cmIncludeGuardCommand.h @@ -24,14 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmIncludeGuardCommand; } + cmCommand* Clone() override { return new cmIncludeGuardCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmIncludeRegularExpressionCommand.h b/Source/cmIncludeRegularExpressionCommand.h index 3ea0443..8da991d 100644 --- a/Source/cmIncludeRegularExpressionCommand.h +++ b/Source/cmIncludeRegularExpressionCommand.h @@ -24,17 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE - { - return new cmIncludeRegularExpressionCommand; - } + cmCommand* Clone() override { return new cmIncludeRegularExpressionCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmInstallCommand.cxx b/Source/cmInstallCommand.cxx index 7402105..685fc67 100644 --- a/Source/cmInstallCommand.cxx +++ b/Source/cmInstallCommand.cxx @@ -141,23 +141,23 @@ bool cmInstallCommand::HandleScriptMode(std::vector<std::string> const& args) // Scan the args again, this time adding install generators each time we // encounter a SCRIPT or CODE arg: // - for (size_t i = 0; i < args.size(); ++i) { - if (args[i] == "SCRIPT") { + for (std::string const& arg : args) { + if (arg == "SCRIPT") { doing_script = true; doing_code = false; - } else if (args[i] == "CODE") { + } else if (arg == "CODE") { doing_script = false; doing_code = true; - } else if (args[i] == "COMPONENT") { + } else if (arg == "COMPONENT") { doing_script = false; doing_code = false; } else if (doing_script) { doing_script = false; - std::string script = args[i]; + std::string script = arg; if (!cmSystemTools::FileIsFullPath(script.c_str())) { script = this->Makefile->GetCurrentSourceDirectory(); script += "/"; - script += args[i]; + script += arg; } if (cmSystemTools::FileIsDirectory(script)) { this->SetError("given a directory as value of SCRIPT argument."); @@ -167,7 +167,7 @@ bool cmInstallCommand::HandleScriptMode(std::vector<std::string> const& args) script.c_str(), false, component.c_str(), exclude_from_all)); } else if (doing_code) { doing_code = false; - std::string const& code = args[i]; + std::string const& code = arg; this->Makefile->AddInstallGenerator(new cmInstallScriptGenerator( code.c_str(), true, component.c_str(), exclude_from_all)); } @@ -336,19 +336,16 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args) (this->Makefile->IsOn("WIN32") || this->Makefile->IsOn("CYGWIN") || this->Makefile->IsOn("MINGW")); - for (std::vector<std::string>::const_iterator targetIt = - targetList.GetVector().begin(); - targetIt != targetList.GetVector().end(); ++targetIt) { + for (std::string const& tgt : targetList.GetVector()) { - if (this->Makefile->IsAlias(*targetIt)) { + if (this->Makefile->IsAlias(tgt)) { std::ostringstream e; - e << "TARGETS given target \"" << (*targetIt) << "\" which is an alias."; + e << "TARGETS given target \"" << tgt << "\" which is an alias."; this->SetError(e.str()); return false; } // Lookup this target in the current directory. - if (cmTarget* target = - this->Makefile->FindLocalNonAliasTarget(*targetIt)) { + if (cmTarget* target = this->Makefile->FindLocalNonAliasTarget(tgt)) { // Found the target. Check its type. if (target->GetType() != cmStateEnums::EXECUTABLE && target->GetType() != cmStateEnums::STATIC_LIBRARY && @@ -357,7 +354,7 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args) target->GetType() != cmStateEnums::OBJECT_LIBRARY && target->GetType() != cmStateEnums::INTERFACE_LIBRARY) { std::ostringstream e; - e << "TARGETS given target \"" << (*targetIt) + e << "TARGETS given target \"" << tgt << "\" which is not an executable, library, or module."; this->SetError(e.str()); return false; @@ -367,7 +364,7 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args) if (!this->Makefile->GetGlobalGenerator()->HasKnownObjectFileLocation( &reason)) { std::ostringstream e; - e << "TARGETS given OBJECT library \"" << (*targetIt) + e << "TARGETS given OBJECT library \"" << tgt << "\" which may not be installed" << reason << "."; this->SetError(e.str()); return false; @@ -378,7 +375,7 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args) } else { // Did not find the target. std::ostringstream e; - e << "TARGETS given target \"" << (*targetIt) + e << "TARGETS given target \"" << tgt << "\" which does not exist in this directory."; this->SetError(e.str()); return false; @@ -398,10 +395,9 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args) bool installsResource = false; // Generate install script code to install the given targets. - for (std::vector<cmTarget*>::iterator ti = targets.begin(); - ti != targets.end(); ++ti) { + for (cmTarget* ti : targets) { // Handle each target type. - cmTarget& target = *(*ti); + cmTarget& target = *ti; cmInstallTargetGenerator* archiveGenerator = nullptr; cmInstallTargetGenerator* libraryGenerator = nullptr; cmInstallTargetGenerator* runtimeGenerator = nullptr; @@ -815,9 +811,8 @@ bool cmInstallCommand::HandleFilesMode(std::vector<std::string> const& args) this->Makefile->GetPolicyStatus(cmPolicies::CMP0062); cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator(); - for (std::vector<std::string>::const_iterator fileIt = filesVector.begin(); - fileIt != filesVector.end(); ++fileIt) { - if (gg->IsExportedTargetsFile(*fileIt)) { + for (std::string const& file : filesVector) { + if (gg->IsExportedTargetsFile(file)) { const char* modal = nullptr; std::ostringstream e; cmake::MessageType messageType = cmake::AUTHOR_WARNING; @@ -835,8 +830,8 @@ bool cmInstallCommand::HandleFilesMode(std::vector<std::string> const& args) messageType = cmake::FATAL_ERROR; } if (modal) { - e << "The file\n " << *fileIt << "\nwas generated by the export() " - "command. It " + e << "The file\n " << file << "\nwas generated by the export() " + "command. It " << modal << " not be installed with the " "install() command. Use the install(EXPORT) mechanism " "instead. See the cmake-packages(7) manual for more.\n"; @@ -1339,10 +1334,7 @@ bool cmInstallCommand::HandleExportMode(std::vector<std::string> const& args) cmExportSet* exportSet = this->Makefile->GetGlobalGenerator()->GetExportSets()[exp.GetString()]; if (exportOld.IsEnabled()) { - for (std::vector<cmTargetExport*>::const_iterator tei = - exportSet->GetTargetExports()->begin(); - tei != exportSet->GetTargetExports()->end(); ++tei) { - cmTargetExport const* te = *tei; + for (cmTargetExport* te : *exportSet->GetTargetExports()) { cmTarget* tgt = this->Makefile->GetGlobalGenerator()->FindTarget(te->TargetName); const bool newCMP0022Behavior = @@ -1379,20 +1371,19 @@ bool cmInstallCommand::MakeFilesFullPath( const char* modeName, const std::vector<std::string>& relFiles, std::vector<std::string>& absFiles) { - for (std::vector<std::string>::const_iterator fileIt = relFiles.begin(); - fileIt != relFiles.end(); ++fileIt) { - std::string file = (*fileIt); + for (std::string const& relFile : relFiles) { + std::string file = relFile; std::string::size_type gpos = cmGeneratorExpression::Find(file); if (gpos != 0 && !cmSystemTools::FileIsFullPath(file.c_str())) { file = this->Makefile->GetCurrentSourceDirectory(); file += "/"; - file += *fileIt; + file += relFile; } // Make sure the file is not a directory. if (gpos == std::string::npos && cmSystemTools::FileIsDirectory(file)) { std::ostringstream e; - e << modeName << " given directory \"" << (*fileIt) << "\" to install."; + e << modeName << " given directory \"" << relFile << "\" to install."; this->SetError(e.str()); return false; } diff --git a/Source/cmInstallCommand.h b/Source/cmInstallCommand.h index b34f560..8bd0159 100644 --- a/Source/cmInstallCommand.h +++ b/Source/cmInstallCommand.h @@ -24,14 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmInstallCommand; } + cmCommand* Clone() override { return new cmInstallCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: bool HandleScriptMode(std::vector<std::string> const& args); diff --git a/Source/cmInstallCommandArguments.cxx b/Source/cmInstallCommandArguments.cxx index 072d2a5..ff6420d 100644 --- a/Source/cmInstallCommandArguments.cxx +++ b/Source/cmInstallCommandArguments.cxx @@ -153,11 +153,9 @@ void cmInstallCommandArguments::Parse(const std::vector<std::string>* args, bool cmInstallCommandArguments::CheckPermissions() { - this->PermissionsString = ""; - for (std::vector<std::string>::const_iterator permIt = - this->Permissions.GetVector().begin(); - permIt != this->Permissions.GetVector().end(); ++permIt) { - if (!this->CheckPermissions(*permIt, this->PermissionsString)) { + this->PermissionsString.clear(); + for (std::string const& perm : this->Permissions.GetVector()) { + if (!this->CheckPermissions(perm, this->PermissionsString)) { return false; } } diff --git a/Source/cmInstallDirectoryGenerator.cxx b/Source/cmInstallDirectoryGenerator.cxx index 1ca9893..e4209bd 100644 --- a/Source/cmInstallDirectoryGenerator.cxx +++ b/Source/cmInstallDirectoryGenerator.cxx @@ -7,7 +7,8 @@ #include "cmLocalGenerator.h" #include "cmMakefile.h" #include "cmSystemTools.h" -#include "cm_auto_ptr.hxx" + +#include <memory> // IWYU pragma: keep cmInstallDirectoryGenerator::cmInstallDirectoryGenerator( std::vector<std::string> const& dirs, const char* dest, @@ -62,19 +63,17 @@ void cmInstallDirectoryGenerator::GenerateScriptForConfig( { std::vector<std::string> dirs; cmGeneratorExpression ge; - for (std::vector<std::string>::const_iterator i = this->Directories.begin(); - i != this->Directories.end(); ++i) { - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(*i); + for (std::string const& d : this->Directories) { + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(d); cmSystemTools::ExpandListArgument( cge->Evaluate(this->LocalGenerator, config), dirs); } // Make sure all dirs have absolute paths. cmMakefile const& mf = *this->LocalGenerator->GetMakefile(); - for (std::vector<std::string>::iterator i = dirs.begin(); i != dirs.end(); - ++i) { - if (!cmSystemTools::FileIsFullPath(i->c_str())) { - *i = std::string(mf.GetCurrentSourceDirectory()) + "/" + *i; + for (std::string& d : dirs) { + if (!cmSystemTools::FileIsFullPath(d.c_str())) { + d = std::string(mf.GetCurrentSourceDirectory()) + "/" + d; } } diff --git a/Source/cmInstallDirectoryGenerator.h b/Source/cmInstallDirectoryGenerator.h index d699599..ac6e504 100644 --- a/Source/cmInstallDirectoryGenerator.h +++ b/Source/cmInstallDirectoryGenerator.h @@ -27,16 +27,16 @@ public: const char* component, MessageLevel message, bool exclude_from_all, const char* literal_args, bool optional = false); - ~cmInstallDirectoryGenerator() CM_OVERRIDE; + ~cmInstallDirectoryGenerator() override; - void Compute(cmLocalGenerator* lg) CM_OVERRIDE; + void Compute(cmLocalGenerator* lg) override; std::string GetDestination(std::string const& config) const; protected: - void GenerateScriptActions(std::ostream& os, Indent indent) CM_OVERRIDE; + void GenerateScriptActions(std::ostream& os, Indent indent) override; void GenerateScriptForConfig(std::ostream& os, const std::string& config, - Indent indent) CM_OVERRIDE; + Indent indent) override; void AddDirectoryInstallRule(std::ostream& os, const std::string& config, Indent indent, std::vector<std::string> const& dirs); diff --git a/Source/cmInstallExportGenerator.cxx b/Source/cmInstallExportGenerator.cxx index ec1b210..fdd231c 100644 --- a/Source/cmInstallExportGenerator.cxx +++ b/Source/cmInstallExportGenerator.cxx @@ -3,7 +3,6 @@ #include "cmInstallExportGenerator.h" #include <algorithm> -#include <map> #include <sstream> #include <utility> @@ -111,11 +110,9 @@ size_t cmInstallExportGenerator::GetMaxConfigLength() const len = this->ConfigurationName.size(); } } else { - for (std::vector<std::string>::const_iterator ci = - this->ConfigurationTypes->begin(); - ci != this->ConfigurationTypes->end(); ++ci) { - if (ci->size() > len) { - len = ci->size(); + for (std::string const& c : *this->ConfigurationTypes) { + if (c.size() > len) { + len = c.size(); } } } @@ -153,10 +150,8 @@ void cmInstallExportGenerator::GenerateScript(std::ostream& os) this->EFGen->AddConfiguration(""); } } else { - for (std::vector<std::string>::const_iterator ci = - this->ConfigurationTypes->begin(); - ci != this->ConfigurationTypes->end(); ++ci) { - this->EFGen->AddConfiguration(*ci); + for (std::string const& c : *this->ConfigurationTypes) { + this->EFGen->AddConfiguration(c); } } this->EFGen->GenerateImportFile(); @@ -174,11 +169,9 @@ void cmInstallExportGenerator::GenerateScriptConfigs(std::ostream& os, // Now create a configuration-specific install rule for the import // file of each configuration. std::vector<std::string> files; - for (std::map<std::string, std::string>::const_iterator i = - this->EFGen->GetConfigImportFiles().begin(); - i != this->EFGen->GetConfigImportFiles().end(); ++i) { - files.push_back(i->second); - std::string config_test = this->CreateConfigTest(i->first); + for (auto const& i : this->EFGen->GetConfigImportFiles()) { + files.push_back(i.second); + std::string config_test = this->CreateConfigTest(i.first); os << indent << "if(" << config_test << ")\n"; this->AddInstallRule(os, this->Destination, cmInstallType_FILES, files, false, this->FilePermissions.c_str(), nullptr, diff --git a/Source/cmInstallExportGenerator.h b/Source/cmInstallExportGenerator.h index 35c7743..d23cf06 100644 --- a/Source/cmInstallExportGenerator.h +++ b/Source/cmInstallExportGenerator.h @@ -30,11 +30,11 @@ public: bool exclude_from_all, const char* filename, const char* name_space, bool exportOld, bool android); - ~cmInstallExportGenerator() CM_OVERRIDE; + ~cmInstallExportGenerator() override; cmExportSet* GetExportSet() { return this->ExportSet; } - void Compute(cmLocalGenerator* lg) CM_OVERRIDE; + void Compute(cmLocalGenerator* lg) override; cmLocalGenerator* GetLocalGenerator() const { return this->LocalGenerator; } @@ -43,9 +43,9 @@ public: std::string const& GetDestination() const { return this->Destination; } protected: - void GenerateScript(std::ostream& os) CM_OVERRIDE; - void GenerateScriptConfigs(std::ostream& os, Indent indent) CM_OVERRIDE; - void GenerateScriptActions(std::ostream& os, Indent indent) CM_OVERRIDE; + void GenerateScript(std::ostream& os) override; + void GenerateScriptConfigs(std::ostream& os, Indent indent) override; + void GenerateScriptActions(std::ostream& os, Indent indent) override; void GenerateImportFile(cmExportSet const* exportSet); void GenerateImportFile(const char* config, cmExportSet const* exportSet); void ComputeTempDir(); diff --git a/Source/cmInstallFilesCommand.h b/Source/cmInstallFilesCommand.h index 702b332..19f2559 100644 --- a/Source/cmInstallFilesCommand.h +++ b/Source/cmInstallFilesCommand.h @@ -24,14 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmInstallFilesCommand; } + cmCommand* Clone() override { return new cmInstallFilesCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; /** * This is called at the end after all the information @@ -39,8 +39,8 @@ public: * not implement this method. At this point, reading and * writing to the cache can be done. */ - void FinalPass() CM_OVERRIDE; - bool HasFinalPass() const CM_OVERRIDE { return !this->IsFilesForm; } + void FinalPass() override; + bool HasFinalPass() const override { return !this->IsFilesForm; } protected: void CreateInstallGenerator() const; diff --git a/Source/cmInstallFilesGenerator.cxx b/Source/cmInstallFilesGenerator.cxx index 4fcff4f..68e3f86 100644 --- a/Source/cmInstallFilesGenerator.cxx +++ b/Source/cmInstallFilesGenerator.cxx @@ -5,7 +5,8 @@ #include "cmGeneratorExpression.h" #include "cmInstallType.h" #include "cmSystemTools.h" -#include "cm_auto_ptr.hxx" + +#include <memory> // IWYU pragma: keep class cmLocalGenerator; @@ -81,9 +82,8 @@ void cmInstallFilesGenerator::GenerateScriptForConfig( { std::vector<std::string> files; cmGeneratorExpression ge; - for (std::vector<std::string>::const_iterator i = this->Files.begin(); - i != this->Files.end(); ++i) { - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(*i); + for (std::string const& f : this->Files) { + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(f); cmSystemTools::ExpandListArgument( cge->Evaluate(this->LocalGenerator, config), files); } diff --git a/Source/cmInstallFilesGenerator.h b/Source/cmInstallFilesGenerator.h index b2c7c4b..0ef2a06 100644 --- a/Source/cmInstallFilesGenerator.h +++ b/Source/cmInstallFilesGenerator.h @@ -27,16 +27,16 @@ public: const char* component, MessageLevel message, bool exclude_from_all, const char* rename, bool optional = false); - ~cmInstallFilesGenerator() CM_OVERRIDE; + ~cmInstallFilesGenerator() override; - void Compute(cmLocalGenerator* lg) CM_OVERRIDE; + void Compute(cmLocalGenerator* lg) override; std::string GetDestination(std::string const& config) const; protected: - void GenerateScriptActions(std::ostream& os, Indent indent) CM_OVERRIDE; + void GenerateScriptActions(std::ostream& os, Indent indent) override; void GenerateScriptForConfig(std::ostream& os, const std::string& config, - Indent indent) CM_OVERRIDE; + Indent indent) override; void AddFilesInstallRule(std::ostream& os, std::string const& config, Indent indent, std::vector<std::string> const& files); diff --git a/Source/cmInstallGenerator.cxx b/Source/cmInstallGenerator.cxx index 3fbb3af..4d01978 100644 --- a/Source/cmInstallGenerator.cxx +++ b/Source/cmInstallGenerator.cxx @@ -113,9 +113,8 @@ void cmInstallGenerator::AddInstallRule( if (files.size() == 1) { os << " \"" << files[0] << "\""; } else { - for (std::vector<std::string>::const_iterator fi = files.begin(); - fi != files.end(); ++fi) { - os << "\n" << indent << " \"" << *fi << "\""; + for (std::string const& f : files) { + os << "\n" << indent << " \"" << f << "\""; } os << "\n" << indent << " "; if (!(literal_args && *literal_args)) { diff --git a/Source/cmInstallGenerator.h b/Source/cmInstallGenerator.h index 813cbe8..fc1ce86 100644 --- a/Source/cmInstallGenerator.h +++ b/Source/cmInstallGenerator.h @@ -36,7 +36,7 @@ public: std::vector<std::string> const& configurations, const char* component, MessageLevel message, bool exclude_from_all); - ~cmInstallGenerator() CM_OVERRIDE; + ~cmInstallGenerator() override; void AddInstallRule( std::ostream& os, std::string const& dest, cmInstallType type, @@ -58,7 +58,7 @@ public: virtual void Compute(cmLocalGenerator*) {} protected: - void GenerateScript(std::ostream& os) CM_OVERRIDE; + void GenerateScript(std::ostream& os) override; std::string CreateComponentTest(const char* component, bool exclude_from_all); diff --git a/Source/cmInstallProgramsCommand.h b/Source/cmInstallProgramsCommand.h index e0ecbda..5c705eb 100644 --- a/Source/cmInstallProgramsCommand.h +++ b/Source/cmInstallProgramsCommand.h @@ -24,14 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmInstallProgramsCommand; } + cmCommand* Clone() override { return new cmInstallProgramsCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; /** * This is called at the end after all the information @@ -39,9 +39,9 @@ public: * not implement this method. At this point, reading and * writing to the cache can be done. */ - void FinalPass() CM_OVERRIDE; + void FinalPass() override; - bool HasFinalPass() const CM_OVERRIDE { return true; } + bool HasFinalPass() const override { return true; } protected: std::string FindInstallSource(const char* name) const; diff --git a/Source/cmInstallScriptGenerator.h b/Source/cmInstallScriptGenerator.h index 7e19aa6..fe0f7c6 100644 --- a/Source/cmInstallScriptGenerator.h +++ b/Source/cmInstallScriptGenerator.h @@ -18,10 +18,10 @@ class cmInstallScriptGenerator : public cmInstallGenerator public: cmInstallScriptGenerator(const char* script, bool code, const char* component, bool exclude_from_all); - ~cmInstallScriptGenerator() CM_OVERRIDE; + ~cmInstallScriptGenerator() override; protected: - void GenerateScript(std::ostream& os) CM_OVERRIDE; + void GenerateScript(std::ostream& os) override; std::string Script; bool Code; }; diff --git a/Source/cmInstallTargetGenerator.cxx b/Source/cmInstallTargetGenerator.cxx index 2b15aeb..b964794 100644 --- a/Source/cmInstallTargetGenerator.cxx +++ b/Source/cmInstallTargetGenerator.cxx @@ -362,9 +362,8 @@ void cmInstallTargetGenerator::GetInstallObjectNames( std::string const& config, std::vector<std::string>& objects) const { this->Target->GetTargetObjectNames(config, objects); - for (std::vector<std::string>::iterator i = objects.begin(); - i != objects.end(); ++i) { - *i = computeInstallObjectDir(this->Target, config) + "/" + *i; + for (std::string& o : objects) { + o = computeInstallObjectDir(this->Target, config) + "/" + o; } } @@ -476,9 +475,8 @@ void cmInstallTargetGenerator::AddTweak(std::ostream& os, Indent indent, if (!tws.empty()) { Indent indent2 = indent.Next().Next(); os << indent << "foreach(file\n"; - for (std::vector<std::string>::const_iterator i = files.begin(); - i != files.end(); ++i) { - os << indent2 << "\"" << this->GetDestDirPath(*i) << "\"\n"; + for (std::string const& f : files) { + os << indent2 << "\"" << this->GetDestDirPath(f) << "\"\n"; } os << indent2 << ")\n"; os << tws; @@ -546,11 +544,7 @@ void cmInstallTargetGenerator::AddInstallNamePatchRule( this->Target->GetLinkInformation(config)) { std::set<cmGeneratorTarget const*> const& sharedLibs = cli->GetSharedLibrariesLinked(); - for (std::set<cmGeneratorTarget const*>::const_iterator j = - sharedLibs.begin(); - j != sharedLibs.end(); ++j) { - cmGeneratorTarget const* tgt = *j; - + for (cmGeneratorTarget const* tgt : sharedLibs) { // The install_name of an imported target does not change. if (tgt->IsImported()) { continue; @@ -609,12 +603,9 @@ void cmInstallTargetGenerator::AddInstallNamePatchRule( if (!new_id.empty()) { os << "\n" << indent << " -id \"" << new_id << "\""; } - for (std::map<std::string, std::string>::const_iterator i = - install_name_remap.begin(); - i != install_name_remap.end(); ++i) { + for (auto const& i : install_name_remap) { os << "\n" - << indent << " -change \"" << i->first << "\" \"" << i->second - << "\""; + << indent << " -change \"" << i.first << "\" \"" << i.second << "\""; } os << "\n" << indent << " \"" << toDestDirPath << "\")\n"; } @@ -702,10 +693,9 @@ void cmInstallTargetGenerator::AddChrpathPatchRule( // Note: These paths are kept unique to avoid // install_name_tool corruption. std::set<std::string> runpaths; - for (std::vector<std::string>::const_iterator i = oldRuntimeDirs.begin(); - i != oldRuntimeDirs.end(); ++i) { + for (std::string const& i : oldRuntimeDirs) { std::string runpath = - mf->GetGlobalGenerator()->ExpandCFGIntDir(*i, config); + mf->GetGlobalGenerator()->ExpandCFGIntDir(i, config); if (runpaths.find(runpath) == runpaths.end()) { runpaths.insert(runpath); @@ -717,10 +707,9 @@ void cmInstallTargetGenerator::AddChrpathPatchRule( } runpaths.clear(); - for (std::vector<std::string>::const_iterator i = newRuntimeDirs.begin(); - i != newRuntimeDirs.end(); ++i) { + for (std::string const& i : newRuntimeDirs) { std::string runpath = - mf->GetGlobalGenerator()->ExpandCFGIntDir(*i, config); + mf->GetGlobalGenerator()->ExpandCFGIntDir(i, config); if (runpaths.find(runpath) == runpaths.end()) { os << indent << "execute_process(COMMAND " << installNameTool diff --git a/Source/cmInstallTargetGenerator.h b/Source/cmInstallTargetGenerator.h index 385d995..f6bec20 100644 --- a/Source/cmInstallTargetGenerator.h +++ b/Source/cmInstallTargetGenerator.h @@ -26,7 +26,7 @@ public: std::vector<std::string> const& configurations, const char* component, MessageLevel message, bool exclude_from_all, bool optional); - ~cmInstallTargetGenerator() CM_OVERRIDE; + ~cmInstallTargetGenerator() override; /** Select the policy for installing shared library linkable name symlinks. */ @@ -56,7 +56,7 @@ public: const std::string& config, NameType nameType = NameNormal); - void Compute(cmLocalGenerator* lg) CM_OVERRIDE; + void Compute(cmLocalGenerator* lg) override; cmGeneratorTarget* GetTarget() const { return this->Target; } @@ -65,9 +65,9 @@ public: std::string GetDestination(std::string const& config) const; protected: - void GenerateScript(std::ostream& os) CM_OVERRIDE; + void GenerateScript(std::ostream& os) override; void GenerateScriptForConfig(std::ostream& os, const std::string& config, - Indent indent) CM_OVERRIDE; + Indent indent) override; void GenerateScriptForConfigObjectLibrary(std::ostream& os, const std::string& config, Indent indent); diff --git a/Source/cmInstallTargetsCommand.h b/Source/cmInstallTargetsCommand.h index 17622fb..9950fb7 100644 --- a/Source/cmInstallTargetsCommand.h +++ b/Source/cmInstallTargetsCommand.h @@ -25,14 +25,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmInstallTargetsCommand; } + cmCommand* Clone() override { return new cmInstallTargetsCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmInstalledFile.cxx b/Source/cmInstalledFile.cxx index 035c900..c8144aa 100644 --- a/Source/cmInstalledFile.cxx +++ b/Source/cmInstalledFile.cxx @@ -90,11 +90,9 @@ bool cmInstalledFile::GetProperty(const std::string& prop, std::string output; std::string separator; - for (ExpressionVectorType::const_iterator j = - property.ValueExpressions.begin(); - j != property.ValueExpressions.end(); ++j) { + for (auto ve : property.ValueExpressions) { output += separator; - output += (*j)->GetInput(); + output += ve->GetInput(); separator = ";"; } diff --git a/Source/cmInstalledFile.h b/Source/cmInstalledFile.h index fbf754f..47a4959 100644 --- a/Source/cmInstalledFile.h +++ b/Source/cmInstalledFile.h @@ -6,9 +6,9 @@ #include "cmConfigure.h" // IWYU pragma: keep #include "cmGeneratorExpression.h" -#include "cm_auto_ptr.hxx" #include <map> +#include <memory> // IWYU pragma: keep #include <string> #include <vector> @@ -22,7 +22,7 @@ class cmMakefile; class cmInstalledFile { public: - typedef CM_AUTO_PTR<cmCompiledGeneratorExpression> + typedef std::unique_ptr<cmCompiledGeneratorExpression> CompiledGeneratorExpressionPtrType; typedef std::vector<cmCompiledGeneratorExpression*> ExpressionVectorType; diff --git a/Source/cmLinkDirectoriesCommand.cxx b/Source/cmLinkDirectoriesCommand.cxx index 9b0c288..98ab7e7 100644 --- a/Source/cmLinkDirectoriesCommand.cxx +++ b/Source/cmLinkDirectoriesCommand.cxx @@ -19,9 +19,8 @@ bool cmLinkDirectoriesCommand::InitialPass( return true; } - for (std::vector<std::string>::const_iterator i = args.begin(); - i != args.end(); ++i) { - this->AddLinkDir(*i); + for (std::string const& i : args) { + this->AddLinkDir(i); } return true; } diff --git a/Source/cmLinkDirectoriesCommand.h b/Source/cmLinkDirectoriesCommand.h index 6297073..3fd4e50 100644 --- a/Source/cmLinkDirectoriesCommand.h +++ b/Source/cmLinkDirectoriesCommand.h @@ -26,14 +26,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmLinkDirectoriesCommand; } + cmCommand* Clone() override { return new cmLinkDirectoriesCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: void AddLinkDir(std::string const& dir); diff --git a/Source/cmLinkLibrariesCommand.h b/Source/cmLinkLibrariesCommand.h index 54121dd..af25fba 100644 --- a/Source/cmLinkLibrariesCommand.h +++ b/Source/cmLinkLibrariesCommand.h @@ -25,14 +25,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmLinkLibrariesCommand; } + cmCommand* Clone() override { return new cmLinkLibrariesCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmLinkLineComputer.cxx b/Source/cmLinkLineComputer.cxx index c0f702e..7511fd2 100644 --- a/Source/cmLinkLineComputer.cxx +++ b/Source/cmLinkLineComputer.cxx @@ -59,17 +59,16 @@ std::string cmLinkLineComputer::ComputeLinkLibs(cmComputeLinkInformation& cli) std::string linkLibs; typedef cmComputeLinkInformation::ItemVector ItemVector; ItemVector const& items = cli.GetItems(); - for (ItemVector::const_iterator li = items.begin(); li != items.end(); - ++li) { - if (li->Target && - li->Target->GetType() == cmStateEnums::INTERFACE_LIBRARY) { + for (auto const& item : items) { + if (item.Target && + item.Target->GetType() == cmStateEnums::INTERFACE_LIBRARY) { continue; } - if (li->IsPath) { + if (item.IsPath) { linkLibs += - this->ConvertToOutputFormat(this->ConvertToLinkReference(li->Value)); + this->ConvertToOutputFormat(this->ConvertToLinkReference(item.Value)); } else { - linkLibs += li->Value; + linkLibs += item.Value; } linkLibs += " "; } @@ -103,9 +102,8 @@ std::string cmLinkLineComputer::ComputeLinkPath( { std::string linkPath; std::vector<std::string> const& libDirs = cli.GetDirectories(); - for (std::vector<std::string>::const_iterator libDir = libDirs.begin(); - libDir != libDirs.end(); ++libDir) { - std::string libpath = this->ConvertToOutputForExisting(*libDir); + for (std::string const& libDir : libDirs) { + std::string libpath = this->ConvertToOutputForExisting(libDir); linkPath += " " + libPathFlag; linkPath += libpath; linkPath += libPathTerminator; @@ -123,10 +121,9 @@ std::string cmLinkLineComputer::ComputeRPath(cmComputeLinkInformation& cli) std::vector<std::string> runtimeDirs; cli.GetRPath(runtimeDirs, this->Relink); - for (std::vector<std::string>::iterator ri = runtimeDirs.begin(); - ri != runtimeDirs.end(); ++ri) { + for (std::string const& rd : runtimeDirs) { rpath += cli.GetRuntimeFlag(); - rpath += this->ConvertToOutputFormat(*ri); + rpath += this->ConvertToOutputFormat(rd); rpath += " "; } } else { @@ -150,10 +147,9 @@ std::string cmLinkLineComputer::ComputeFrameworkPath( std::string frameworkPath; if (!fwSearchFlag.empty()) { std::vector<std::string> const& fwDirs = cli.GetFrameworkPaths(); - for (std::vector<std::string>::const_iterator fdi = fwDirs.begin(); - fdi != fwDirs.end(); ++fdi) { + for (std::string const& fd : fwDirs) { frameworkPath += fwSearchFlag; - frameworkPath += this->ConvertToOutputFormat(*fdi); + frameworkPath += this->ConvertToOutputFormat(fd); frameworkPath += " "; } } diff --git a/Source/cmLinkLineDeviceComputer.cxx b/Source/cmLinkLineDeviceComputer.cxx index 942e9b9..3beeae3 100644 --- a/Source/cmLinkLineDeviceComputer.cxx +++ b/Source/cmLinkLineDeviceComputer.cxx @@ -5,7 +5,6 @@ #include <set> #include <sstream> -#include <vector> #include "cmComputeLinkInformation.h" #include "cmGeneratorTarget.h" @@ -32,14 +31,13 @@ std::string cmLinkLineDeviceComputer::ComputeLinkLibraries( typedef cmComputeLinkInformation::ItemVector ItemVector; ItemVector const& items = cli.GetItems(); std::string config = cli.GetConfig(); - for (ItemVector::const_iterator li = items.begin(); li != items.end(); - ++li) { - if (!li->Target) { + for (auto const& item : items) { + if (!item.Target) { continue; } bool skippable = false; - switch (li->Target->GetType()) { + switch (item.Target->GetType()) { case cmStateEnums::SHARED_LIBRARY: case cmStateEnums::MODULE_LIBRARY: case cmStateEnums::INTERFACE_LIBRARY: @@ -49,7 +47,7 @@ std::string cmLinkLineDeviceComputer::ComputeLinkLibraries( // If a static library is resolving its device linking, it should // be removed for other device linking skippable = - li->Target->GetPropertyAsBool("CUDA_RESOLVE_DEVICE_SYMBOLS"); + item.Target->GetPropertyAsBool("CUDA_RESOLVE_DEVICE_SYMBOLS"); break; default: break; @@ -60,16 +58,16 @@ std::string cmLinkLineDeviceComputer::ComputeLinkLibraries( } std::set<std::string> langs; - li->Target->GetLanguages(langs, config); + item.Target->GetLanguages(langs, config); if (langs.count("CUDA") == 0) { continue; } - if (li->IsPath) { + if (item.IsPath) { fout << this->ConvertToOutputFormat( - this->ConvertToLinkReference(li->Value)); + this->ConvertToLinkReference(item.Value)); } else { - fout << li->Value; + fout << item.Value; } fout << " "; } diff --git a/Source/cmLinkLineDeviceComputer.h b/Source/cmLinkLineDeviceComputer.h index 66941d3..81b48b3 100644 --- a/Source/cmLinkLineDeviceComputer.h +++ b/Source/cmLinkLineDeviceComputer.h @@ -23,14 +23,13 @@ class cmLinkLineDeviceComputer : public cmLinkLineComputer public: cmLinkLineDeviceComputer(cmOutputConverter* outputConverter, cmStateDirectory const& stateDir); - ~cmLinkLineDeviceComputer() CM_OVERRIDE; + ~cmLinkLineDeviceComputer() override; std::string ComputeLinkLibraries(cmComputeLinkInformation& cli, - std::string const& stdLibString) - CM_OVERRIDE; + std::string const& stdLibString) override; std::string GetLinkerLanguage(cmGeneratorTarget* target, - std::string const& config) CM_OVERRIDE; + std::string const& config) override; }; class cmNinjaLinkLineDeviceComputer : public cmLinkLineDeviceComputer @@ -42,8 +41,7 @@ public: cmStateDirectory const& stateDir, cmGlobalNinjaGenerator const* gg); - std::string ConvertToLinkReference(std::string const& input) const - CM_OVERRIDE; + std::string ConvertToLinkReference(std::string const& input) const override; private: cmGlobalNinjaGenerator const* GG; diff --git a/Source/cmListCommand.h b/Source/cmListCommand.h index 7d3800a..2965399 100644 --- a/Source/cmListCommand.h +++ b/Source/cmListCommand.h @@ -22,14 +22,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmListCommand; } + cmCommand* Clone() override { return new cmListCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; protected: bool HandleLengthCommand(std::vector<std::string> const& args); diff --git a/Source/cmLoadCacheCommand.cxx b/Source/cmLoadCacheCommand.cxx index 00a30bf..32fdef5 100644 --- a/Source/cmLoadCacheCommand.cxx +++ b/Source/cmLoadCacheCommand.cxx @@ -27,17 +27,16 @@ bool cmLoadCacheCommand::InitialPass(std::vector<std::string> const& args, // If this set is empty, all cache entries are brought in // and they can not be overridden. bool excludeFiles = false; - unsigned int i; std::set<std::string> excludes; - for (i = 0; i < args.size(); i++) { + for (std::string const& arg : args) { if (excludeFiles) { - excludes.insert(args[i]); + excludes.insert(arg); } - if (args[i] == "EXCLUDE") { + if (arg == "EXCLUDE") { excludeFiles = true; } - if (excludeFiles && (args[i] == "INCLUDE_INTERNALS")) { + if (excludeFiles && (arg == "INCLUDE_INTERNALS")) { break; } } @@ -48,25 +47,25 @@ bool cmLoadCacheCommand::InitialPass(std::vector<std::string> const& args, bool includeFiles = false; std::set<std::string> includes; - for (i = 0; i < args.size(); i++) { + for (std::string const& arg : args) { if (includeFiles) { - includes.insert(args[i]); + includes.insert(arg); } - if (args[i] == "INCLUDE_INTERNALS") { + if (arg == "INCLUDE_INTERNALS") { includeFiles = true; } - if (includeFiles && (args[i] == "EXCLUDE")) { + if (includeFiles && (arg == "EXCLUDE")) { break; } } // Loop over each build directory listed in the arguments. Each // directory has a cache file. - for (i = 0; i < args.size(); i++) { - if ((args[i] == "EXCLUDE") || (args[i] == "INCLUDE_INTERNALS")) { + for (std::string const& arg : args) { + if ((arg == "EXCLUDE") || (arg == "INCLUDE_INTERNALS")) { break; } - this->Makefile->GetCMakeInstance()->LoadCache(args[i], false, excludes, + this->Makefile->GetCMakeInstance()->LoadCache(arg, false, excludes, includes); } @@ -125,7 +124,7 @@ bool cmLoadCacheCommand::ReadWithPrefix(std::vector<std::string> const& args) if (i != end) { // Completed a line. this->CheckLine(line.c_str()); - line = ""; + line.clear(); // Skip the newline character. ++i; diff --git a/Source/cmLoadCacheCommand.h b/Source/cmLoadCacheCommand.h index e46144d..e0f6e4f 100644 --- a/Source/cmLoadCacheCommand.h +++ b/Source/cmLoadCacheCommand.h @@ -24,14 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmLoadCacheCommand; } + cmCommand* Clone() override { return new cmLoadCacheCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; protected: std::set<std::string> VariablesToRead; diff --git a/Source/cmLoadCommandCommand.cxx b/Source/cmLoadCommandCommand.cxx index 5ce48e3..6bfac17 100644 --- a/Source/cmLoadCommandCommand.cxx +++ b/Source/cmLoadCommandCommand.cxx @@ -34,12 +34,12 @@ public: } ///! clean up any memory allocated by the plugin - ~cmLoadedCommand() CM_OVERRIDE; + ~cmLoadedCommand() override; /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmLoadedCommand* newC = new cmLoadedCommand; // we must copy when we clone @@ -52,7 +52,7 @@ public: * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) CM_OVERRIDE; + cmExecutionStatus&) override; /** * This is called at the end after all the information @@ -60,8 +60,8 @@ public: * not implement this method. At this point, reading and * writing to the cache can be done. */ - void FinalPass() CM_OVERRIDE; - bool HasFinalPass() const CM_OVERRIDE + void FinalPass() override; + bool HasFinalPass() const override { return this->info.FinalPass != nullptr; } @@ -120,7 +120,7 @@ bool cmLoadedCommand::InitialPass(std::vector<std::string> const& args, int argc = static_cast<int>(args.size()); char** argv = nullptr; if (argc) { - argv = reinterpret_cast<char**>(malloc(argc * sizeof(char*))); + argv = static_cast<char**>(malloc(argc * sizeof(char*))); } int i; for (i = 0; i < argc; ++i) { @@ -197,7 +197,7 @@ bool cmLoadCommandCommand::InitialPass(std::vector<std::string> const& args, // Try to find the program. std::string fullPath = cmSystemTools::FindFile(moduleName, path); - if (fullPath == "") { + if (fullPath.empty()) { std::ostringstream e; e << "Attempt to load command failed from file \"" << moduleName << "\""; this->SetError(e.str()); diff --git a/Source/cmLoadCommandCommand.h b/Source/cmLoadCommandCommand.h index 30bb7da..021e6c7 100644 --- a/Source/cmLoadCommandCommand.h +++ b/Source/cmLoadCommandCommand.h @@ -15,9 +15,9 @@ class cmExecutionStatus; class cmLoadCommandCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE { return new cmLoadCommandCommand; } + cmCommand* Clone() override { return new cmLoadCommandCommand; } bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmLocalCommonGenerator.cxx b/Source/cmLocalCommonGenerator.cxx index 6524db4..50ebfa1 100644 --- a/Source/cmLocalCommonGenerator.cxx +++ b/Source/cmLocalCommonGenerator.cxx @@ -22,7 +22,7 @@ cmLocalCommonGenerator::cmLocalCommonGenerator(cmGlobalGenerator* gg, this->ConfigName = config; } else { // No configuration type given. - this->ConfigName = ""; + this->ConfigName.clear(); } } @@ -67,10 +67,9 @@ std::string cmLocalCommonGenerator::GetTargetFortranFlags( this->Makefile->GetDefinition("CMAKE_Fortran_MODPATH_FLAG")) { std::vector<std::string> includes; this->GetIncludeDirectories(includes, target, "C", config); - for (std::vector<std::string>::const_iterator idi = includes.begin(); - idi != includes.end(); ++idi) { + for (std::string const& id : includes) { std::string flg = modpath_flag; - flg += this->ConvertToOutputFormat(*idi, cmOutputConverter::SHELL); + flg += this->ConvertToOutputFormat(id, cmOutputConverter::SHELL); this->AppendFlags(flags, flg); } } diff --git a/Source/cmLocalCommonGenerator.h b/Source/cmLocalCommonGenerator.h index 999085e..a60573c 100644 --- a/Source/cmLocalCommonGenerator.h +++ b/Source/cmLocalCommonGenerator.h @@ -21,14 +21,14 @@ class cmLocalCommonGenerator : public cmLocalGenerator public: cmLocalCommonGenerator(cmGlobalGenerator* gg, cmMakefile* mf, std::string const& wd); - ~cmLocalCommonGenerator() CM_OVERRIDE; + ~cmLocalCommonGenerator() override; std::string const& GetConfigName() { return this->ConfigName; } std::string GetWorkingDirectory() const { return this->WorkingDirectory; } std::string GetTargetFortranFlags(cmGeneratorTarget const* target, - std::string const& config) CM_OVERRIDE; + std::string const& config) override; protected: std::string WorkingDirectory; diff --git a/Source/cmLocalGenerator.cxx b/Source/cmLocalGenerator.cxx index 6e0e28c..1a088ea 100644 --- a/Source/cmLocalGenerator.cxx +++ b/Source/cmLocalGenerator.cxx @@ -102,9 +102,7 @@ cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile) this->LinkerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT"); } - for (std::vector<std::string>::iterator i = enabledLanguages.begin(); - i != enabledLanguages.end(); ++i) { - std::string const& lang = *i; + for (std::string const& lang : enabledLanguages) { if (lang == "NONE") { continue; } @@ -209,18 +207,16 @@ void cmLocalGenerator::TraceDependencies() if (configs.empty()) { configs.push_back(""); } - for (std::vector<std::string>::const_iterator ci = configs.begin(); - ci != configs.end(); ++ci) { - this->GlobalGenerator->CreateEvaluationSourceFiles(*ci); + for (std::string const& c : configs) { + this->GlobalGenerator->CreateEvaluationSourceFiles(c); } // Generate the rule files for each target. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator t = targets.begin(); - t != targets.end(); ++t) { - if ((*t)->GetType() == cmStateEnums::INTERFACE_LIBRARY) { + for (cmGeneratorTarget* target : targets) { + if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) { continue; } - (*t)->TraceDependencies(); + target->TraceDependencies(); } } @@ -264,26 +260,24 @@ void cmLocalGenerator::GenerateTestFiles() if (testIncludeFiles) { std::vector<std::string> includesList; cmSystemTools::ExpandListArgument(testIncludeFiles, includesList); - for (std::vector<std::string>::const_iterator i = includesList.begin(); - i != includesList.end(); ++i) { - fout << "include(\"" << *i << "\")" << std::endl; + for (std::string const& i : includesList) { + fout << "include(\"" << i << "\")" << std::endl; } } // Ask each test generator to write its code. std::vector<cmTestGenerator*> const& testers = this->Makefile->GetTestGenerators(); - for (std::vector<cmTestGenerator*>::const_iterator gi = testers.begin(); - gi != testers.end(); ++gi) { - (*gi)->Compute(this); - (*gi)->Generate(fout, config, configurationTypes); + for (cmTestGenerator* tester : testers) { + tester->Compute(this); + tester->Generate(fout, config, configurationTypes); } typedef std::vector<cmStateSnapshot> vec_t; vec_t const& children = this->Makefile->GetStateSnapshot().GetChildren(); std::string parentBinDir = this->GetCurrentBinaryDirectory(); - for (vec_t::const_iterator i = children.begin(); i != children.end(); ++i) { + for (cmStateSnapshot const& i : children) { // TODO: Use add_subdirectory instead? - std::string outP = i->GetDirectory().GetCurrentBinary(); + std::string outP = i.GetDirectory().GetCurrentBinary(); outP = this->ConvertToRelativePath(parentBinDir, outP); outP = cmOutputConverter::EscapeForCMake(outP); fout << "subdirs(" << outP << ")" << std::endl; @@ -313,10 +307,8 @@ void cmLocalGenerator::CreateEvaluationFileOutputs(std::string const& config) { std::vector<cmGeneratorExpressionEvaluationFile*> ef = this->Makefile->GetEvaluationFiles(); - for (std::vector<cmGeneratorExpressionEvaluationFile*>::const_iterator li = - ef.begin(); - li != ef.end(); ++li) { - (*li)->CreateOutputFile(this, config); + for (cmGeneratorExpressionEvaluationFile* geef : ef) { + geef->CreateOutputFile(this, config); } } @@ -325,14 +317,12 @@ void cmLocalGenerator::ProcessEvaluationFiles( { std::vector<cmGeneratorExpressionEvaluationFile*> ef = this->Makefile->GetEvaluationFiles(); - for (std::vector<cmGeneratorExpressionEvaluationFile*>::const_iterator li = - ef.begin(); - li != ef.end(); ++li) { - (*li)->Generate(this); + for (cmGeneratorExpressionEvaluationFile* geef : ef) { + geef->Generate(this); if (cmSystemTools::GetFatalErrorOccured()) { return; } - std::vector<std::string> files = (*li)->GetFiles(); + std::vector<std::string> files = geef->GetFiles(); std::sort(files.begin(), files.end()); std::vector<std::string> intersection; @@ -403,10 +393,9 @@ void cmLocalGenerator::GenerateInstallRules() const char* default_order[] = { "RELEASE", "MINSIZEREL", "RELWITHDEBINFO", "DEBUG", nullptr }; for (const char** c = default_order; *c && default_config.empty(); ++c) { - for (std::vector<std::string>::iterator i = configurationTypes.begin(); - i != configurationTypes.end(); ++i) { - if (cmSystemTools::UpperCase(*i) == *c) { - default_config = *i; + for (std::string const& configurationType : configurationTypes) { + if (cmSystemTools::UpperCase(configurationType) == *c) { + default_config = configurationType; } } } @@ -498,10 +487,8 @@ void cmLocalGenerator::GenerateInstallRules() // Ask each install generator to write its code. std::vector<cmInstallGenerator*> const& installers = this->Makefile->GetInstallGenerators(); - for (std::vector<cmInstallGenerator*>::const_iterator gi = - installers.begin(); - gi != installers.end(); ++gi) { - (*gi)->Generate(fout, config, configurationTypes); + for (cmInstallGenerator* installer : installers) { + installer->Generate(fout, config, configurationTypes); } // Write rules from old-style specification stored in targets. @@ -513,10 +500,9 @@ void cmLocalGenerator::GenerateInstallRules() if (!children.empty()) { fout << "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n"; fout << " # Include the install script for each subdirectory.\n"; - for (std::vector<cmStateSnapshot>::const_iterator ci = children.begin(); - ci != children.end(); ++ci) { - if (!ci->GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) { - std::string odir = ci->GetDirectory().GetCurrentBinary(); + for (cmStateSnapshot const& c : children) { + if (!c.GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) { + std::string odir = c.GetDirectory().GetCurrentBinary(); cmSystemTools::ConvertToUnixSlashes(odir); fout << " include(\"" << odir << "/cmake_install.cmake\")" << std::endl; @@ -602,16 +588,12 @@ void cmLocalGenerator::ComputeTargetManifest() // Add our targets to the manifest for each configuration. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator t = targets.begin(); - t != targets.end(); ++t) { - cmGeneratorTarget* target = *t; + for (cmGeneratorTarget* target : targets) { if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) { continue; } - for (std::vector<std::string>::iterator ci = configNames.begin(); - ci != configNames.end(); ++ci) { - const char* config = ci->c_str(); - target->ComputeTargetManifest(config); + for (std::string const& c : configNames) { + target->ComputeTargetManifest(c); } } } @@ -627,12 +609,9 @@ bool cmLocalGenerator::ComputeTargetCompileFeatures() // Process compile features of all targets. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator t = targets.begin(); - t != targets.end(); ++t) { - cmGeneratorTarget* target = *t; - for (std::vector<std::string>::iterator ci = configNames.begin(); - ci != configNames.end(); ++ci) { - if (!target->ComputeCompileFeatures(*ci)) { + for (cmGeneratorTarget* target : targets) { + for (std::string const& c : configNames) { + if (!target->ComputeCompileFeatures(c)) { return false; } } @@ -729,16 +708,15 @@ std::string cmLocalGenerator::GetIncludeFlags( #ifdef __APPLE__ emitted.insert("/System/Library/Frameworks"); #endif - std::vector<std::string>::const_iterator i; - for (i = includes.begin(); i != includes.end(); ++i) { + for (std::string const& i : includes) { if (fwSearchFlag && *fwSearchFlag && this->Makefile->IsOn("APPLE") && - cmSystemTools::IsPathToFramework(i->c_str())) { - std::string frameworkDir = *i; + cmSystemTools::IsPathToFramework(i.c_str())) { + std::string frameworkDir = i; frameworkDir += "/../"; frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir); if (emitted.insert(frameworkDir).second) { if (sysFwSearchFlag && target && - target->IsSystemIncludeDirectory(*i, config)) { + target->IsSystemIncludeDirectory(i, config)) { includeFlags << sysFwSearchFlag; } else { includeFlags << fwSearchFlag; @@ -751,7 +729,7 @@ std::string cmLocalGenerator::GetIncludeFlags( if (!flagUsed || repeatFlag) { if (sysIncludeFlag && target && - target->IsSystemIncludeDirectory(*i, config)) { + target->IsSystemIncludeDirectory(i, config)) { includeFlags << sysIncludeFlag; } else { includeFlags << includeFlag; @@ -759,7 +737,7 @@ std::string cmLocalGenerator::GetIncludeFlags( flagUsed = true; } std::string includePath = - this->ConvertToIncludeReference(*i, shellFormat, forceFullPaths); + this->ConvertToIncludeReference(i, shellFormat, forceFullPaths); if (quotePaths && !includePath.empty() && includePath[0] != '\"') { includeFlags << "\""; } @@ -803,12 +781,11 @@ void cmLocalGenerator::AddCompileOptions(std::string& flags, cmSystemTools::ParseWindowsCommandLine(targetFlags, opts); } target->GetCompileOptions(opts, config, lang); - for (std::vector<std::string>::const_iterator i = opts.begin(); - i != opts.end(); ++i) { - if (r.find(i->c_str())) { + for (std::string const& opt : opts) { + if (r.find(opt.c_str())) { // (Re-)Escape this flag. COMPILE_FLAGS were already parsed // as a command line above, and COMPILE_OPTIONS are escaped. - this->AppendFlagEscape(flags, *i); + this->AppendFlagEscape(flags, opt); } } } else { @@ -819,30 +796,27 @@ void cmLocalGenerator::AddCompileOptions(std::string& flags, } std::vector<std::string> opts; target->GetCompileOptions(opts, config, lang); - for (std::vector<std::string>::const_iterator i = opts.begin(); - i != opts.end(); ++i) { + for (std::string const& opt : opts) { // COMPILE_OPTIONS are escaped. - this->AppendFlagEscape(flags, *i); + this->AppendFlagEscape(flags, opt); } } - for (std::map<std::string, std::string>::const_iterator it = - target->GetMaxLanguageStandards().begin(); - it != target->GetMaxLanguageStandards().end(); ++it) { - const char* standard = target->GetProperty(it->first + "_STANDARD"); + for (auto const& it : target->GetMaxLanguageStandards()) { + const char* standard = target->GetProperty(it.first + "_STANDARD"); if (!standard) { continue; } - if (this->Makefile->IsLaterStandard(it->first, standard, it->second)) { + if (this->Makefile->IsLaterStandard(it.first, standard, it.second)) { std::ostringstream e; e << "The COMPILE_FEATURES property of target \"" << target->GetName() << "\" was evaluated when computing the link " "implementation, and the \"" - << it->first << "_STANDARD\" was \"" << it->second + << it.first << "_STANDARD\" was \"" << it.second << "\" for that computation. Computing the " "COMPILE_FEATURES based on the link implementation resulted in a " "higher \"" - << it->first << "_STANDARD\" \"" << standard + << it.first << "_STANDARD\" \"" << standard << "\". " "This is not permitted. The COMPILE_FEATURES may not both depend " "on " @@ -917,13 +891,12 @@ void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs, if (const char* value = this->Makefile->GetDefinition(impDirVar)) { std::vector<std::string> impDirVec; cmSystemTools::ExpandListArgument(value, impDirVec); - for (std::vector<std::string>::const_iterator i = impDirVec.begin(); - i != impDirVec.end(); ++i) { - std::string d = rootPath + *i; + for (std::string const& i : impDirVec) { + std::string d = rootPath + i; cmSystemTools::ConvertToUnixSlashes(d); emitted.insert(d); if (!stripImplicitInclDirs) { - implicitDirs.push_back(*i); + implicitDirs.push_back(i); } } } @@ -938,26 +911,24 @@ void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs, if (this->Makefile->IsOn("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE")) { const char* topSourceDir = this->GetState()->GetSourceDirectory(); const char* topBinaryDir = this->GetState()->GetBinaryDirectory(); - for (std::vector<std::string>::const_iterator i = includes.begin(); - i != includes.end(); ++i) { + for (std::string const& i : includes) { // Emit this directory only if it is a subdirectory of the // top-level source or binary tree. - if (cmSystemTools::ComparePath(*i, topSourceDir) || - cmSystemTools::ComparePath(*i, topBinaryDir) || - cmSystemTools::IsSubDirectory(*i, topSourceDir) || - cmSystemTools::IsSubDirectory(*i, topBinaryDir)) { - if (emitted.insert(*i).second) { - dirs.push_back(*i); + if (cmSystemTools::ComparePath(i, topSourceDir) || + cmSystemTools::ComparePath(i, topBinaryDir) || + cmSystemTools::IsSubDirectory(i, topSourceDir) || + cmSystemTools::IsSubDirectory(i, topBinaryDir)) { + if (emitted.insert(i).second) { + dirs.push_back(i); } } } } // Construct the final ordered include directory list. - for (std::vector<std::string>::const_iterator i = includes.begin(); - i != includes.end(); ++i) { - if (emitted.insert(*i).second) { - dirs.push_back(*i); + for (std::string const& i : includes) { + if (emitted.insert(i).second) { + dirs.push_back(i); } } @@ -975,10 +946,9 @@ void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs, dirs.push_back(*i); } - for (std::vector<std::string>::const_iterator i = implicitDirs.begin(); - i != implicitDirs.end(); ++i) { - if (std::find(includes.begin(), includes.end(), *i) != includes.end()) { - dirs.push_back(*i); + for (std::string const& i : implicitDirs) { + if (std::find(includes.begin(), includes.end(), i) != includes.end()) { + dirs.push_back(i); } } } @@ -1036,9 +1006,7 @@ void cmLocalGenerator::GetTargetFlags( target->GetSourceFiles(sources, buildType); std::string defFlag = this->Makefile->GetSafeDefinition("CMAKE_LINK_DEF_FILE_FLAG"); - for (std::vector<cmSourceFile*>::const_iterator i = sources.begin(); - i != sources.end(); ++i) { - cmSourceFile* sf = *i; + for (cmSourceFile* sf : sources) { if (sf->GetExtension() == "def") { linkFlags += defFlag; linkFlags += this->ConvertToOutputFormat( @@ -1189,10 +1157,9 @@ static std::string GetFrameworkFlags(const std::string& lang, lg->GetIncludeDirectories(includes, target, "C", config); // check all include directories for frameworks as this // will already have added a -F for the framework - for (std::vector<std::string>::iterator i = includes.begin(); - i != includes.end(); ++i) { - if (lg->GetGlobalGenerator()->NameResolvesToFramework(*i)) { - std::string frameworkDir = *i; + for (std::string const& include : includes) { + if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) { + std::string frameworkDir = include; frameworkDir += "/../"; frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir); emitted.insert(frameworkDir); @@ -1202,11 +1169,11 @@ static std::string GetFrameworkFlags(const std::string& lang, std::string flags; if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) { std::vector<std::string> const& frameworks = cli->GetFrameworkPaths(); - for (std::vector<std::string>::const_iterator i = frameworks.begin(); - i != frameworks.end(); ++i) { - if (emitted.insert(*i).second) { + for (std::string const& framework : frameworks) { + if (emitted.insert(framework).second) { flags += fwSearchFlag; - flags += lg->ConvertToOutputFormat(*i, cmOutputConverter::SHELL); + flags += + lg->ConvertToOutputFormat(framework, cmOutputConverter::SHELL); flags += " "; } } @@ -1359,10 +1326,9 @@ void cmLocalGenerator::AddArchitectureFlags(std::string& flags, this->Makefile->GetDefinition(deploymentTargetFlagVar); if (!archs.empty() && !lang.empty() && (lang[0] == 'C' || lang[0] == 'F')) { - for (std::vector<std::string>::iterator i = archs.begin(); - i != archs.end(); ++i) { + for (std::string const& arch : archs) { flags += " -arch "; - flags += *i; + flags += arch; } } @@ -1444,7 +1410,7 @@ bool cmLocalGenerator::GetRealDependency(const std::string& inName, // If the input name is the empty string, there is no real // dependency. Short-circuit the other checks: - if (name == "") { + if (name.empty()) { return false; } @@ -1566,8 +1532,8 @@ void cmLocalGenerator::AddCompilerRequirementFlag( target->Target->GetMakefile()->GetDefinition(option_flag)) { std::vector<std::string> optVec; cmSystemTools::ExpandListArgument(opt, optVec); - for (size_t i = 0; i < optVec.size(); ++i) { - this->AppendFlagEscape(flags, optVec[i]); + for (std::string const& i : optVec) { + this->AppendFlagEscape(flags, i); } } } @@ -1594,14 +1560,14 @@ void cmLocalGenerator::AddCompilerRequirementFlag( } else { std::vector<std::string> optVec; cmSystemTools::ExpandListArgument(opt, optVec); - for (size_t i = 0; i < optVec.size(); ++i) { - this->AppendFlagEscape(flags, optVec[i]); + for (std::string const& i : optVec) { + this->AppendFlagEscape(flags, i); } } return; } - static std::map<std::string, std::vector<std::string> > langStdMap; + static std::map<std::string, std::vector<std::string>> langStdMap; if (langStdMap.empty()) { // Maintain sorted order, most recent first. langStdMap["CXX"].push_back("17"); @@ -1654,8 +1620,8 @@ void cmLocalGenerator::AddCompilerRequirementFlag( target->Target->GetMakefile()->GetRequiredDefinition(option_flag); std::vector<std::string> optVec; cmSystemTools::ExpandListArgument(opt, optVec); - for (size_t i = 0; i < optVec.size(); ++i) { - this->AppendFlagEscape(flags, optVec[i]); + for (std::string const& i : optVec) { + this->AppendFlagEscape(flags, i); } return; } @@ -1671,8 +1637,8 @@ void cmLocalGenerator::AddCompilerRequirementFlag( target->Target->GetMakefile()->GetDefinition(option_flag)) { std::vector<std::string> optVec; cmSystemTools::ExpandListArgument(opt, optVec); - for (size_t i = 0; i < optVec.size(); ++i) { - this->AppendFlagEscape(flags, optVec[i]); + for (std::string const& i : optVec) { + this->AppendFlagEscape(flags, i); } return; } @@ -1871,9 +1837,8 @@ void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags, if (picFlags) { std::vector<std::string> options; cmSystemTools::ExpandListArgument(picFlags, options); - for (std::vector<std::string>::const_iterator oi = options.begin(); - oi != options.end(); ++oi) { - this->AppendFlagEscape(flags, *oi); + for (std::string const& o : options) { + this->AppendFlagEscape(flags, o); } } } @@ -1943,9 +1908,8 @@ void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags, std::vector<std::string> flagsList; cmSystemTools::ExpandListArgument(rawFlagsList, flagsList); - for (std::vector<std::string>::const_iterator oi = flagsList.begin(); - oi != flagsList.end(); ++oi) { - this->AppendFlagEscape(flags, *oi); + for (std::string const& o : flagsList) { + this->AppendFlagEscape(flags, o); } } @@ -1967,13 +1931,12 @@ void cmLocalGenerator::AppendDefines( std::set<std::string>& defines, const std::vector<std::string>& defines_vec) const { - for (std::vector<std::string>::const_iterator di = defines_vec.begin(); - di != defines_vec.end(); ++di) { + for (std::string const& d : defines_vec) { // Skip unsupported definitions. - if (!this->CheckDefinition(*di)) { + if (!this->CheckDefinition(d)) { continue; } - defines.insert(*di); + defines.insert(d); } } @@ -2043,9 +2006,8 @@ void cmLocalGenerator::AppendFeatureOptions(std::string& flags, if (const char* optionList = this->Makefile->GetDefinition(optVar)) { std::vector<std::string> options; cmSystemTools::ExpandListArgument(optionList, options); - for (std::vector<std::string>::const_iterator oi = options.begin(); - oi != options.end(); ++oi) { - this->AppendFlagEscape(flags, *oi); + for (std::string const& o : options) { + this->AppendFlagEscape(flags, o); } } } @@ -2089,10 +2051,9 @@ std::string cmLocalGenerator::ConstructComment( comment = "Generating "; const char* sep = ""; std::string currentBinaryDir = this->GetCurrentBinaryDirectory(); - for (std::vector<std::string>::const_iterator o = ccg.GetOutputs().begin(); - o != ccg.GetOutputs().end(); ++o) { + for (std::string const& o : ccg.GetOutputs()) { comment += sep; - comment += this->ConvertToRelativePath(currentBinaryDir, *o); + comment += this->ConvertToRelativePath(currentBinaryDir, o); sep = ", "; } return comment; @@ -2123,36 +2084,35 @@ void cmLocalGenerator::GenerateTargetInstallRules( // Convert the old-style install specification from each target to // an install generator and run it. const std::vector<cmGeneratorTarget*>& tgts = this->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator l = tgts.begin(); - l != tgts.end(); ++l) { - if ((*l)->GetType() == cmStateEnums::INTERFACE_LIBRARY) { + for (cmGeneratorTarget* l : tgts) { + if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) { continue; } // Include the user-specified pre-install script for this target. - if (const char* preinstall = (*l)->GetProperty("PRE_INSTALL_SCRIPT")) { + if (const char* preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) { cmInstallScriptGenerator g(preinstall, false, nullptr, false); g.Generate(os, config, configurationTypes); } // Install this target if a destination is given. - if ((*l)->Target->GetInstallPath() != "") { + if (!l->Target->GetInstallPath().empty()) { // Compute the full install destination. Note that converting // to unix slashes also removes any trailing slash. // We also skip over the leading slash given by the user. - std::string destination = (*l)->Target->GetInstallPath().substr(1); + std::string destination = l->Target->GetInstallPath().substr(1); cmSystemTools::ConvertToUnixSlashes(destination); if (destination.empty()) { destination = "."; } // Generate the proper install generator for this target type. - switch ((*l)->GetType()) { + switch (l->GetType()) { case cmStateEnums::EXECUTABLE: case cmStateEnums::STATIC_LIBRARY: case cmStateEnums::MODULE_LIBRARY: { // Use a target install generator. - cmInstallTargetGeneratorLocal g(this, (*l)->GetName(), + cmInstallTargetGeneratorLocal g(this, l->GetName(), destination.c_str(), false); g.Generate(os, config, configurationTypes); } break; @@ -2161,18 +2121,18 @@ void cmLocalGenerator::GenerateTargetInstallRules( // Special code to handle DLL. Install the import library // to the normal destination and the DLL to the runtime // destination. - cmInstallTargetGeneratorLocal g1(this, (*l)->GetName(), + cmInstallTargetGeneratorLocal g1(this, l->GetName(), destination.c_str(), true); g1.Generate(os, config, configurationTypes); // We also skip over the leading slash given by the user. - destination = (*l)->Target->GetRuntimeInstallPath().substr(1); + destination = l->Target->GetRuntimeInstallPath().substr(1); cmSystemTools::ConvertToUnixSlashes(destination); - cmInstallTargetGeneratorLocal g2(this, (*l)->GetName(), + cmInstallTargetGeneratorLocal g2(this, l->GetName(), destination.c_str(), false); g2.Generate(os, config, configurationTypes); #else // Use a target install generator. - cmInstallTargetGeneratorLocal g(this, (*l)->GetName(), + cmInstallTargetGeneratorLocal g(this, l->GetName(), destination.c_str(), false); g.Generate(os, config, configurationTypes); #endif @@ -2183,7 +2143,7 @@ void cmLocalGenerator::GenerateTargetInstallRules( } // Include the user-specified post-install script for this target. - if (const char* postinstall = (*l)->GetProperty("POST_INSTALL_SCRIPT")) { + if (const char* postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) { cmInstallScriptGenerator g(postinstall, false, nullptr, false); g.Generate(os, config, configurationTypes); } diff --git a/Source/cmLocalNinjaGenerator.cxx b/Source/cmLocalNinjaGenerator.cxx index 9fa3ca5..477ce51 100644 --- a/Source/cmLocalNinjaGenerator.cxx +++ b/Source/cmLocalNinjaGenerator.cxx @@ -5,6 +5,7 @@ #include <algorithm> #include <assert.h> #include <iterator> +#include <memory> // IWYU pragma: keep #include <sstream> #include <stdio.h> #include <utility> @@ -22,7 +23,6 @@ #include "cmState.h" #include "cmStateTypes.h" #include "cmSystemTools.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" cmLocalNinjaGenerator::cmLocalNinjaGenerator(cmGlobalGenerator* gg, @@ -55,7 +55,7 @@ void cmLocalNinjaGenerator::Generate() this->HomeRelativeOutputPath = this->ConvertToRelativePath( this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory()); if (this->HomeRelativeOutputPath == ".") { - this->HomeRelativeOutputPath = ""; + this->HomeRelativeOutputPath.clear(); } this->WriteProcessedMakefile(this->GetBuildFileStream()); @@ -80,18 +80,18 @@ void cmLocalNinjaGenerator::Generate() } const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator t = targets.begin(); - t != targets.end(); ++t) { - if ((*t)->GetType() == cmStateEnums::INTERFACE_LIBRARY) { + for (cmGeneratorTarget* target : targets) { + if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) { continue; } - cmNinjaTargetGenerator* tg = cmNinjaTargetGenerator::New(*t); + cmNinjaTargetGenerator* tg = cmNinjaTargetGenerator::New(target); if (tg) { tg->Generate(); // Add the target to "all" if required. if (!this->GetGlobalNinjaGenerator()->IsExcluded( - this->GetGlobalNinjaGenerator()->GetLocalGenerators()[0], *t)) { - this->GetGlobalNinjaGenerator()->AddDependencyToAll(*t); + this->GetGlobalNinjaGenerator()->GetLocalGenerators()[0], + target)) { + this->GetGlobalNinjaGenerator()->AddDependencyToAll(target); } delete tg; } @@ -212,8 +212,7 @@ void cmLocalNinjaGenerator::WritePools(std::ostream& os) os, "Pools defined by global property JOB_POOLS"); std::vector<std::string> pools; cmSystemTools::ExpandListArgument(jobpools, pools); - for (size_t i = 0; i < pools.size(); ++i) { - std::string const& pool = pools[i]; + for (std::string const& pool : pools) { const std::string::size_type eq = pool.find('='); unsigned int jobs; if (eq != std::string::npos && @@ -250,12 +249,10 @@ void cmLocalNinjaGenerator::ComputeObjectFilenames( { // Determine if these object files should use a custom extension char const* custom_ext = gt->GetCustomObjectExtension(); - for (std::map<cmSourceFile const*, std::string>::iterator si = - mapping.begin(); - si != mapping.end(); ++si) { - cmSourceFile const* sf = si->first; + for (auto& si : mapping) { + cmSourceFile const* sf = si.first; bool keptSourceExtension; - si->second = this->GetObjectFileNameWithoutTarget( + si.second = this->GetObjectFileNameWithoutTarget( *sf, gt->ObjectDirectory, &keptSourceExtension, custom_ext); } } @@ -291,10 +288,9 @@ void cmLocalNinjaGenerator::AppendCustomCommandDeps( cmCustomCommandGenerator const& ccg, cmNinjaDeps& ninjaDeps) { const std::vector<std::string>& deps = ccg.GetDepends(); - for (std::vector<std::string>::const_iterator i = deps.begin(); - i != deps.end(); ++i) { + for (std::string const& i : deps) { std::string dep; - if (this->GetRealDependency(*i, this->GetConfigName(), dep)) { + if (this->GetRealDependency(i, this->GetConfigName(), dep)) { ninjaDeps.push_back( this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(dep)); } @@ -408,9 +404,8 @@ void cmLocalNinjaGenerator::WriteCustomCommandBuildStatement( this->GetGlobalNinjaGenerator()->MapToNinjaPath()); this->AppendCustomCommandDeps(ccg, ninjaDeps); - for (cmNinjaDeps::iterator i = ninjaOutputs.begin(); i != ninjaOutputs.end(); - ++i) { - this->GetGlobalNinjaGenerator()->SeenCustomCommandOutput(*i); + for (std::string const& ninjaOutput : ninjaOutputs) { + this->GetGlobalNinjaGenerator()->SeenCustomCommandOutput(ninjaOutput); } std::vector<std::string> cmdLines; @@ -445,10 +440,9 @@ void cmLocalNinjaGenerator::AddCustomCommandTarget(cmCustomCommand const* cc, void cmLocalNinjaGenerator::WriteCustomCommandBuildStatements() { - for (std::vector<cmCustomCommand const*>::iterator vi = - this->CustomCommands.begin(); - vi != this->CustomCommands.end(); ++vi) { - CustomCommandTargetMap::iterator i = this->CustomCommandTargets.find(*vi); + for (cmCustomCommand const* customCommand : this->CustomCommands) { + CustomCommandTargetMap::iterator i = + this->CustomCommandTargets.find(customCommand); assert(i != this->CustomCommandTargets.end()); // A custom command may appear on multiple targets. However, some build @@ -511,7 +505,7 @@ std::string cmLocalNinjaGenerator::MakeCustomLauncher( std::string launcher = property_value; launcher += " "; - CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander( + std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( this->CreateRulePlaceholderExpander()); rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars); diff --git a/Source/cmLocalNinjaGenerator.h b/Source/cmLocalNinjaGenerator.h index 83bc9d3..bb16899 100644 --- a/Source/cmLocalNinjaGenerator.h +++ b/Source/cmLocalNinjaGenerator.h @@ -38,14 +38,14 @@ class cmLocalNinjaGenerator : public cmLocalCommonGenerator public: cmLocalNinjaGenerator(cmGlobalGenerator* gg, cmMakefile* mf); - ~cmLocalNinjaGenerator() CM_OVERRIDE; + ~cmLocalNinjaGenerator() override; - void Generate() CM_OVERRIDE; + void Generate() override; - cmRulePlaceholderExpander* CreateRulePlaceholderExpander() const CM_OVERRIDE; + cmRulePlaceholderExpander* CreateRulePlaceholderExpander() const override; - std::string GetTargetDirectory(cmGeneratorTarget const* target) const - CM_OVERRIDE; + std::string GetTargetDirectory( + cmGeneratorTarget const* target) const override; const cmGlobalNinjaGenerator* GetGlobalNinjaGenerator() const; cmGlobalNinjaGenerator* GetGlobalNinjaGenerator(); @@ -76,13 +76,13 @@ public: void ComputeObjectFilenames( std::map<cmSourceFile const*, std::string>& mapping, - cmGeneratorTarget const* gt = nullptr) CM_OVERRIDE; + cmGeneratorTarget const* gt = nullptr) override; protected: std::string ConvertToIncludeReference( std::string const& path, cmOutputConverter::OutputFormat format = cmOutputConverter::SHELL, - bool forceFullPaths = false) CM_OVERRIDE; + bool forceFullPaths = false) override; private: cmGeneratedFileStream& GetBuildFileStream() const; @@ -105,7 +105,7 @@ private: std::string HomeRelativeOutputPath; - typedef std::map<cmCustomCommand const*, std::set<cmGeneratorTarget*> > + typedef std::map<cmCustomCommand const*, std::set<cmGeneratorTarget*>> CustomCommandTargetMap; CustomCommandTargetMap CustomCommandTargets; std::vector<cmCustomCommand const*> CustomCommands; diff --git a/Source/cmLocalUnixMakefileGenerator3.cxx b/Source/cmLocalUnixMakefileGenerator3.cxx index cde2621..e26182a 100644 --- a/Source/cmLocalUnixMakefileGenerator3.cxx +++ b/Source/cmLocalUnixMakefileGenerator3.cxx @@ -5,13 +5,12 @@ #include "cmsys/FStream.hxx" #include "cmsys/Terminal.h" #include <algorithm> -#include <functional> +#include <memory> // IWYU pragma: keep #include <sstream> #include <stdio.h> #include <utility> #include "cmAlgorithms.h" -#include "cmCustomCommand.h" #include "cmCustomCommandGenerator.h" #include "cmFileTimeComparison.h" #include "cmGeneratedFileStream.h" @@ -30,7 +29,6 @@ #include "cmStateTypes.h" #include "cmSystemTools.h" #include "cmVersion.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" // Include dependency scanners for supported languages. Only the @@ -119,14 +117,13 @@ void cmLocalUnixMakefileGenerator3::Generate() const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets(); cmGlobalUnixMakefileGenerator3* gg = static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator); - for (std::vector<cmGeneratorTarget*>::const_iterator t = targets.begin(); - t != targets.end(); ++t) { - if ((*t)->GetType() == cmStateEnums::INTERFACE_LIBRARY) { + for (cmGeneratorTarget* target : targets) { + if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) { continue; } - CM_AUTO_PTR<cmMakefileTargetGenerator> tg( - cmMakefileTargetGenerator::New(*t)); - if (tg.get()) { + std::unique_ptr<cmMakefileTargetGenerator> tg( + cmMakefileTargetGenerator::New(target)); + if (tg) { tg->WriteRuleFiles(); gg->RecordTargetProgress(tg.get()); } @@ -146,7 +143,7 @@ void cmLocalUnixMakefileGenerator3::ComputeHomeRelativeOutputPath() this->HomeRelativeOutputPath = this->MaybeConvertToRelativePath( this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory()); if (this->HomeRelativeOutputPath == ".") { - this->HomeRelativeOutputPath = ""; + this->HomeRelativeOutputPath.clear(); } if (!this->HomeRelativeOutputPath.empty()) { this->HomeRelativeOutputPath += "/"; @@ -159,12 +156,10 @@ void cmLocalUnixMakefileGenerator3::ComputeObjectFilenames( { // Determine if these object files should use a custom extension char const* custom_ext = gt->GetCustomObjectExtension(); - for (std::map<cmSourceFile const*, std::string>::iterator si = - mapping.begin(); - si != mapping.end(); ++si) { - cmSourceFile const* sf = si->first; + for (auto& si : mapping) { + cmSourceFile const* sf = si.first; bool keptSourceExtension; - si->second = this->GetObjectFileNameWithoutTarget( + si.second = this->GetObjectFileNameWithoutTarget( *sf, gt->ObjectDirectory, &keptSourceExtension, custom_ext); } } @@ -173,9 +168,7 @@ void cmLocalUnixMakefileGenerator3::GetLocalObjectFiles( std::map<std::string, LocalObjectInfo>& localObjectFiles) { const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets(); - for (std::vector<cmGeneratorTarget*>::const_iterator ti = targets.begin(); - ti != targets.end(); ++ti) { - cmGeneratorTarget* gt = *ti; + for (cmGeneratorTarget* gt : targets) { if (gt->GetType() == cmStateEnums::INTERFACE_LIBRARY) { continue; } @@ -189,9 +182,7 @@ void cmLocalUnixMakefileGenerator3::GetLocalObjectFiles( dir += this->GetTargetDirectory(gt); dir += "/"; // Compute the name of each object file. - for (std::vector<cmSourceFile const*>::iterator si = objectSources.begin(); - si != objectSources.end(); ++si) { - cmSourceFile const* sf = *si; + for (cmSourceFile const* sf : objectSources) { bool hasSourceExtension = true; std::string objectName = this->GetObjectFileNameWithoutTarget(*sf, dir, &hasSourceExtension); @@ -210,18 +201,16 @@ void cmLocalUnixMakefileGenerator3::GetIndividualFileTargets( { std::map<std::string, LocalObjectInfo> localObjectFiles; this->GetLocalObjectFiles(localObjectFiles); - for (std::map<std::string, LocalObjectInfo>::iterator lo = - localObjectFiles.begin(); - lo != localObjectFiles.end(); ++lo) { - targets.push_back(lo->first); - - std::string::size_type dot_pos = lo->first.rfind("."); - std::string base = lo->first.substr(0, dot_pos); - if (lo->second.HasPreprocessRule) { + for (auto const& localObjectFile : localObjectFiles) { + targets.push_back(localObjectFile.first); + + std::string::size_type dot_pos = localObjectFile.first.rfind("."); + std::string base = localObjectFile.first.substr(0, dot_pos); + if (localObjectFile.second.HasPreprocessRule) { targets.push_back(base + ".i"); } - if (lo->second.HasAssembleRule) { + if (localObjectFile.second.HasAssembleRule) { targets.push_back(base + ".s"); } } @@ -270,23 +259,20 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefile() // now write out the object rules // for each object file name - for (std::map<std::string, LocalObjectInfo>::iterator lo = - localObjectFiles.begin(); - lo != localObjectFiles.end(); ++lo) { + for (auto& localObjectFile : localObjectFiles) { // Add a convenience rule for building the object file. - this->WriteObjectConvenienceRule(ruleFileStream, - "target to build an object file", - lo->first.c_str(), lo->second); + this->WriteObjectConvenienceRule( + ruleFileStream, "target to build an object file", + localObjectFile.first.c_str(), localObjectFile.second); // Check whether preprocessing and assembly rules make sense. // They make sense only for C and C++ sources. bool lang_has_preprocessor = false; bool lang_has_assembly = false; - for (std::vector<LocalObjectEntry>::const_iterator ei = lo->second.begin(); - ei != lo->second.end(); ++ei) { - if (ei->Language == "C" || ei->Language == "CXX" || - ei->Language == "CUDA" || ei->Language == "Fortran") { + for (LocalObjectEntry const& entry : localObjectFile.second) { + if (entry.Language == "C" || entry.Language == "CXX" || + entry.Language == "CUDA" || entry.Language == "Fortran") { // Right now, C, C++, Fortran and CUDA have both a preprocessor and the // ability to generate assembly code lang_has_preprocessor = true; @@ -297,21 +283,21 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefile() // Add convenience rules for preprocessed and assembly files. if (lang_has_preprocessor && do_preprocess_rules) { - std::string::size_type dot_pos = lo->first.rfind("."); - std::string base = lo->first.substr(0, dot_pos); - this->WriteObjectConvenienceRule(ruleFileStream, - "target to preprocess a source file", - (base + ".i").c_str(), lo->second); - lo->second.HasPreprocessRule = true; + std::string::size_type dot_pos = localObjectFile.first.rfind("."); + std::string base = localObjectFile.first.substr(0, dot_pos); + this->WriteObjectConvenienceRule( + ruleFileStream, "target to preprocess a source file", + (base + ".i").c_str(), localObjectFile.second); + localObjectFile.second.HasPreprocessRule = true; } if (lang_has_assembly && do_assembly_rules) { - std::string::size_type dot_pos = lo->first.rfind("."); - std::string base = lo->first.substr(0, dot_pos); + std::string::size_type dot_pos = localObjectFile.first.rfind("."); + std::string base = localObjectFile.first.substr(0, dot_pos); this->WriteObjectConvenienceRule( ruleFileStream, "target to generate assembly for a file", - (base + ".s").c_str(), lo->second); - lo->second.HasAssembleRule = true; + (base + ".s").c_str(), localObjectFile.second); + localObjectFile.second.HasAssembleRule = true; } } @@ -355,9 +341,8 @@ void cmLocalUnixMakefileGenerator3::WriteObjectConvenienceRule( // Recursively make the rule for each target using the object file. std::vector<std::string> commands; - for (std::vector<LocalObjectEntry>::const_iterator t = info.begin(); - t != info.end(); ++t) { - std::string tgtMakefileName = this->GetRelativeTargetDirectory(t->Target); + for (LocalObjectEntry const& t : info) { + std::string tgtMakefileName = this->GetRelativeTargetDirectory(t.Target); std::string targetName = tgtMakefileName; tgtMakefileName += "/build.make"; targetName += "/"; @@ -384,18 +369,17 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets( // on the target const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets(); std::string localName; - for (std::vector<cmGeneratorTarget*>::const_iterator t = targets.begin(); - t != targets.end(); ++t) { - if (((*t)->GetType() == cmStateEnums::EXECUTABLE) || - ((*t)->GetType() == cmStateEnums::STATIC_LIBRARY) || - ((*t)->GetType() == cmStateEnums::SHARED_LIBRARY) || - ((*t)->GetType() == cmStateEnums::MODULE_LIBRARY) || - ((*t)->GetType() == cmStateEnums::OBJECT_LIBRARY) || - ((*t)->GetType() == cmStateEnums::UTILITY)) { - emitted.insert((*t)->GetName()); + for (cmGeneratorTarget* target : targets) { + if ((target->GetType() == cmStateEnums::EXECUTABLE) || + (target->GetType() == cmStateEnums::STATIC_LIBRARY) || + (target->GetType() == cmStateEnums::SHARED_LIBRARY) || + (target->GetType() == cmStateEnums::MODULE_LIBRARY) || + (target->GetType() == cmStateEnums::OBJECT_LIBRARY) || + (target->GetType() == cmStateEnums::UTILITY)) { + emitted.insert(target->GetName()); // for subdirs add a rule to build this specific target by name. - localName = this->GetRelativeTargetDirectory(*t); + localName = this->GetRelativeTargetDirectory(target); localName += "/rule"; commands.clear(); depends.clear(); @@ -411,20 +395,20 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets( localName, depends, commands, true); // Add a target with the canonical name (no prefix, suffix or path). - if (localName != (*t)->GetName()) { + if (localName != target->GetName()) { commands.clear(); depends.push_back(localName); this->WriteMakeRule(ruleFileStream, "Convenience name for target.", - (*t)->GetName(), depends, commands, true); + target->GetName(), depends, commands, true); } // Add a fast rule to build the target - std::string makefileName = this->GetRelativeTargetDirectory(*t); + std::string makefileName = this->GetRelativeTargetDirectory(target); makefileName += "/build.make"; // make sure the makefile name is suitable for a makefile - std::string makeTargetName = this->GetRelativeTargetDirectory(*t); + std::string makeTargetName = this->GetRelativeTargetDirectory(target); makeTargetName += "/build"; - localName = (*t)->GetName(); + localName = target->GetName(); localName += "/fast"; depends.clear(); commands.clear(); @@ -437,10 +421,10 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets( // Add a local name for the rule to relink the target before // installation. - if ((*t)->NeedRelinkBeforeInstall(this->ConfigName)) { - makeTargetName = this->GetRelativeTargetDirectory(*t); + if (target->NeedRelinkBeforeInstall(this->ConfigName)) { + makeTargetName = this->GetRelativeTargetDirectory(target); makeTargetName += "/preinstall"; - localName = (*t)->GetName(); + localName = target->GetName(); localName += "/preinstall"; depends.clear(); commands.clear(); @@ -581,9 +565,8 @@ void cmLocalUnixMakefileGenerator3::WriteMakeRule( // Split dependencies into multiple rule lines. This allows for // very long dependency lists even on older make implementations. std::string binDir = this->GetBinaryDirectory(); - for (std::vector<std::string>::const_iterator dep = depends.begin(); - dep != depends.end(); ++dep) { - replace = *dep; + for (std::string const& depend : depends) { + replace = depend; replace = cmSystemTools::ConvertToOutputPath( this->MaybeConvertToRelativePath(binDir, replace).c_str()); os << cmMakeSafe(tgt) << space << ": " << cmMakeSafe(replace) << "\n"; @@ -892,9 +875,8 @@ void cmLocalUnixMakefileGenerator3::AppendRuleDepends( void cmLocalUnixMakefileGenerator3::AppendCustomDepends( std::vector<std::string>& depends, const std::vector<cmCustomCommand>& ccs) { - for (std::vector<cmCustomCommand>::const_iterator i = ccs.begin(); - i != ccs.end(); ++i) { - cmCustomCommandGenerator ccg(*i, this->ConfigName, this); + for (cmCustomCommand const& cc : ccs) { + cmCustomCommandGenerator ccg(cc, this->ConfigName, this); this->AppendCustomDepend(depends, ccg); } } @@ -902,11 +884,10 @@ void cmLocalUnixMakefileGenerator3::AppendCustomDepends( void cmLocalUnixMakefileGenerator3::AppendCustomDepend( std::vector<std::string>& depends, cmCustomCommandGenerator const& ccg) { - for (std::vector<std::string>::const_iterator d = ccg.GetDepends().begin(); - d != ccg.GetDepends().end(); ++d) { + for (std::string const& d : ccg.GetDepends()) { // Lookup the real name of the dependency in case it is a CMake target. std::string dep; - if (this->GetRealDependency(*d, this->ConfigName, dep)) { + if (this->GetRealDependency(d, this->ConfigName, dep)) { depends.push_back(dep); } } @@ -916,9 +897,8 @@ void cmLocalUnixMakefileGenerator3::AppendCustomCommands( std::vector<std::string>& commands, const std::vector<cmCustomCommand>& ccs, cmGeneratorTarget* target, std::string const& relative) { - for (std::vector<cmCustomCommand>::const_iterator i = ccs.begin(); - i != ccs.end(); ++i) { - cmCustomCommandGenerator ccg(*i, this->ConfigName, this); + for (cmCustomCommand const& cc : ccs) { + cmCustomCommandGenerator ccg(cc, this->ConfigName, this); this->AppendCustomCommand(commands, ccg, target, relative, true); } } @@ -950,7 +930,7 @@ void cmLocalUnixMakefileGenerator3::AppendCustomCommand( *content << dir; } - CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander( + std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( this->CreateRulePlaceholderExpander()); // Add each command line to the set of commands. @@ -1089,9 +1069,8 @@ void cmLocalUnixMakefileGenerator3::AppendCleanCommand( } if (!files.empty()) { fout << "file(REMOVE_RECURSE\n"; - for (std::vector<std::string>::const_iterator f = files.begin(); - f != files.end(); ++f) { - std::string fc = this->MaybeConvertToRelativePath(currentBinDir, *f); + for (std::string const& file : files) { + std::string fc = this->MaybeConvertToRelativePath(currentBinDir, file); fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n"; } fout << ")\n"; @@ -1183,7 +1162,7 @@ void cmLocalUnixMakefileGenerator3::AppendEcho( } // Reset the line to emtpy. - line = ""; + line.clear(); // Progress appears only on first line. progress = nullptr; @@ -1454,11 +1433,8 @@ bool cmLocalUnixMakefileGenerator3::ScanDependencies( const char* langStr = mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES"); std::vector<std::string> langs; cmSystemTools::ExpandListArgument(langStr, langs); - for (std::vector<std::string>::iterator li = langs.begin(); - li != langs.end(); ++li) { + for (std::string const& lang : langs) { // construct the checker - std::string lang = *li; - // Create the scanner for this language cmDepends* scanner = nullptr; if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" || @@ -1563,25 +1539,22 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules( ruleFileStream << "# Targets provided globally by CMake.\n" << "\n"; const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets(); - std::vector<cmGeneratorTarget*>::const_iterator glIt; - for (glIt = targets.begin(); glIt != targets.end(); ++glIt) { - if ((*glIt)->GetType() == cmStateEnums::GLOBAL_TARGET) { + for (cmGeneratorTarget* gt : targets) { + if (gt->GetType() == cmStateEnums::GLOBAL_TARGET) { std::string targetString = - "Special rule for the target " + (*glIt)->GetName(); + "Special rule for the target " + gt->GetName(); std::vector<std::string> commands; std::vector<std::string> depends; - const char* text = (*glIt)->GetProperty("EchoString"); + const char* text = gt->GetProperty("EchoString"); if (!text) { text = "Running external command ..."; } - depends.insert(depends.end(), (*glIt)->GetUtilities().begin(), - (*glIt)->GetUtilities().end()); + depends.insert(depends.end(), gt->GetUtilities().begin(), + gt->GetUtilities().end()); this->AppendEcho(commands, text, cmLocalUnixMakefileGenerator3::EchoGlobal); - cmGeneratorTarget* gt = *glIt; - // Global targets store their rules in pre- and post-build commands. this->AppendCustomDepends(depends, gt->GetPreBuildCommands()); this->AppendCustomDepends(depends, gt->GetPostBuildCommands()); @@ -1728,9 +1701,8 @@ void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf, // dependencies for that target. cmDepends clearer; clearer.SetVerbose(verbose); - for (std::vector<std::string>::iterator l = files.begin(); l != files.end(); - ++l) { - std::string dir = cmSystemTools::GetFilenamePath(*l); + for (std::string const& file : files) { + std::string dir = cmSystemTools::GetFilenamePath(file); // Clear the implicit dependency makefile. std::string dependFile = dir + "/depend.make"; @@ -1802,54 +1774,51 @@ void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo( cmakefileStream << "# The set of languages for which implicit dependencies are needed:\n"; cmakefileStream << "set(CMAKE_DEPENDS_LANGUAGES\n"; - for (ImplicitDependLanguageMap::const_iterator l = implicitLangs.begin(); - l != implicitLangs.end(); ++l) { - cmakefileStream << " \"" << l->first << "\"\n"; + for (auto const& implicitLang : implicitLangs) { + cmakefileStream << " \"" << implicitLang.first << "\"\n"; } cmakefileStream << " )\n"; // now list the files for each language cmakefileStream << "# The set of files for implicit dependencies of each language:\n"; - for (ImplicitDependLanguageMap::const_iterator l = implicitLangs.begin(); - l != implicitLangs.end(); ++l) { - cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << l->first << "\n"; - ImplicitDependFileMap const& implicitPairs = l->second; + for (auto const& implicitLang : implicitLangs) { + cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << implicitLang.first + << "\n"; + ImplicitDependFileMap const& implicitPairs = implicitLang.second; // for each file pair - for (ImplicitDependFileMap::const_iterator pi = implicitPairs.begin(); - pi != implicitPairs.end(); ++pi) { - for (cmDepends::DependencyVector::const_iterator di = pi->second.begin(); - di != pi->second.end(); ++di) { - cmakefileStream << " \"" << *di << "\" "; - cmakefileStream << "\"" << pi->first << "\"\n"; + for (auto const& implicitPair : implicitPairs) { + for (auto const& di : implicitPair.second) { + cmakefileStream << " \"" << di << "\" "; + cmakefileStream << "\"" << implicitPair.first << "\"\n"; } } cmakefileStream << " )\n"; // Tell the dependency scanner what compiler is used. std::string cidVar = "CMAKE_"; - cidVar += l->first; + cidVar += implicitLang.first; cidVar += "_COMPILER_ID"; const char* cid = this->Makefile->GetDefinition(cidVar); if (cid && *cid) { - cmakefileStream << "set(CMAKE_" << l->first << "_COMPILER_ID \"" << cid - << "\")\n"; + cmakefileStream << "set(CMAKE_" << implicitLang.first + << "_COMPILER_ID \"" << cid << "\")\n"; } // Build a list of preprocessor definitions for the target. std::set<std::string> defines; - this->AddCompileDefinitions(defines, target, this->ConfigName, l->first); + this->AddCompileDefinitions(defines, target, this->ConfigName, + implicitLang.first); if (!defines.empty()) { /* clang-format off */ cmakefileStream << "\n" << "# Preprocessor definitions for this target.\n" - << "set(CMAKE_TARGET_DEFINITIONS_" << l->first << "\n"; + << "set(CMAKE_TARGET_DEFINITIONS_" << implicitLang.first << "\n"; /* clang-format on */ - for (std::set<std::string>::const_iterator di = defines.begin(); - di != defines.end(); ++di) { - cmakefileStream << " " << cmOutputConverter::EscapeForCMake(*di) + for (std::string const& define : defines) { + cmakefileStream << " " << cmOutputConverter::EscapeForCMake(define) << "\n"; } cmakefileStream << " )\n"; @@ -1858,21 +1827,21 @@ void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo( // Target-specific include directories: cmakefileStream << "\n" << "# The include file search paths:\n"; - cmakefileStream << "set(CMAKE_" << l->first << "_TARGET_INCLUDE_PATH\n"; + cmakefileStream << "set(CMAKE_" << implicitLang.first + << "_TARGET_INCLUDE_PATH\n"; std::vector<std::string> includes; const std::string& config = this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"); - this->GetIncludeDirectories(includes, target, l->first, config); + this->GetIncludeDirectories(includes, target, implicitLang.first, config); std::string binaryDir = this->GetState()->GetBinaryDirectory(); if (this->Makefile->IsOn("CMAKE_DEPENDS_IN_PROJECT_ONLY")) { const char* sourceDir = this->GetState()->GetSourceDirectory(); cmEraseIf(includes, ::NotInProjectDir(sourceDir, binaryDir)); } - for (std::vector<std::string>::iterator i = includes.begin(); - i != includes.end(); ++i) { + for (std::string const& include : includes) { cmakefileStream << " \"" - << this->MaybeConvertToRelativePath(binaryDir, *i) + << this->MaybeConvertToRelativePath(binaryDir, include) << "\"\n"; } cmakefileStream << " )\n"; @@ -1891,10 +1860,8 @@ void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo( } if (!transformRules.empty()) { cmakefileStream << "set(CMAKE_INCLUDE_TRANSFORMS\n"; - for (std::vector<std::string>::const_iterator tri = transformRules.begin(); - tri != transformRules.end(); ++tri) { - cmakefileStream << " " << cmOutputConverter::EscapeForCMake(*tri) - << "\n"; + for (std::string const& tr : transformRules) { + cmakefileStream << " " << cmOutputConverter::EscapeForCMake(tr) << "\n"; } cmakefileStream << " )\n"; } @@ -2004,10 +1971,9 @@ std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath( #if defined(_WIN32) && !defined(__CYGWIN__) if (!cmSystemTools::GetForceUnixPaths()) { slash = "\\"; - for (std::string::iterator i = components[0].begin(); - i != components[0].end(); ++i) { - if (*i == '/') { - *i = '\\'; + for (char& i : components[0]) { + if (i == '/') { + i = '\\'; } } } @@ -2106,7 +2072,7 @@ void cmLocalUnixMakefileGenerator3::CreateCDCommand( std::string outputForExisting = this->ConvertToOutputForExisting(tgtDir); std::string prefix = cd_cmd + outputForExisting + " && "; std::transform(commands.begin(), commands.end(), commands.begin(), - std::bind1st(std::plus<std::string>(), prefix)); + [&prefix](std::string const& s) { return prefix + s; }); } } diff --git a/Source/cmLocalUnixMakefileGenerator3.h b/Source/cmLocalUnixMakefileGenerator3.h index 16c305a..b149524 100644 --- a/Source/cmLocalUnixMakefileGenerator3.h +++ b/Source/cmLocalUnixMakefileGenerator3.h @@ -31,14 +31,14 @@ class cmLocalUnixMakefileGenerator3 : public cmLocalCommonGenerator { public: cmLocalUnixMakefileGenerator3(cmGlobalGenerator* gg, cmMakefile* mf); - ~cmLocalUnixMakefileGenerator3() CM_OVERRIDE; + ~cmLocalUnixMakefileGenerator3() override; - void ComputeHomeRelativeOutputPath() CM_OVERRIDE; + void ComputeHomeRelativeOutputPath() override; /** * Generate the makefile for this directory. */ - void Generate() CM_OVERRIDE; + void Generate() override; // this returns the relative path between the HomeOutputDirectory and this // local generators StartOutputDirectory @@ -88,9 +88,8 @@ public: const std::string& tgt); // append flags to a string - void AppendFlags(std::string& flags, - const std::string& newFlags) CM_OVERRIDE; - void AppendFlags(std::string& flags, const char* newFlags) CM_OVERRIDE; + void AppendFlags(std::string& flags, const std::string& newFlags) override; + void AppendFlags(std::string& flags, const char* newFlags) override; // append an echo command enum EchoColor @@ -113,8 +112,8 @@ public: /** Get whether the makefile is to have color. */ bool GetColorMakefile() const { return this->ColorMakefile; } - std::string GetTargetDirectory(cmGeneratorTarget const* target) const - CM_OVERRIDE; + std::string GetTargetDirectory( + cmGeneratorTarget const* target) const override; // create a command that cds to the start dir then runs the commands void CreateCDCommand(std::vector<std::string>& commands, @@ -129,10 +128,10 @@ public: /** Called from command-line hook to bring dependencies up to date for a target. */ bool UpdateDependencies(const char* tgtInfo, bool verbose, - bool color) CM_OVERRIDE; + bool color) override; /** Called from command-line hook to clear dependencies. */ - void ClearDependencies(cmMakefile* mf, bool verbose) CM_OVERRIDE; + void ClearDependencies(cmMakefile* mf, bool verbose) override; /** write some extra rules such as make test etc */ void WriteSpecialTargetsTop(std::ostream& makefileStream); @@ -254,7 +253,7 @@ private: void ComputeObjectFilenames( std::map<cmSourceFile const*, std::string>& mapping, - cmGeneratorTarget const* gt = nullptr) CM_OVERRIDE; + cmGeneratorTarget const* gt = nullptr) override; friend class cmMakefileTargetGenerator; friend class cmMakefileExecutableTargetGenerator; diff --git a/Source/cmLocalVisualStudio10Generator.cxx b/Source/cmLocalVisualStudio10Generator.cxx index db1776a..5e81514 100644 --- a/Source/cmLocalVisualStudio10Generator.cxx +++ b/Source/cmLocalVisualStudio10Generator.cxx @@ -17,7 +17,12 @@ public: virtual void CharacterDataHandler(const char* data, int length) { if (this->DoGUID) { - this->GUID.assign(data + 1, length - 2); + if (data[0] == '{') { + // remove surrounding curly brackets + this->GUID.assign(data + 1, length - 2); + } else { + this->GUID.assign(data, length); + } this->DoGUID = false; } } diff --git a/Source/cmLocalVisualStudio7Generator.cxx b/Source/cmLocalVisualStudio7Generator.cxx index 857ce46..8027191 100644 --- a/Source/cmLocalVisualStudio7Generator.cxx +++ b/Source/cmLocalVisualStudio7Generator.cxx @@ -121,7 +121,7 @@ void cmLocalVisualStudio7Generator::FixGlobalTargets() force_command.push_back("."); cmCustomCommandLines force_commands; force_commands.push_back(force_command); - std::string no_main_dependency = ""; + std::string no_main_dependency; std::string force = this->GetCurrentBinaryDirectory(); force += cmake::GetCMakeFilesDirectory(); force += "/"; @@ -526,6 +526,7 @@ cmVS7FlagTable cmLocalVisualStudio7GeneratorLinkFlagTable[] = { { "TargetMachine", "MACHINE:SH5", "Machine SH5", "15", 0 }, { "TargetMachine", "MACHINE:THUMB", "Machine THUMB", "16", 0 }, { "TargetMachine", "MACHINE:X64", "Machine x64", "17", 0 }, + { "TargetMachine", "MACHINE:ARM64", "Machine ARM64", "18", 0 }, { "TurnOffAssemblyGeneration", "NOASSEMBLY", "No assembly even if CLR information is present in objects.", "true", 0 }, { "ModuleDefinitionFile", "DEF:", "add an export def file", "", @@ -1452,7 +1453,7 @@ cmLocalVisualStudio7GeneratorFCInfo::cmLocalVisualStudio7GeneratorFCInfo( } if (const char* cflags = sf.GetProperty("COMPILE_FLAGS")) { cmGeneratorExpression ge; - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(cflags); + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(cflags); fc.CompileFlags = cge->Evaluate(lg, *i); needfc = true; } @@ -1590,7 +1591,7 @@ bool cmLocalVisualStudio7Generator::WriteGroup( // If the group has a name, write the header. std::string name = sg->GetName(); - if (name != "") { + if (!name.empty()) { this->WriteVCProjBeginGroup(fout, name.c_str(), ""); } @@ -1708,7 +1709,7 @@ bool cmLocalVisualStudio7Generator::WriteGroup( } // If the group has a name, write the footer. - if (name != "") { + if (!name.empty()) { this->WriteVCProjEndGroup(fout); } @@ -1848,7 +1849,7 @@ void cmLocalVisualStudio7Generator::OutputTargetRules( if (!addedPrelink) { event.Write(target->GetPreLinkCommands()); } - CM_AUTO_PTR<cmCustomCommand> pcc( + std::unique_ptr<cmCustomCommand> pcc( this->MaybeCreateImplibDir(target, configName, this->FortranProject)); if (pcc.get()) { event.Write(*pcc); @@ -2005,7 +2006,7 @@ void cmLocalVisualStudio7Generator::WriteVCProjFooter( i != props.end(); ++i) { if (i->find("VS_GLOBAL_") == 0) { std::string name = i->substr(10); - if (name != "") { + if (!name.empty()) { /* clang-format off */ fout << "\t\t<Global\n" << "\t\t\tName=\"" << name << "\"\n" @@ -2078,9 +2079,12 @@ public: if (strcmp(atts[i], "ProjectGUID") == 0) { if (atts[i + 1]) { this->GUID = atts[i + 1]; - this->GUID = this->GUID.substr(1, this->GUID.size() - 2); + if (this->GUID[0] == '{') { + // remove surrounding curly brackets + this->GUID = this->GUID.substr(1, this->GUID.size() - 2); + } } else { - this->GUID = ""; + this->GUID.clear(); } return; } diff --git a/Source/cmLocalVisualStudioGenerator.cxx b/Source/cmLocalVisualStudioGenerator.cxx index 41025af..bbb91e0 100644 --- a/Source/cmLocalVisualStudioGenerator.cxx +++ b/Source/cmLocalVisualStudioGenerator.cxx @@ -78,12 +78,12 @@ void cmLocalVisualStudioGenerator::ComputeObjectFilenames( } } -CM_AUTO_PTR<cmCustomCommand> +std::unique_ptr<cmCustomCommand> cmLocalVisualStudioGenerator::MaybeCreateImplibDir(cmGeneratorTarget* target, const std::string& config, bool isFortran) { - CM_AUTO_PTR<cmCustomCommand> pcc; + std::unique_ptr<cmCustomCommand> pcc; // If an executable exports symbols then VS wants to create an // import library but forgets to create the output directory. @@ -135,7 +135,7 @@ std::string cmLocalVisualStudioGenerator::ConstructScript( std::string workingDirectory = ccg.GetWorkingDirectory(); // Avoid leading or trailing newlines. - std::string newline = ""; + std::string newline; // Line to check for error between commands. std::string check_error = newline_text; @@ -191,13 +191,17 @@ std::string cmLocalVisualStudioGenerator::ConstructScript( // Write each command on a single line. for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) { + // Add this command line. + std::string cmd = ccg.GetCommand(c); + + if (cmd.empty()) { + continue; + } + // Start a new line. script += newline; newline = newline_text; - // Add this command line. - std::string cmd = ccg.GetCommand(c); - // Use "call " before any invocations of .bat or .cmd files // invoked as custom commands. // diff --git a/Source/cmLocalVisualStudioGenerator.h b/Source/cmLocalVisualStudioGenerator.h index c47db4f..cba24fe 100644 --- a/Source/cmLocalVisualStudioGenerator.h +++ b/Source/cmLocalVisualStudioGenerator.h @@ -6,12 +6,11 @@ #include "cmConfigure.h" // IWYU pragma: keep #include <map> -#include <memory> +#include <memory> // IWYU pragma: keep #include <string> #include "cmGlobalVisualStudioGenerator.h" #include "cmLocalGenerator.h" -#include "cm_auto_ptr.hxx" class cmCustomCommand; class cmCustomCommandGenerator; @@ -56,9 +55,8 @@ protected: virtual bool CustomCommandUseLocal() const { return false; } /** Construct a custom command to make exe import lib dir. */ - CM_AUTO_PTR<cmCustomCommand> MaybeCreateImplibDir(cmGeneratorTarget* target, - const std::string& config, - bool isFortran); + std::unique_ptr<cmCustomCommand> MaybeCreateImplibDir( + cmGeneratorTarget* target, const std::string& config, bool isFortran); }; #endif diff --git a/Source/cmLocalXCodeGenerator.h b/Source/cmLocalXCodeGenerator.h index 4ca02a9..b05eab7 100644 --- a/Source/cmLocalXCodeGenerator.h +++ b/Source/cmLocalXCodeGenerator.h @@ -36,7 +36,7 @@ public: virtual void GenerateInstallRules(); virtual void ComputeObjectFilenames( std::map<cmSourceFile const*, std::string>& mapping, - cmGeneratorTarget const* gt = 0); + cmGeneratorTarget const* gt = nullptr); private: }; diff --git a/Source/cmMSVC60LinkLineComputer.h b/Source/cmMSVC60LinkLineComputer.h index 19e2c16..31223ec 100644 --- a/Source/cmMSVC60LinkLineComputer.h +++ b/Source/cmMSVC60LinkLineComputer.h @@ -21,8 +21,7 @@ public: cmMSVC60LinkLineComputer(cmOutputConverter* outputConverter, cmStateDirectory const& stateDir); - std::string ConvertToLinkReference(std::string const& input) const - CM_OVERRIDE; + std::string ConvertToLinkReference(std::string const& input) const override; }; #endif diff --git a/Source/cmMachO.cxx b/Source/cmMachO.cxx index a4350f7..3706dd3 100644 --- a/Source/cmMachO.cxx +++ b/Source/cmMachO.cxx @@ -283,7 +283,7 @@ bool cmMachOInternal::read_mach_o(uint32_t file_offset) return false; } - cmMachOHeaderAndLoadCommands* f = NULL; + cmMachOHeaderAndLoadCommands* f = nullptr; if (magic == MH_CIGAM || magic == MH_MAGIC) { bool swap = false; if (magic == MH_CIGAM) { @@ -313,7 +313,7 @@ bool cmMachOInternal::read_mach_o(uint32_t file_offset) // External class implementation. cmMachO::cmMachO(const char* fname) - : Internal(0) + : Internal(nullptr) { this->Internal = new cmMachOInternal(fname); } diff --git a/Source/cmMacroCommand.cxx b/Source/cmMacroCommand.cxx index a6a9ea3..74a1da0 100644 --- a/Source/cmMacroCommand.cxx +++ b/Source/cmMacroCommand.cxx @@ -19,12 +19,12 @@ public: cmMacroHelperCommand() {} ///! clean up any memory allocated by the macro - ~cmMacroHelperCommand() CM_OVERRIDE {} + ~cmMacroHelperCommand() override {} /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { cmMacroHelperCommand* newC = new cmMacroHelperCommand; // we must copy when we clone @@ -40,10 +40,10 @@ public: * the CMakeLists.txt file. */ bool InvokeInitialPass(const std::vector<cmListFileArgument>& args, - cmExecutionStatus&) CM_OVERRIDE; + cmExecutionStatus&) override; bool InitialPass(std::vector<std::string> const&, - cmExecutionStatus&) CM_OVERRIDE + cmExecutionStatus&) override { return false; } @@ -98,20 +98,18 @@ bool cmMacroHelperCommand::InvokeInitialPass( // Invoke all the functions that were collected in the block. cmListFileFunction newLFF; // for each function - for (unsigned int c = 0; c < this->Functions.size(); ++c) { + for (cmListFileFunction const& func : this->Functions) { // Replace the formal arguments and then invoke the command. newLFF.Arguments.clear(); - newLFF.Arguments.reserve(this->Functions[c].Arguments.size()); - newLFF.Name = this->Functions[c].Name; - newLFF.Line = this->Functions[c].Line; + newLFF.Arguments.reserve(func.Arguments.size()); + newLFF.Name = func.Name; + newLFF.Line = func.Line; // for each argument of the current function - for (std::vector<cmListFileArgument>::iterator k = - this->Functions[c].Arguments.begin(); - k != this->Functions[c].Arguments.end(); ++k) { + for (cmListFileArgument const& k : func.Arguments) { cmListFileArgument arg; - arg.Value = k->Value; - if (k->Delim != cmListFileArgument::Bracket) { + arg.Value = k.Value; + if (k.Delim != cmListFileArgument::Bracket) { // replace formal arguments for (unsigned int j = 0; j < variables.size(); ++j) { cmSystemTools::ReplaceString(arg.Value, variables[j], @@ -131,8 +129,8 @@ bool cmMacroHelperCommand::InvokeInitialPass( } } } - arg.Delim = k->Delim; - arg.Line = k->Line; + arg.Delim = k.Delim; + arg.Line = k.Line; newLFF.Arguments.push_back(arg); } cmExecutionStatus status; diff --git a/Source/cmMacroCommand.h b/Source/cmMacroCommand.h index cbfb60f..d967388 100644 --- a/Source/cmMacroCommand.h +++ b/Source/cmMacroCommand.h @@ -19,10 +19,10 @@ class cmMacroFunctionBlocker : public cmFunctionBlocker { public: cmMacroFunctionBlocker() { this->Depth = 0; } - ~cmMacroFunctionBlocker() CM_OVERRIDE {} + ~cmMacroFunctionBlocker() override {} bool IsFunctionBlocked(const cmListFileFunction&, cmMakefile& mf, - cmExecutionStatus&) CM_OVERRIDE; - bool ShouldRemove(const cmListFileFunction&, cmMakefile& mf) CM_OVERRIDE; + cmExecutionStatus&) override; + bool ShouldRemove(const cmListFileFunction&, cmMakefile& mf) override; std::vector<std::string> Args; std::vector<cmListFileFunction> Functions; @@ -36,14 +36,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmMacroCommand; } + cmCommand* Clone() override { return new cmMacroCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmMakeDirectoryCommand.h b/Source/cmMakeDirectoryCommand.h index 214cf92..d2637f3 100644 --- a/Source/cmMakeDirectoryCommand.h +++ b/Source/cmMakeDirectoryCommand.h @@ -27,14 +27,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmMakeDirectoryCommand; } + cmCommand* Clone() override { return new cmMakeDirectoryCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmMakefile.cxx b/Source/cmMakefile.cxx index 230c210..32181cf 100644 --- a/Source/cmMakefile.cxx +++ b/Source/cmMakefile.cxx @@ -7,6 +7,7 @@ #include <algorithm> #include <assert.h> #include <ctype.h> +#include <memory> // IWYU pragma: keep #include <sstream> #include <stdlib.h> #include <string.h> @@ -37,7 +38,6 @@ #include "cmTestGenerator.h" // IWYU pragma: keep #include "cmVersion.h" #include "cmWorkingDirectory.h" -#include "cm_auto_ptr.hxx" #include "cm_sys_stat.h" #include "cmake.h" @@ -206,15 +206,13 @@ void cmMakefile::PrintCommandTrace(const cmListFileFunction& lff) const msg << lff.Name << "("; bool expand = this->GetCMakeInstance()->GetTraceExpand(); std::string temp; - for (std::vector<cmListFileArgument>::const_iterator i = - lff.Arguments.begin(); - i != lff.Arguments.end(); ++i) { + for (cmListFileArgument const& arg : lff.Arguments) { if (expand) { - temp = i->Value; + temp = arg.Value; this->ExpandVariablesInString(temp); msg << temp; } else { - msg << i->Value; + msg << arg.Value; } msg << " "; } @@ -266,7 +264,7 @@ bool cmMakefile::ExecuteCommand(const cmListFileFunction& lff, // Lookup the command prototype. if (cmCommand* proto = this->GetState()->GetCommand(name)) { // Clone the prototype. - CM_AUTO_PTR<cmCommand> pcmd(proto->Clone()); + std::unique_ptr<cmCommand> pcmd(proto->Clone()); pcmd->SetMakefile(this); // Decide whether to invoke the command. @@ -586,11 +584,12 @@ void cmMakefile::EnforceDirectoryLevelRules() const void cmMakefile::AddEvaluationFile( const std::string& inputFile, - CM_AUTO_PTR<cmCompiledGeneratorExpression> outputName, - CM_AUTO_PTR<cmCompiledGeneratorExpression> condition, bool inputIsContent) + std::unique_ptr<cmCompiledGeneratorExpression> outputName, + std::unique_ptr<cmCompiledGeneratorExpression> condition, + bool inputIsContent) { this->EvaluationFiles.push_back(new cmGeneratorExpressionEvaluationFile( - inputFile, outputName, condition, inputIsContent, + inputFile, std::move(outputName), std::move(condition), inputIsContent, this->GetPolicyStatus(cmPolicies::CMP0070))); } @@ -640,9 +639,8 @@ void cmMakefile::FinalPass() // give all the commands a chance to do something // after the file has been parsed before generation - for (std::vector<cmCommand*>::iterator i = this->FinalPassCommands.begin(); - i != this->FinalPassCommands.end(); ++i) { - (*i)->FinalPass(); + for (cmCommand* fpCommand : this->FinalPassCommands) { + fpCommand->FinalPass(); } // go through all configured files and see which ones still exist. @@ -739,9 +737,8 @@ void cmMakefile::AddCustomCommandToTarget( } // Always create the byproduct sources and mark them generated. - for (std::vector<std::string>::const_iterator o = byproducts.begin(); - o != byproducts.end(); ++o) { - if (cmSourceFile* out = this->GetOrCreateSource(*o, true)) { + for (std::string const& o : byproducts) { + if (cmSourceFile* out = this->GetOrCreateSource(o, true)) { out->SetProperty("GENERATED", "1"); } } @@ -783,9 +780,7 @@ cmSourceFile* cmMakefile::AddCustomCommandToOutput( } // Validate custom commands. TODO: More strict? - for (cmCustomCommandLines::const_iterator i = commandLines.begin(); - i != commandLines.end(); ++i) { - cmCustomCommandLine const& cl = *i; + for (cmCustomCommandLine const& cl : commandLines) { if (!cl.empty() && !cl[0].empty() && cl[0][0] == '"') { std::ostringstream e; e << "COMMAND may not contain literal quotes:\n " << cl[0] << "\n"; @@ -842,15 +837,13 @@ cmSourceFile* cmMakefile::AddCustomCommandToOutput( } // Always create the output sources and mark them generated. - for (std::vector<std::string>::const_iterator o = outputs.begin(); - o != outputs.end(); ++o) { - if (cmSourceFile* out = this->GetOrCreateSource(*o, true)) { + for (std::string const& o : outputs) { + if (cmSourceFile* out = this->GetOrCreateSource(o, true)) { out->SetProperty("GENERATED", "1"); } } - for (std::vector<std::string>::const_iterator o = byproducts.begin(); - o != byproducts.end(); ++o) { - if (cmSourceFile* out = this->GetOrCreateSource(*o, true)) { + for (std::string const& o : byproducts) { + if (cmSourceFile* out = this->GetOrCreateSource(o, true)) { out->SetProperty("GENERATED", "1"); } } @@ -879,9 +872,8 @@ cmSourceFile* cmMakefile::AddCustomCommandToOutput( void cmMakefile::UpdateOutputToSourceMap( std::vector<std::string> const& outputs, cmSourceFile* source) { - for (std::vector<std::string>::const_iterator o = outputs.begin(); - o != outputs.end(); ++o) { - this->UpdateOutputToSourceMap(*o, source); + for (std::string const& o : outputs) { + this->UpdateOutputToSourceMap(o, source); } } @@ -941,10 +933,9 @@ void cmMakefile::AddCustomCommandOldStyle( cmsys::RegularExpression sourceFiles("\\.(C|M|c|c\\+\\+|cc|cpp|cxx|m|mm|" "rc|def|r|odl|idl|hpj|bat|h|h\\+\\+|" "hm|hpp|hxx|in|txx|inl)$"); - for (std::vector<std::string>::const_iterator oi = outputs.begin(); - oi != outputs.end(); ++oi) { + for (std::string const& oi : outputs) { // Get the name of this output. - const char* output = oi->c_str(); + const char* output = oi.c_str(); cmSourceFile* sf; // Choose whether to use a main dependency. @@ -1062,9 +1053,8 @@ cmTarget* cmMakefile::AddUtilityCommand( } // Always create the byproduct sources and mark them generated. - for (std::vector<std::string>::const_iterator o = byproducts.begin(); - o != byproducts.end(); ++o) { - if (cmSourceFile* out = this->GetOrCreateSource(*o, true)) { + for (std::string const& byproduct : byproducts) { + if (cmSourceFile* out = this->GetOrCreateSource(byproduct, true)) { out->SetProperty("GENERATED", "1"); } } @@ -1226,10 +1216,9 @@ void cmMakefile::InitializeFromParent(cmMakefile* parent) parent->GetProperty("COMPILE_DEFINITIONS")); std::vector<std::string> configs; this->GetConfigurations(configs); - for (std::vector<std::string>::const_iterator ci = configs.begin(); - ci != configs.end(); ++ci) { + for (std::string const& config : configs) { std::string defPropName = "COMPILE_DEFINITIONS_"; - defPropName += cmSystemTools::UpperCase(*ci); + defPropName += cmSystemTools::UpperCase(config); const char* prop = parent->GetProperty(defPropName); this->SetProperty(defPropName, prop); } @@ -1391,10 +1380,8 @@ void cmMakefile::Configure() if (this->IsRootMakefile()) { bool hasVersion = false; // search for the right policy command - for (std::vector<cmListFileFunction>::iterator i = - listFile.Functions.begin(); - i != listFile.Functions.end(); ++i) { - if (cmSystemTools::LowerCase(i->Name) == "cmake_minimum_required") { + for (cmListFileFunction const& func : listFile.Functions) { + if (cmSystemTools::LowerCase(func.Name) == "cmake_minimum_required") { hasVersion = true; break; } @@ -1420,10 +1407,8 @@ void cmMakefile::Configure() allowedCommands.insert("option"); allowedCommands.insert("message"); isProblem = false; - for (std::vector<cmListFileFunction>::iterator i = - listFile.Functions.begin(); - i != listFile.Functions.end(); ++i) { - std::string name = cmSystemTools::LowerCase(i->Name); + for (cmListFileFunction const& func : listFile.Functions) { + std::string name = cmSystemTools::LowerCase(func.Name); if (allowedCommands.find(name) == allowedCommands.end()) { isProblem = true; break; @@ -1442,10 +1427,8 @@ void cmMakefile::Configure() } bool hasProject = false; // search for a project command - for (std::vector<cmListFileFunction>::iterator i = - listFile.Functions.begin(); - i != listFile.Functions.end(); ++i) { - if (cmSystemTools::LowerCase(i->Name) == "project") { + for (cmListFileFunction const& func : listFile.Functions) { + if (cmSystemTools::LowerCase(func.Name) == "project") { hasProject = true; break; } @@ -1577,9 +1560,8 @@ std::vector<cmTarget*> cmMakefile::GetImportedTargets() const { std::vector<cmTarget*> tgts; tgts.reserve(this->ImportedTargets.size()); - for (TargetMap::const_iterator it = this->ImportedTargets.begin(); - it != this->ImportedTargets.end(); ++it) { - tgts.push_back(it->second); + for (auto const& impTarget : this->ImportedTargets) { + tgts.push_back(impTarget.second); } return tgts; } @@ -1602,9 +1584,8 @@ void cmMakefile::AddIncludeDirectories(const std::vector<std::string>& incs, } // Property on each target: - for (cmTargets::iterator l = this->Targets.begin(); l != this->Targets.end(); - ++l) { - cmTarget& t = l->second; + for (auto& target : this->Targets) { + cmTarget& t = target.second; t.InsertInclude(entryString, lfbt, before); } } @@ -1617,9 +1598,8 @@ void cmMakefile::AddSystemIncludeDirectories(const std::set<std::string>& incs) this->SystemIncludeDirectories.insert(incs.begin(), incs.end()); - for (cmTargets::iterator l = this->Targets.begin(); l != this->Targets.end(); - ++l) { - cmTarget& t = l->second; + for (auto& target : this->Targets) { + cmTarget& t = target.second; t.AddSystemIncludeDirectories(incs); } } @@ -1666,7 +1646,7 @@ void cmMakefile::AddCacheDefinition(const std::string& name, const char* value, nvalue = value ? value : ""; cmSystemTools::ExpandListArgument(nvalue, files); - nvalue = ""; + nvalue.clear(); for (cc = 0; cc < files.size(); cc++) { if (!cmSystemTools::IsOff(files[cc].c_str())) { files[cc] = cmSystemTools::CollapseFullPath(files[cc]); @@ -1788,14 +1768,13 @@ void cmMakefile::AddGlobalLinkInformation(cmTarget& target) std::vector<std::string> linkDirs; cmSystemTools::ExpandListArgument(linkDirsProp, linkDirs); - for (std::vector<std::string>::iterator j = linkDirs.begin(); - j != linkDirs.end(); ++j) { - std::string newdir = *j; + for (std::string const& linkDir : linkDirs) { + std::string newdir = linkDir; // remove trailing slashes - if (*j->rbegin() == '/') { - newdir = j->substr(0, j->size() - 1); + if (*linkDir.rbegin() == '/') { + newdir = linkDir.substr(0, linkDir.size() - 1); } - target.AddLinkDirectory(*j); + target.AddLinkDirectory(linkDir); } } @@ -1888,22 +1867,19 @@ cmSourceFile* cmMakefile::LinearGetSourceFileWithOutput( // look through all the source files that have custom commands // and see if the custom command has the passed source file as an output - for (std::vector<cmSourceFile*>::const_iterator i = - this->SourceFiles.begin(); - i != this->SourceFiles.end(); ++i) { + for (cmSourceFile* src : this->SourceFiles) { // does this source file have a custom command? - if ((*i)->GetCustomCommand()) { + if (src->GetCustomCommand()) { // Does the output of the custom command match the source file name? const std::vector<std::string>& outputs = - (*i)->GetCustomCommand()->GetOutputs(); - for (std::vector<std::string>::const_iterator o = outputs.begin(); - o != outputs.end(); ++o) { - out = *o; + src->GetCustomCommand()->GetOutputs(); + for (std::string const& output : outputs) { + out = output; std::string::size_type pos = out.rfind(name); // If the output matches exactly if (pos != std::string::npos && pos == out.size() - name.size() && (pos == 0 || out[pos - 1] == '/')) { - return *i; + return src; } } } @@ -1936,12 +1912,10 @@ cmSourceGroup* cmMakefile::GetSourceGroup( cmSourceGroup* sg = nullptr; // first look for source group starting with the same as the one we want - for (std::vector<cmSourceGroup>::const_iterator sgIt = - this->SourceGroups.begin(); - sgIt != this->SourceGroups.end(); ++sgIt) { - std::string sgName = sgIt->GetName(); + for (cmSourceGroup const& srcGroup : this->SourceGroups) { + std::string sgName = srcGroup.GetName(); if (sgName == name[0]) { - sg = const_cast<cmSourceGroup*>(&(*sgIt)); + sg = const_cast<cmSourceGroup*>(&srcGroup); break; } } @@ -2010,6 +1984,58 @@ void cmMakefile::AddSourceGroup(const std::vector<std::string>& name, sg->SetGroupRegex(regex); } +cmSourceGroup* cmMakefile::GetOrCreateSourceGroup( + const std::vector<std::string>& folders) +{ + cmSourceGroup* sg = this->GetSourceGroup(folders); + if (sg == nullptr) { + this->AddSourceGroup(folders); + sg = this->GetSourceGroup(folders); + } + return sg; +} + +cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(const std::string& name) +{ + const char* delimiter = this->GetDefinition("SOURCE_GROUP_DELIMITER"); + if (delimiter == nullptr) { + delimiter = "\\"; + } + return this->GetOrCreateSourceGroup( + cmSystemTools::tokenize(name, delimiter)); +} + +/** + * Find a source group whose regular expression matches the filename + * part of the given source name. Search backward through the list of + * source groups, and take the first matching group found. This way + * non-inherited SOURCE_GROUP commands will have precedence over + * inherited ones. + */ +cmSourceGroup* cmMakefile::FindSourceGroup( + const char* source, std::vector<cmSourceGroup>& groups) const +{ + // First search for a group that lists the file explicitly. + for (std::vector<cmSourceGroup>::reverse_iterator sg = groups.rbegin(); + sg != groups.rend(); ++sg) { + cmSourceGroup* result = sg->MatchChildrenFiles(source); + if (result) { + return result; + } + } + + // Now search for a group whose regex matches the file. + for (std::vector<cmSourceGroup>::reverse_iterator sg = groups.rbegin(); + sg != groups.rend(); ++sg) { + cmSourceGroup* result = sg->MatchChildrenRegex(source); + if (result) { + return result; + } + } + + // Shouldn't get here, but just in case, return the default group. + return &groups.front(); +} #endif static bool mightExpandVariablesCMP0019(const char* s) @@ -2042,9 +2068,8 @@ void cmMakefile::ExpandVariablesCMP0019() } // Also for each target's INCLUDE_DIRECTORIES property: - for (cmTargets::iterator l = this->Targets.begin(); l != this->Targets.end(); - ++l) { - cmTarget& t = l->second; + for (auto& target : this->Targets) { + cmTarget& t = target.second; if (t.GetType() == cmStateEnums::INTERFACE_LIBRARY || t.GetType() == cmStateEnums::GLOBAL_TARGET) { continue; @@ -2191,9 +2216,9 @@ bool cmMakefile::PlatformIsAppleIos() const "iphonesimulator", "watchos", "watchsimulator", }; - for (size_t i = 0; i < sizeof(embedded) / sizeof(embedded[0]); ++i) { - if (sdkRoot.find(embedded[i]) == 0 || - sdkRoot.find(std::string("/") + embedded[i]) != std::string::npos) { + for (std::string const& i : embedded) { + if (sdkRoot.find(i) == 0 || + sdkRoot.find(std::string("/") + i) != std::string::npos) { return true; } } @@ -2424,7 +2449,7 @@ cmake::MessageType cmMakefile::ExpandVariablesInStringOld( std::string input = source; // Start with empty output. - source = ""; + source.clear(); // Look for one @VAR@ at a time. const char* in = input.c_str(); @@ -2818,40 +2843,6 @@ std::string cmMakefile::GetConfigurations(std::vector<std::string>& configs, return buildType; } -#if defined(CMAKE_BUILD_WITH_CMAKE) -/** - * Find a source group whose regular expression matches the filename - * part of the given source name. Search backward through the list of - * source groups, and take the first matching group found. This way - * non-inherited SOURCE_GROUP commands will have precedence over - * inherited ones. - */ -cmSourceGroup* cmMakefile::FindSourceGroup( - const char* source, std::vector<cmSourceGroup>& groups) const -{ - // First search for a group that lists the file explicitly. - for (std::vector<cmSourceGroup>::reverse_iterator sg = groups.rbegin(); - sg != groups.rend(); ++sg) { - cmSourceGroup* result = sg->MatchChildrenFiles(source); - if (result) { - return result; - } - } - - // Now search for a group whose regex matches the file. - for (std::vector<cmSourceGroup>::reverse_iterator sg = groups.rbegin(); - sg != groups.rend(); ++sg) { - cmSourceGroup* result = sg->MatchChildrenRegex(source); - if (result) { - return result; - } - } - - // Shouldn't get here, but just in case, return the default group. - return &groups.front(); -} -#endif - bool cmMakefile::IsFunctionBlocked(const cmListFileFunction& lff, cmExecutionStatus& status) { @@ -2884,7 +2875,7 @@ void cmMakefile::PopFunctionBlockerBarrier(bool reportError) FunctionBlockersType::size_type barrier = this->FunctionBlockerBarriers.back(); while (this->FunctionBlockers.size() > barrier) { - CM_AUTO_PTR<cmFunctionBlocker> fb(this->FunctionBlockers.back()); + std::unique_ptr<cmFunctionBlocker> fb(this->FunctionBlockers.back()); this->FunctionBlockers.pop_back(); if (reportError) { // Report the context in which the unclosed block was opened. @@ -2949,23 +2940,22 @@ bool cmMakefile::ExpandArguments(std::vector<cmListFileArgument> const& inArgs, if (!filename) { filename = efp.c_str(); } - std::vector<cmListFileArgument>::const_iterator i; std::string value; outArgs.reserve(inArgs.size()); - for (i = inArgs.begin(); i != inArgs.end(); ++i) { + for (cmListFileArgument const& i : inArgs) { // No expansion in a bracket argument. - if (i->Delim == cmListFileArgument::Bracket) { - outArgs.push_back(i->Value); + if (i.Delim == cmListFileArgument::Bracket) { + outArgs.push_back(i.Value); continue; } // Expand the variables in the argument. - value = i->Value; - this->ExpandVariablesInString(value, false, false, false, filename, - i->Line, false, false); + value = i.Value; + this->ExpandVariablesInString(value, false, false, false, filename, i.Line, + false, false); // If the argument is quoted, it should be one argument. // Otherwise, it may be a list of arguments. - if (i->Delim == cmListFileArgument::Quoted) { + if (i.Delim == cmListFileArgument::Quoted) { outArgs.push_back(value); } else { cmSystemTools::ExpandListArgument(value, outArgs); @@ -2982,29 +2972,28 @@ bool cmMakefile::ExpandArguments( if (!filename) { filename = efp.c_str(); } - std::vector<cmListFileArgument>::const_iterator i; std::string value; outArgs.reserve(inArgs.size()); - for (i = inArgs.begin(); i != inArgs.end(); ++i) { + for (cmListFileArgument const& i : inArgs) { // No expansion in a bracket argument. - if (i->Delim == cmListFileArgument::Bracket) { - outArgs.push_back(cmExpandedCommandArgument(i->Value, true)); + if (i.Delim == cmListFileArgument::Bracket) { + outArgs.push_back(cmExpandedCommandArgument(i.Value, true)); continue; } // Expand the variables in the argument. - value = i->Value; - this->ExpandVariablesInString(value, false, false, false, filename, - i->Line, false, false); + value = i.Value; + this->ExpandVariablesInString(value, false, false, false, filename, i.Line, + false, false); // If the argument is quoted, it should be one argument. // Otherwise, it may be a list of arguments. - if (i->Delim == cmListFileArgument::Quoted) { + if (i.Delim == cmListFileArgument::Quoted) { outArgs.push_back(cmExpandedCommandArgument(value, true)); } else { std::vector<std::string> stringArgs; cmSystemTools::ExpandListArgument(value, stringArgs); - for (size_t j = 0; j < stringArgs.size(); ++j) { - outArgs.push_back(cmExpandedCommandArgument(stringArgs[j], false)); + for (std::string const& stringArg : stringArgs) { + outArgs.push_back(cmExpandedCommandArgument(stringArg, false)); } } } @@ -3021,7 +3010,7 @@ void cmMakefile::AddFunctionBlocker(cmFunctionBlocker* fb) this->FunctionBlockers.push_back(fb); } -CM_AUTO_PTR<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker( +std::unique_ptr<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker( cmFunctionBlocker* fb, const cmListFileFunction& lff) { // Find the function blocker stack barrier for the current scope. @@ -3054,11 +3043,11 @@ CM_AUTO_PTR<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker( } cmFunctionBlocker* b = *pos; this->FunctionBlockers.erase(pos); - return CM_AUTO_PTR<cmFunctionBlocker>(b); + return std::unique_ptr<cmFunctionBlocker>(b); } } - return CM_AUTO_PTR<cmFunctionBlocker>(); + return std::unique_ptr<cmFunctionBlocker>(); } const char* cmMakefile::GetHomeDirectory() const @@ -3094,10 +3083,7 @@ void cmMakefile::SetArgcArgv(const std::vector<std::string>& args) cmSourceFile* cmMakefile::GetSource(const std::string& sourceName) const { cmSourceFileLocation sfl(this, sourceName); - for (std::vector<cmSourceFile*>::const_iterator sfi = - this->SourceFiles.begin(); - sfi != this->SourceFiles.end(); ++sfi) { - cmSourceFile* sf = *sfi; + for (cmSourceFile* sf : this->SourceFiles) { if (sf->Matches(sfl)) { return sf; } @@ -3148,12 +3134,11 @@ void cmMakefile::EnableLanguage(std::vector<std::string> const& lang, std::vector<std::string> langs; std::vector<std::string> langsRC; langs.reserve(lang.size()); - for (std::vector<std::string>::const_iterator i = lang.begin(); - i != lang.end(); ++i) { - if (*i == "RC") { - langsRC.push_back(*i); + for (std::string const& i : lang) { + if (i == "RC") { + langsRC.push_back(i); } else { - langs.push_back(*i); + langs.push_back(i); } } if (!langs.empty()) { @@ -3347,9 +3332,7 @@ std::string cmMakefile::GetModulesFile(const char* filename) const cmSystemTools::ExpandListArgument(cmakeModulePath, modulePath); // Look through the possible module directories. - for (std::vector<std::string>::iterator i = modulePath.begin(); - i != modulePath.end(); ++i) { - std::string itempl = *i; + for (std::string itempl : modulePath) { cmSystemTools::ConvertToUnixSlashes(itempl); itempl += "/"; itempl += filename; @@ -3366,7 +3349,7 @@ std::string cmMakefile::GetModulesFile(const char* filename) const moduleInCMakeRoot += filename; cmSystemTools::ConvertToUnixSlashes(moduleInCMakeRoot); if (!cmSystemTools::FileExists(moduleInCMakeRoot.c_str())) { - moduleInCMakeRoot = ""; + moduleInCMakeRoot.clear(); } // Normally, prefer the files found in CMAKE_MODULE_PATH. Only when the file @@ -3550,7 +3533,7 @@ int cmMakefile::ConfigureFile(const char* infile, const char* outfile, std::string inLine; std::string outLine; while (cmSystemTools::GetLineFromStream(fin, inLine)) { - outLine = ""; + outLine.clear(); this->ConfigureString(inLine, outLine, atOnly, escapeQuotes); fout << outLine << newLineCharacters; } @@ -3639,14 +3622,13 @@ void cmMakefile::AddCMakeDependFilesFromUser() if (const char* deps_str = this->GetProperty("CMAKE_CONFIGURE_DEPENDS")) { cmSystemTools::ExpandListArgument(deps_str, deps); } - for (std::vector<std::string>::iterator i = deps.begin(); i != deps.end(); - ++i) { - if (cmSystemTools::FileIsFullPath(i->c_str())) { - this->AddCMakeDependFile(*i); + for (std::string const& dep : deps) { + if (cmSystemTools::FileIsFullPath(dep.c_str())) { + this->AddCMakeDependFile(dep); } else { std::string f = this->GetCurrentSourceDirectory(); f += "/"; - f += *i; + f += dep; this->AddCMakeDependFile(f); } } @@ -3722,7 +3704,7 @@ cmTarget* cmMakefile::AddImportedTarget(const std::string& name, bool global) { // Create the target. - CM_AUTO_PTR<cmTarget> target( + std::unique_ptr<cmTarget> target( new cmTarget(name, type, global ? cmTarget::VisibilityImportedGlobally : cmTarget::VisibilityImported, this)); diff --git a/Source/cmMakefile.h b/Source/cmMakefile.h index 938b61b..0273f5b 100644 --- a/Source/cmMakefile.h +++ b/Source/cmMakefile.h @@ -8,6 +8,7 @@ #include "cmsys/RegularExpression.hxx" #include <deque> #include <map> +#include <memory> // IWYU pragma: keep #include <set> #include <stack> #include <stddef.h> @@ -22,7 +23,6 @@ #include "cmStateSnapshot.h" #include "cmStateTypes.h" #include "cmTarget.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" #if defined(CMAKE_BUILD_WITH_CMAKE) @@ -92,7 +92,7 @@ public: * Remove the function blocker whose scope ends with the given command. * This returns ownership of the function blocker object. */ - CM_AUTO_PTR<cmFunctionBlocker> RemoveFunctionBlocker( + std::unique_ptr<cmFunctionBlocker> RemoveFunctionBlocker( cmFunctionBlocker* fb, const cmListFileFunction& lff); /** @@ -270,21 +270,6 @@ public: bool excludeFromAll = false); void AddAlias(const std::string& libname, const std::string& tgt); -#if defined(CMAKE_BUILD_WITH_CMAKE) - /** - * Add a root source group for consideration when adding a new source. - */ - void AddSourceGroup(const std::string& name, const char* regex = nullptr); - - /** - * Add a source group for consideration when adding a new source. - * name is tokenized. - */ - void AddSourceGroup(const std::vector<std::string>& name, - const char* regex = nullptr); - -#endif - //@{ /** * Set, Push, Pop policy values for CMake. @@ -476,6 +461,36 @@ public: * Get the source group */ cmSourceGroup* GetSourceGroup(const std::vector<std::string>& name) const; + + /** + * Add a root source group for consideration when adding a new source. + */ + void AddSourceGroup(const std::string& name, const char* regex = nullptr); + + /** + * Add a source group for consideration when adding a new source. + * name is tokenized. + */ + void AddSourceGroup(const std::vector<std::string>& name, + const char* regex = nullptr); + + /** + * Get and existing or create a new source group. + */ + cmSourceGroup* GetOrCreateSourceGroup( + const std::vector<std::string>& folders); + + /** + * Get and existing or create a new source group. + * The name will be tokenized. + */ + cmSourceGroup* GetOrCreateSourceGroup(const std::string& name); + + /** + * find what source group this source is in + */ + cmSourceGroup* FindSourceGroup(const char* source, + std::vector<cmSourceGroup>& groups) const; #endif /** @@ -552,14 +567,6 @@ public: bool atOnly, bool escapeQuotes, cmNewLineStyle = cmNewLineStyle()); -#if defined(CMAKE_BUILD_WITH_CMAKE) - /** - * find what source group this source is in - */ - cmSourceGroup* FindSourceGroup(const char* source, - std::vector<cmSourceGroup>& groups) const; -#endif - /** * Print a command's invocation */ @@ -616,7 +623,6 @@ public: { return this->SourceFiles; } - std::vector<cmSourceFile*>& GetSourceFiles() { return this->SourceFiles; } /** * Is there a source file that has the provided source file as an output? @@ -775,10 +781,11 @@ public: void EnforceDirectoryLevelRules() const; - void AddEvaluationFile(const std::string& inputFile, - CM_AUTO_PTR<cmCompiledGeneratorExpression> outputName, - CM_AUTO_PTR<cmCompiledGeneratorExpression> condition, - bool inputIsContent); + void AddEvaluationFile( + const std::string& inputFile, + std::unique_ptr<cmCompiledGeneratorExpression> outputName, + std::unique_ptr<cmCompiledGeneratorExpression> condition, + bool inputIsContent); std::vector<cmGeneratorExpressionEvaluationFile*> GetEvaluationFiles() const; std::vector<cmExportBuildFileGenerator*> GetExportBuildFileGenerators() diff --git a/Source/cmMakefileExecutableTargetGenerator.cxx b/Source/cmMakefileExecutableTargetGenerator.cxx index b9b3c2f..801f72a 100644 --- a/Source/cmMakefileExecutableTargetGenerator.cxx +++ b/Source/cmMakefileExecutableTargetGenerator.cxx @@ -3,6 +3,7 @@ #include "cmMakefileExecutableTargetGenerator.h" #include <algorithm> +#include <memory> // IWYU pragma: keep #include <sstream> #include <string> #include <vector> @@ -23,7 +24,6 @@ #include "cmStateSnapshot.h" #include "cmStateTypes.h" #include "cmSystemTools.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" cmMakefileExecutableTargetGenerator::cmMakefileExecutableTargetGenerator( @@ -193,7 +193,7 @@ void cmMakefileExecutableTargetGenerator::WriteDeviceExecutableRule( // Set path conversion for link script shells. this->LocalGenerator->SetLinkScriptShell(useLinkScript); - CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer( + std::unique_ptr<cmLinkLineComputer> linkLineComputer( new cmLinkLineDeviceComputer( this->LocalGenerator, this->LocalGenerator->GetStateSnapshot().GetDirectory())); @@ -251,16 +251,15 @@ void cmMakefileExecutableTargetGenerator::WriteDeviceExecutableRule( launcher += " "; } - CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander( + std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( this->LocalGenerator->CreateRulePlaceholderExpander()); // Expand placeholders in the commands. rulePlaceholderExpander->SetTargetImpLib(targetOutputReal); - for (std::vector<std::string>::iterator i = real_link_commands.begin(); - i != real_link_commands.end(); ++i) { - *i = launcher + *i; - rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, *i, - vars); + for (std::string& real_link_command : real_link_commands) { + real_link_command = launcher + real_link_command; + rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, + real_link_command, vars); } // Restore path conversion to normal shells. @@ -449,7 +448,7 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) linkFlags, this->GeneratorTarget->GetProperty(linkFlagsConfig)); { - CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer( + std::unique_ptr<cmLinkLineComputer> linkLineComputer( this->CreateLinkLineComputer( this->LocalGenerator, this->LocalGenerator->GetStateSnapshot().GetDirectory())); @@ -539,7 +538,7 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) // Set path conversion for link script shells. this->LocalGenerator->SetLinkScriptShell(useLinkScript); - CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer( + std::unique_ptr<cmLinkLineComputer> linkLineComputer( this->CreateLinkLineComputer( this->LocalGenerator, this->LocalGenerator->GetStateSnapshot().GetDirectory())); @@ -619,7 +618,7 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) if (this->GeneratorTarget->GetPropertyAsBool("LINK_WHAT_YOU_USE")) { std::string cmakeCommand = this->LocalGenerator->ConvertToOutputFormat( cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL); - cmakeCommand += " -E __run_iwyu --lwyu="; + cmakeCommand += " -E __run_co_compile --lwyu="; cmakeCommand += targetOutPathReal; real_link_commands.push_back(cmakeCommand); } @@ -633,16 +632,15 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) launcher += " "; } - CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander( + std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( this->LocalGenerator->CreateRulePlaceholderExpander()); // Expand placeholders in the commands. rulePlaceholderExpander->SetTargetImpLib(targetOutPathImport); - for (std::vector<std::string>::iterator i = real_link_commands.begin(); - i != real_link_commands.end(); ++i) { - *i = launcher + *i; - rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, *i, - vars); + for (std::string& real_link_command : real_link_commands) { + real_link_command = launcher + real_link_command; + rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, + real_link_command, vars); } // Restore path conversion to normal shells. diff --git a/Source/cmMakefileExecutableTargetGenerator.h b/Source/cmMakefileExecutableTargetGenerator.h index 122e817..b9bbe86 100644 --- a/Source/cmMakefileExecutableTargetGenerator.h +++ b/Source/cmMakefileExecutableTargetGenerator.h @@ -15,11 +15,11 @@ class cmMakefileExecutableTargetGenerator : public cmMakefileTargetGenerator { public: cmMakefileExecutableTargetGenerator(cmGeneratorTarget* target); - ~cmMakefileExecutableTargetGenerator() CM_OVERRIDE; + ~cmMakefileExecutableTargetGenerator() override; /* the main entry point for this class. Writes the Makefiles associated with this target */ - void WriteRuleFiles() CM_OVERRIDE; + void WriteRuleFiles() override; protected: virtual void WriteExecutableRule(bool relink); diff --git a/Source/cmMakefileLibraryTargetGenerator.cxx b/Source/cmMakefileLibraryTargetGenerator.cxx index 2faef67..80c62d1 100644 --- a/Source/cmMakefileLibraryTargetGenerator.cxx +++ b/Source/cmMakefileLibraryTargetGenerator.cxx @@ -3,6 +3,7 @@ #include "cmMakefileLibraryTargetGenerator.h" #include <algorithm> +#include <memory> // IWYU pragma: keep #include <sstream> #include <vector> @@ -22,7 +23,6 @@ #include "cmStateSnapshot.h" #include "cmStateTypes.h" #include "cmSystemTools.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" cmMakefileLibraryTargetGenerator::cmMakefileLibraryTargetGenerator( @@ -199,7 +199,7 @@ void cmMakefileLibraryTargetGenerator::WriteSharedLibraryRules(bool relink) this->LocalGenerator->AddConfigVariableFlags( extraFlags, "CMAKE_SHARED_LINKER_FLAGS", this->ConfigName); - CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer( + std::unique_ptr<cmLinkLineComputer> linkLineComputer( this->CreateLinkLineComputer( this->LocalGenerator, this->LocalGenerator->GetStateSnapshot().GetDirectory())); @@ -248,7 +248,7 @@ void cmMakefileLibraryTargetGenerator::WriteModuleLibraryRules(bool relink) this->LocalGenerator->AddConfigVariableFlags( extraFlags, "CMAKE_MODULE_LINKER_FLAGS", this->ConfigName); - CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer( + std::unique_ptr<cmLinkLineComputer> linkLineComputer( this->CreateLinkLineComputer( this->LocalGenerator, this->LocalGenerator->GetStateSnapshot().GetDirectory())); @@ -348,7 +348,7 @@ void cmMakefileLibraryTargetGenerator::WriteDeviceLibraryRules( std::string linkLibs; if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) { - CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer( + std::unique_ptr<cmLinkLineComputer> linkLineComputer( new cmLinkLineDeviceComputer( this->LocalGenerator, this->LocalGenerator->GetStateSnapshot().GetDirectory())); @@ -410,7 +410,7 @@ void cmMakefileLibraryTargetGenerator::WriteDeviceLibraryRules( launcher += " "; } - CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander( + std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( this->LocalGenerator->CreateRulePlaceholderExpander()); // Construct the main link rule and expand placeholders. @@ -419,11 +419,10 @@ void cmMakefileLibraryTargetGenerator::WriteDeviceLibraryRules( cmSystemTools::ExpandListArgument(linkRule, real_link_commands); // Expand placeholders. - for (std::vector<std::string>::iterator i = real_link_commands.begin(); - i != real_link_commands.end(); ++i) { - *i = launcher + *i; - rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, *i, - vars); + for (std::string& real_link_command : real_link_commands) { + real_link_command = launcher + real_link_command; + rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, + real_link_command, vars); } // Restore path conversion to normal shells. this->LocalGenerator->SetLinkScriptShell(false); @@ -755,7 +754,7 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules( std::string linkLibs; if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) { - CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer( + std::unique_ptr<cmLinkLineComputer> linkLineComputer( this->CreateLinkLineComputer( this->LocalGenerator, this->LocalGenerator->GetStateSnapshot().GetDirectory())); @@ -874,7 +873,7 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules( launcher += " "; } - CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander( + std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( this->LocalGenerator->CreateRulePlaceholderExpander()); // Construct the main link rule and expand placeholders. rulePlaceholderExpander->SetTargetImpLib(targetOutPathImport); @@ -897,10 +896,8 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules( std::vector<std::string>::iterator osi = object_strings.begin(); { vars.Objects = osi->c_str(); - for (std::vector<std::string>::const_iterator i = - archiveCreateCommands.begin(); - i != archiveCreateCommands.end(); ++i) { - std::string cmd = launcher + *i; + for (std::string const& acc : archiveCreateCommands) { + std::string cmd = launcher + acc; rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, cmd, vars); real_link_commands.push_back(cmd); @@ -909,10 +906,8 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules( // Append to the archive with the other object sets. for (++osi; osi != object_strings.end(); ++osi) { vars.Objects = osi->c_str(); - for (std::vector<std::string>::const_iterator i = - archiveAppendCommands.begin(); - i != archiveAppendCommands.end(); ++i) { - std::string cmd = launcher + *i; + for (std::string const& aac : archiveAppendCommands) { + std::string cmd = launcher + aac; rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, cmd, vars); real_link_commands.push_back(cmd); @@ -920,10 +915,8 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules( } // Finish the archive. vars.Objects = ""; - for (std::vector<std::string>::const_iterator i = - archiveFinishCommands.begin(); - i != archiveFinishCommands.end(); ++i) { - std::string cmd = launcher + *i; + for (std::string const& afc : archiveFinishCommands) { + std::string cmd = launcher + afc; rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, cmd, vars); // If there is no ranlib the command will be ":". Skip it. @@ -939,17 +932,16 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules( (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY)) { std::string cmakeCommand = this->LocalGenerator->ConvertToOutputFormat( cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL); - cmakeCommand += " -E __run_iwyu --lwyu="; + cmakeCommand += " -E __run_co_compile --lwyu="; cmakeCommand += targetOutPathReal; real_link_commands.push_back(cmakeCommand); } // Expand placeholders. - for (std::vector<std::string>::iterator i = real_link_commands.begin(); - i != real_link_commands.end(); ++i) { - *i = launcher + *i; - rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, *i, - vars); + for (std::string& real_link_command : real_link_commands) { + real_link_command = launcher + real_link_command; + rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, + real_link_command, vars); } } diff --git a/Source/cmMakefileLibraryTargetGenerator.h b/Source/cmMakefileLibraryTargetGenerator.h index 307cd15..02fa029 100644 --- a/Source/cmMakefileLibraryTargetGenerator.h +++ b/Source/cmMakefileLibraryTargetGenerator.h @@ -15,11 +15,11 @@ class cmMakefileLibraryTargetGenerator : public cmMakefileTargetGenerator { public: cmMakefileLibraryTargetGenerator(cmGeneratorTarget* target); - ~cmMakefileLibraryTargetGenerator() CM_OVERRIDE; + ~cmMakefileLibraryTargetGenerator() override; /* the main entry point for this class. Writes the Makefiles associated with this target */ - void WriteRuleFiles() CM_OVERRIDE; + void WriteRuleFiles() override; protected: void WriteObjectLibraryRules(); diff --git a/Source/cmMakefileTargetGenerator.cxx b/Source/cmMakefileTargetGenerator.cxx index c1cf103..7db010c 100644 --- a/Source/cmMakefileTargetGenerator.cxx +++ b/Source/cmMakefileTargetGenerator.cxx @@ -2,6 +2,7 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmMakefileTargetGenerator.h" +#include <memory> // IWYU pragma: keep #include <sstream> #include <stdio.h> #include <utility> @@ -27,7 +28,6 @@ #include "cmStateSnapshot.h" #include "cmStateTypes.h" #include "cmSystemTools.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" cmMakefileTargetGenerator::cmMakefileTargetGenerator(cmGeneratorTarget* target) @@ -134,7 +134,7 @@ void cmMakefileTargetGenerator::WriteTargetBuildRules() if (const char* additional_clean_files = this->Makefile->GetProperty("ADDITIONAL_MAKE_CLEAN_FILES")) { cmGeneratorExpression ge; - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(additional_clean_files); cmSystemTools::ExpandListArgument( @@ -153,18 +153,16 @@ void cmMakefileTargetGenerator::WriteTargetBuildRules() this->GeneratorTarget->GetCustomCommands(customCommands, config); std::string currentBinDir = this->LocalGenerator->GetCurrentBinaryDirectory(); - for (std::vector<cmSourceFile const*>::const_iterator si = - customCommands.begin(); - si != customCommands.end(); ++si) { - cmCustomCommandGenerator ccg(*(*si)->GetCustomCommand(), this->ConfigName, + for (cmSourceFile const* sf : customCommands) { + cmCustomCommandGenerator ccg(*sf->GetCustomCommand(), this->ConfigName, this->LocalGenerator); this->GenerateCustomRuleFile(ccg); if (clean) { const std::vector<std::string>& outputs = ccg.GetOutputs(); - for (std::vector<std::string>::const_iterator o = outputs.begin(); - o != outputs.end(); ++o) { + for (std::string const& output : outputs) { this->CleanFiles.push_back( - this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir, *o)); + this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir, + output)); } } } @@ -178,18 +176,14 @@ void cmMakefileTargetGenerator::WriteTargetBuildRules() extraSources, this->MacOSXContentGenerator); std::vector<cmSourceFile const*> externalObjects; this->GeneratorTarget->GetExternalObjects(externalObjects, config); - for (std::vector<cmSourceFile const*>::const_iterator si = - externalObjects.begin(); - si != externalObjects.end(); ++si) { - this->ExternalObjects.push_back((*si)->GetFullPath()); + for (cmSourceFile const* sf : externalObjects) { + this->ExternalObjects.push_back(sf->GetFullPath()); } std::vector<cmSourceFile const*> objectSources; this->GeneratorTarget->GetObjectSources(objectSources, config); - for (std::vector<cmSourceFile const*>::const_iterator si = - objectSources.begin(); - si != objectSources.end(); ++si) { + for (cmSourceFile const* sf : objectSources) { // Generate this object file's rule file. - this->WriteObjectRuleFiles(**si); + this->WriteObjectRuleFiles(*sf); } } @@ -272,28 +266,26 @@ void cmMakefileTargetGenerator::WriteTargetLanguageFlags() languages, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")); // put the compiler in the rules.make file so that if it changes // things rebuild - for (std::set<std::string>::const_iterator l = languages.begin(); - l != languages.end(); ++l) { + for (std::string const& language : languages) { std::string compiler = "CMAKE_"; - compiler += *l; + compiler += language; compiler += "_COMPILER"; - *this->FlagFileStream << "# compile " << *l << " with " + *this->FlagFileStream << "# compile " << language << " with " << this->Makefile->GetSafeDefinition(compiler) << "\n"; } - for (std::set<std::string>::const_iterator l = languages.begin(); - l != languages.end(); ++l) { - std::string flags = this->GetFlags(*l); - std::string defines = this->GetDefines(*l); - std::string includes = this->GetIncludes(*l); + for (std::string const& language : languages) { + std::string flags = this->GetFlags(language); + std::string defines = this->GetDefines(language); + std::string includes = this->GetIncludes(language); // Escape comment characters so they do not terminate assignment. cmSystemTools::ReplaceString(flags, "#", "\\#"); cmSystemTools::ReplaceString(defines, "#", "\\#"); cmSystemTools::ReplaceString(includes, "#", "\\#"); - *this->FlagFileStream << *l << "_FLAGS = " << flags << "\n\n"; - *this->FlagFileStream << *l << "_DEFINES = " << defines << "\n\n"; - *this->FlagFileStream << *l << "_INCLUDES = " << includes << "\n\n"; + *this->FlagFileStream << language << "_FLAGS = " << flags << "\n\n"; + *this->FlagFileStream << language << "_DEFINES = " << defines << "\n\n"; + *this->FlagFileStream << language << "_INCLUDES = " << includes << "\n\n"; } } @@ -442,7 +434,7 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( // Add flags from source file properties. if (const char* cflags = source.GetProperty("COMPILE_FLAGS")) { cmGeneratorExpression ge; - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(cflags); + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(cflags); const char* evaluatedFlags = cge->Evaluate(this->LocalGenerator, config, false, this->GeneratorTarget); this->LocalGenerator->AppendFlags(flags, evaluatedFlags); @@ -578,7 +570,7 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( bool const lang_has_assembly = lang_has_preprocessor; bool const lang_can_export_cmds = lang_has_preprocessor; - CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander( + std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( this->LocalGenerator->CreateRulePlaceholderExpander()); // Construct the compile rules. @@ -637,7 +629,7 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( const char* cppcheck = this->GeneratorTarget->GetProperty(cppcheck_prop); if ((iwyu && *iwyu) || (tidy && *tidy) || (cpplint && *cpplint) || (cppcheck && *cppcheck)) { - std::string run_iwyu = "$(CMAKE_COMMAND) -E __run_iwyu"; + std::string run_iwyu = "$(CMAKE_COMMAND) -E __run_co_compile"; if (iwyu && *iwyu) { run_iwyu += " --iwyu="; run_iwyu += this->LocalGenerator->EscapeForShell(iwyu); @@ -673,10 +665,8 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( if (clauncher && *clauncher) { std::vector<std::string> launcher_cmd; cmSystemTools::ExpandListArgument(clauncher, launcher_cmd, true); - for (std::vector<std::string>::iterator i = launcher_cmd.begin(), - e = launcher_cmd.end(); - i != e; ++i) { - *i = this->LocalGenerator->EscapeForShell(*i); + for (std::string& i : launcher_cmd) { + i = this->LocalGenerator->EscapeForShell(i); } std::string const& run_launcher = cmJoin(launcher_cmd, " ") + " "; compileCommands.front().insert(0, run_launcher); @@ -694,11 +684,10 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( } // Expand placeholders in the commands. - for (std::vector<std::string>::iterator i = compileCommands.begin(); - i != compileCommands.end(); ++i) { - *i = launcher + *i; - rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, *i, - vars); + for (std::string& compileCommand : compileCommands) { + compileCommand = launcher + compileCommand; + rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, + compileCommand, vars); } // Change the command working directory to the local build tree. @@ -759,11 +748,10 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( vars.PreprocessedSource = shellObjI.c_str(); // Expand placeholders in the commands. - for (std::vector<std::string>::iterator i = preprocessCommands.begin(); - i != preprocessCommands.end(); ++i) { + for (std::string& preprocessCommand : preprocessCommands) { // no launcher for preprocessor commands - rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, - *i, vars); + rulePlaceholderExpander->ExpandRuleVariables( + this->LocalGenerator, preprocessCommand, vars); } this->LocalGenerator->CreateCDCommand( @@ -808,11 +796,10 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( vars.AssemblySource = shellObjS.c_str(); // Expand placeholders in the commands. - for (std::vector<std::string>::iterator i = assemblyCommands.begin(); - i != assemblyCommands.end(); ++i) { + for (std::string& assemblyCommand : assemblyCommands) { // no launcher for assembly commands rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, - *i, vars); + assemblyCommand, vars); } this->LocalGenerator->CreateCDCommand( @@ -880,10 +867,9 @@ void cmMakefileTargetGenerator::WriteTargetRequiresRules() // This target drives dependency generation for all object files. std::string relPath = this->LocalGenerator->GetHomeRelativeOutputPath(); std::string objTarget; - for (std::vector<std::string>::const_iterator obj = this->Objects.begin(); - obj != this->Objects.end(); ++obj) { + for (std::string const& obj : this->Objects) { objTarget = relPath; - objTarget += *obj; + objTarget += obj; objTarget += ".requires"; depends.push_back(objTarget); } @@ -1007,12 +993,10 @@ void cmMakefileTargetGenerator::WriteTargetDependRules() << "# Pairs of files generated by the same build rule.\n" << "set(CMAKE_MULTIPLE_OUTPUT_PAIRS\n"; /* clang-format on */ - for (MultipleOutputPairsType::const_iterator pi = - this->MultipleOutputPairs.begin(); - pi != this->MultipleOutputPairs.end(); ++pi) { + for (auto const& pi : this->MultipleOutputPairs) { *this->InfoFileStream - << " " << cmOutputConverter::EscapeForCMake(pi->first) << " " - << cmOutputConverter::EscapeForCMake(pi->second) << "\n"; + << " " << cmOutputConverter::EscapeForCMake(pi.first) << " " + << cmOutputConverter::EscapeForCMake(pi.second) << "\n"; } *this->InfoFileStream << " )\n\n"; } @@ -1026,9 +1010,8 @@ void cmMakefileTargetGenerator::WriteTargetDependRules() << "set(CMAKE_TARGET_LINKED_INFO_FILES\n"; /* clang-format on */ std::vector<std::string> dirs = this->GetLinkedTargetDirectories(); - for (std::vector<std::string>::iterator i = dirs.begin(); i != dirs.end(); - ++i) { - *this->InfoFileStream << " \"" << *i << "/DependInfo.cmake\"\n"; + for (std::string const& d : dirs) { + *this->InfoFileStream << " \"" << d << "/DependInfo.cmake\"\n"; } *this->InfoFileStream << " )\n"; } @@ -1126,9 +1109,8 @@ void cmMakefileTargetGenerator::DriveCustomCommands( std::vector<cmSourceFile*> sources; this->GeneratorTarget->GetSourceFiles( sources, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")); - for (std::vector<cmSourceFile*>::const_iterator source = sources.begin(); - source != sources.end(); ++source) { - if (cmCustomCommand* cc = (*source)->GetCustomCommand()) { + for (cmSourceFile* source : sources) { + if (cmCustomCommand* cc = source->GetCustomCommand()) { cmCustomCommandGenerator ccg(*cc, this->ConfigName, this->LocalGenerator); const std::vector<std::string>& outputs = ccg.GetOutputs(); @@ -1187,12 +1169,10 @@ void cmMakefileTargetGenerator::GenerateCustomRuleFile( } // Setup implicit dependency scanning. - for (cmCustomCommand::ImplicitDependsList::const_iterator idi = - ccg.GetCC().GetImplicitDepends().begin(); - idi != ccg.GetCC().GetImplicitDepends().end(); ++idi) { + for (auto const& idi : ccg.GetCC().GetImplicitDepends()) { std::string objFullPath = cmSystemTools::CollapseFullPath(outputs[0]); - std::string srcFullPath = cmSystemTools::CollapseFullPath(idi->second); - this->LocalGenerator->AddImplicitDepends(this->GeneratorTarget, idi->first, + std::string srcFullPath = cmSystemTools::CollapseFullPath(idi.second); + this->LocalGenerator->AddImplicitDepends(this->GeneratorTarget, idi.first, objFullPath.c_str(), srcFullPath.c_str()); } @@ -1225,11 +1205,10 @@ void cmMakefileTargetGenerator::WriteObjectsVariable( if (!lineContinue) { lineContinue = "\\"; } - for (std::vector<std::string>::const_iterator i = this->Objects.begin(); - i != this->Objects.end(); ++i) { + for (std::string const& obj : this->Objects) { *this->BuildFileStream << " " << lineContinue << "\n"; *this->BuildFileStream << this->LocalGenerator->ConvertToQuotedOutputPath( - i->c_str(), useWatcomQuote); + obj.c_str(), useWatcomQuote); } *this->BuildFileStream << "\n"; @@ -1246,14 +1225,12 @@ void cmMakefileTargetGenerator::WriteObjectsVariable( /* clang-format on */ std::string currentBinDir = this->LocalGenerator->GetCurrentBinaryDirectory(); - for (std::vector<std::string>::const_iterator i = - this->ExternalObjects.begin(); - i != this->ExternalObjects.end(); ++i) { + for (std::string const& obj : this->ExternalObjects) { object = - this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir, *i); + this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir, obj); *this->BuildFileStream << " " << lineContinue << "\n"; *this->BuildFileStream << this->LocalGenerator->ConvertToQuotedOutputPath( - i->c_str(), useWatcomQuote); + obj.c_str(), useWatcomQuote); } *this->BuildFileStream << "\n" << "\n"; @@ -1284,7 +1261,7 @@ public: (this->CurrentString.length() + 1 + this->NextObject.length() > this->LengthLimit)) { this->Strings.push_back(this->CurrentString); - this->CurrentString = ""; + this->CurrentString.clear(); this->Space = ""; } @@ -1323,14 +1300,11 @@ void cmMakefileTargetGenerator::WriteObjectsStrings( cmMakefileTargetGeneratorObjectStrings helper( objStrings, this->LocalGenerator, this->LocalGenerator->GetStateSnapshot().GetDirectory(), limit); - for (std::vector<std::string>::const_iterator i = this->Objects.begin(); - i != this->Objects.end(); ++i) { - helper.Feed(*i); + for (std::string const& obj : this->Objects) { + helper.Feed(obj); } - for (std::vector<std::string>::const_iterator i = - this->ExternalObjects.begin(); - i != this->ExternalObjects.end(); ++i) { - helper.Feed(*i); + for (std::string const& obj : this->ExternalObjects) { + helper.Feed(obj); } helper.Done(); } @@ -1398,10 +1372,9 @@ void cmMakefileTargetGenerator::AppendObjectDepends( // Add dependencies on the compiled object files. std::string relPath = this->LocalGenerator->GetHomeRelativeOutputPath(); std::string objTarget; - for (std::vector<std::string>::const_iterator obj = this->Objects.begin(); - obj != this->Objects.end(); ++obj) { + for (std::string const& obj : this->Objects) { objTarget = relPath; - objTarget += *obj; + objTarget += obj; depends.push_back(objTarget); } @@ -1426,19 +1399,16 @@ void cmMakefileTargetGenerator::AppendLinkDepends( if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi = this->GeneratorTarget->GetModuleDefinitionInfo( this->GetConfigName())) { - for (std::vector<cmSourceFile const*>::const_iterator i = - mdi->Sources.begin(); - i != mdi->Sources.end(); ++i) { - depends.push_back((*i)->GetFullPath()); + for (cmSourceFile const* src : mdi->Sources) { + depends.push_back(src->GetFullPath()); } } // Add a dependency on user-specified manifest files, if any. std::vector<cmSourceFile const*> manifest_srcs; this->GeneratorTarget->GetManifests(manifest_srcs, this->ConfigName); - for (std::vector<cmSourceFile const*>::iterator mi = manifest_srcs.begin(); - mi != manifest_srcs.end(); ++mi) { - depends.push_back((*mi)->GetFullPath()); + for (cmSourceFile const* manifest_src : manifest_srcs) { + depends.push_back(manifest_src->GetFullPath()); } // Add user-specified dependencies. @@ -1481,12 +1451,11 @@ void cmMakefileTargetGenerator::CreateLinkScript( linkScriptName += name; cmGeneratedFileStream linkScriptStream(linkScriptName.c_str()); linkScriptStream.SetCopyIfDifferent(true); - for (std::vector<std::string>::const_iterator cmd = link_commands.begin(); - cmd != link_commands.end(); ++cmd) { + for (std::string const& link_command : link_commands) { // Do not write out empty commands or commands beginning in the // shell no-op ":". - if (!cmd->empty() && (*cmd)[0] != ':') { - linkScriptStream << *cmd << "\n"; + if (!link_command.empty() && link_command[0] != ':') { + linkScriptStream << link_command << "\n"; } } @@ -1521,14 +1490,11 @@ bool cmMakefileTargetGenerator::CheckUseResponseFileForObjects( // actual list will likely be much shorter than this. However, in the // worst case all objects will remain as absolute paths. size_t length = 0; - for (std::vector<std::string>::const_iterator i = this->Objects.begin(); - i != this->Objects.end(); ++i) { - length += i->size() + 3; + for (std::string const& obj : this->Objects) { + length += obj.size() + 3; } - for (std::vector<std::string>::const_iterator i = - this->ExternalObjects.begin(); - i != this->ExternalObjects.end(); ++i) { - length += i->size() + 3; + for (std::string const& ext_obj : this->ExternalObjects) { + length += ext_obj.size() + 3; } // We need to guarantee room for both objects and libraries, so @@ -1751,22 +1717,17 @@ void cmMakefileTargetGenerator::GenDefFile( cmGeneratedFileStream fout(objlist_file.c_str()); if (mdi->WindowsExportAllSymbols) { - for (std::vector<std::string>::const_iterator i = this->Objects.begin(); - i != this->Objects.end(); ++i) { - if (cmHasLiteralSuffix(*i, ".obj")) { - fout << *i << "\n"; + for (std::string const& obj : this->Objects) { + if (cmHasLiteralSuffix(obj, ".obj")) { + fout << obj << "\n"; } } - for (std::vector<std::string>::const_iterator i = - this->ExternalObjects.begin(); - i != this->ExternalObjects.end(); ++i) { - fout << *i << "\n"; + for (std::string const& obj : this->ExternalObjects) { + fout << obj << "\n"; } } - for (std::vector<cmSourceFile const*>::const_iterator i = - mdi->Sources.begin(); - i != mdi->Sources.end(); ++i) { - fout << (*i)->GetFullPath() << "\n"; + for (cmSourceFile const* src : mdi->Sources) { + fout << src->GetFullPath() << "\n"; } } diff --git a/Source/cmMakefileTargetGenerator.h b/Source/cmMakefileTargetGenerator.h index e0e9580..5ab7e36 100644 --- a/Source/cmMakefileTargetGenerator.h +++ b/Source/cmMakefileTargetGenerator.h @@ -33,7 +33,7 @@ class cmMakefileTargetGenerator : public cmCommonTargetGenerator public: // constructor to set the ivars cmMakefileTargetGenerator(cmGeneratorTarget* target); - ~cmMakefileTargetGenerator() CM_OVERRIDE; + ~cmMakefileTargetGenerator() override; // construct using this factory call static cmMakefileTargetGenerator* New(cmGeneratorTarget* tgt); @@ -81,8 +81,7 @@ protected: { } - void operator()(cmSourceFile const& source, - const char* pkgloc) CM_OVERRIDE; + void operator()(cmSourceFile const& source, const char* pkgloc) override; private: cmMakefileTargetGenerator* Generator; @@ -168,8 +167,7 @@ protected: /** Add commands for generate def files */ void GenDefFile(std::vector<std::string>& real_link_commands); - void AddIncludeFlags(std::string& flags, - const std::string& lang) CM_OVERRIDE; + void AddIncludeFlags(std::string& flags, const std::string& lang) override; virtual void CloseFileStreams(); cmLocalUnixMakefileGenerator3* LocalGenerator; diff --git a/Source/cmMakefileUtilityTargetGenerator.h b/Source/cmMakefileUtilityTargetGenerator.h index 2826392..be243a7 100644 --- a/Source/cmMakefileUtilityTargetGenerator.h +++ b/Source/cmMakefileUtilityTargetGenerator.h @@ -13,11 +13,11 @@ class cmMakefileUtilityTargetGenerator : public cmMakefileTargetGenerator { public: cmMakefileUtilityTargetGenerator(cmGeneratorTarget* target); - ~cmMakefileUtilityTargetGenerator() CM_OVERRIDE; + ~cmMakefileUtilityTargetGenerator() override; /* the main entry point for this class. Writes the Makefiles associated with this target */ - void WriteRuleFiles() CM_OVERRIDE; + void WriteRuleFiles() override; protected: }; diff --git a/Source/cmMarkAsAdvancedCommand.h b/Source/cmMarkAsAdvancedCommand.h index 6c22d4c..5dd198f 100644 --- a/Source/cmMarkAsAdvancedCommand.h +++ b/Source/cmMarkAsAdvancedCommand.h @@ -23,14 +23,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmMarkAsAdvancedCommand; } + cmCommand* Clone() override { return new cmMarkAsAdvancedCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmMathCommand.h b/Source/cmMathCommand.h index bc97402..0c6c76b 100644 --- a/Source/cmMathCommand.h +++ b/Source/cmMathCommand.h @@ -19,14 +19,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmMathCommand; } + cmCommand* Clone() override { return new cmMathCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; protected: bool HandleExprCommand(std::vector<std::string> const& args); diff --git a/Source/cmMessageCommand.h b/Source/cmMessageCommand.h index 59ee458..819ebda 100644 --- a/Source/cmMessageCommand.h +++ b/Source/cmMessageCommand.h @@ -22,14 +22,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmMessageCommand; } + cmCommand* Clone() override { return new cmMessageCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmNinjaLinkLineComputer.h b/Source/cmNinjaLinkLineComputer.h index a75de05..0ed53f4 100644 --- a/Source/cmNinjaLinkLineComputer.h +++ b/Source/cmNinjaLinkLineComputer.h @@ -23,8 +23,7 @@ public: cmStateDirectory const& stateDir, cmGlobalNinjaGenerator const* gg); - std::string ConvertToLinkReference(std::string const& input) const - CM_OVERRIDE; + std::string ConvertToLinkReference(std::string const& input) const override; private: cmGlobalNinjaGenerator const* GG; diff --git a/Source/cmNinjaNormalTargetGenerator.cxx b/Source/cmNinjaNormalTargetGenerator.cxx index ddac20e..e0cc35a 100644 --- a/Source/cmNinjaNormalTargetGenerator.cxx +++ b/Source/cmNinjaNormalTargetGenerator.cxx @@ -6,11 +6,11 @@ #include <assert.h> #include <iterator> #include <map> +#include <memory> // IWYU pragma: keep #include <set> #include <sstream> #include "cmAlgorithms.h" -#include "cmCustomCommand.h" #include "cmCustomCommandGenerator.h" #include "cmGeneratedFileStream.h" #include "cmGeneratorTarget.h" @@ -30,9 +30,10 @@ #include "cmStateSnapshot.h" #include "cmStateTypes.h" #include "cmSystemTools.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" +class cmCustomCommand; + cmNinjaNormalTargetGenerator::cmNinjaNormalTargetGenerator( cmGeneratorTarget* target) : cmNinjaTargetGenerator(target) @@ -112,17 +113,14 @@ void cmNinjaNormalTargetGenerator::WriteLanguagesRules() std::vector<cmSourceFile const*> sourceFiles; this->GetGeneratorTarget()->GetObjectSources( sourceFiles, this->GetMakefile()->GetSafeDefinition("CMAKE_BUILD_TYPE")); - for (std::vector<cmSourceFile const*>::const_iterator i = - sourceFiles.begin(); - i != sourceFiles.end(); ++i) { - const std::string& lang = (*i)->GetLanguage(); + for (cmSourceFile const* sf : sourceFiles) { + std::string const lang = sf->GetLanguage(); if (!lang.empty()) { languages.insert(lang); } } - for (std::set<std::string>::const_iterator l = languages.begin(); - l != languages.end(); ++l) { - this->WriteLanguageRules(*l); + for (std::string const& language : languages) { + this->WriteLanguageRules(language); } } @@ -243,16 +241,15 @@ void cmNinjaNormalTargetGenerator::WriteDeviceLinkRule(bool useResponseFile) launcher += " "; } - CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander( + std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( this->GetLocalGenerator()->CreateRulePlaceholderExpander()); // Rule for linking library/executable. std::vector<std::string> linkCmds = this->ComputeDeviceLinkCmd(); - for (std::vector<std::string>::iterator i = linkCmds.begin(); - i != linkCmds.end(); ++i) { - *i = launcher + *i; + for (std::string& linkCmd : linkCmds) { + linkCmd = launcher + linkCmd; rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), - *i, vars); + linkCmd, vars); } // If there is no ranlib the command will be ":". Skip it. @@ -368,16 +365,15 @@ void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile) launcher += " "; } - CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander( + std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( this->GetLocalGenerator()->CreateRulePlaceholderExpander()); // Rule for linking library/executable. std::vector<std::string> linkCmds = this->ComputeLinkCmd(); - for (std::vector<std::string>::iterator i = linkCmds.begin(); - i != linkCmds.end(); ++i) { - *i = launcher + *i; + for (std::string& linkCmd : linkCmds) { + linkCmd = launcher + linkCmd; rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), - *i, vars); + linkCmd, vars); } // If there is no ranlib the command will be ":". Skip it. @@ -499,7 +495,7 @@ std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd() std::string cmakeCommand = this->GetLocalGenerator()->ConvertToOutputFormat( cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL); - cmakeCommand += " -E __run_iwyu --lwyu="; + cmakeCommand += " -E __run_co_compile --lwyu="; cmGeneratorTarget& gt = *this->GetGeneratorTarget(); const std::string cfgName = this->GetConfigName(); std::string targetOutput = ConvertToNinjaPath(gt.GetFullPath(cfgName)); @@ -640,7 +636,7 @@ void cmNinjaNormalTargetGenerator::WriteDeviceLinkStatement() vars["TARGET_FILE"] = localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL); - CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer( + std::unique_ptr<cmLinkLineComputer> linkLineComputer( new cmNinjaLinkLineDeviceComputer( this->GetLocalGenerator(), this->GetLocalGenerator()->GetStateSnapshot().GetDirectory(), @@ -671,7 +667,7 @@ void cmNinjaNormalTargetGenerator::WriteDeviceLinkStatement() std::string t = vars["ARCH_FLAGS"]; localGen.AddArchitectureFlags(t, &genTarget, cudaLinkLanguage, cfgName); vars["ARCH_FLAGS"] = t; - t = ""; + t.clear(); localGen.AddLanguageFlagsForLinking(t, &genTarget, cudaLinkLanguage, cfgName); vars["LANGUAGE_COMPILE_FLAGS"] = t; @@ -731,10 +727,8 @@ void cmNinjaNormalTargetGenerator::WriteDeviceLinkStatement() &postBuildCmdLines }; for (unsigned i = 0; i != 3; ++i) { - for (std::vector<cmCustomCommand>::const_iterator ci = - cmdLists[i]->begin(); - ci != cmdLists[i]->end(); ++ci) { - cmCustomCommandGenerator ccg(*ci, cfgName, this->GetLocalGenerator()); + for (cmCustomCommand const& cc : *cmdLists[i]) { + cmCustomCommandGenerator ccg(cc, cfgName, this->GetLocalGenerator()); localGen.AppendCustomCommandLines(ccg, *cmdLineLists[i]); std::vector<std::string> const& ccByproducts = ccg.GetByproducts(); std::transform(ccByproducts.begin(), ccByproducts.end(), @@ -845,7 +839,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement() vars["TARGET_FILE"] = localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL); - CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer( + std::unique_ptr<cmLinkLineComputer> linkLineComputer( this->GetGlobalGenerator()->CreateLinkLineComputer( this->GetLocalGenerator(), this->GetLocalGenerator()->GetStateSnapshot().GetDirectory())); @@ -890,7 +884,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement() std::string t = vars["ARCH_FLAGS"]; localGen.AddArchitectureFlags(t, &genTarget, TargetLinkLanguage, cfgName); vars["ARCH_FLAGS"] = t; - t = ""; + t.clear(); t += lwyuFlags; localGen.AddLanguageFlagsForLinking(t, &genTarget, TargetLinkLanguage, cfgName); @@ -960,10 +954,8 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement() &postBuildCmdLines }; for (unsigned i = 0; i != 3; ++i) { - for (std::vector<cmCustomCommand>::const_iterator ci = - cmdLists[i]->begin(); - ci != cmdLists[i]->end(); ++ci) { - cmCustomCommandGenerator ccg(*ci, cfgName, this->GetLocalGenerator()); + for (cmCustomCommand const& cc : *cmdLists[i]) { + cmCustomCommandGenerator ccg(cc, cfgName, this->GetLocalGenerator()); localGen.AppendCustomCommandLines(ccg, *cmdLineLists[i]); std::vector<std::string> const& ccByproducts = ccg.GetByproducts(); std::transform(ccByproducts.begin(), ccByproducts.end(), @@ -993,17 +985,15 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement() if (mdi->WindowsExportAllSymbols) { cmNinjaDeps objs = this->GetObjects(); - for (cmNinjaDeps::iterator i = objs.begin(); i != objs.end(); ++i) { - if (cmHasLiteralSuffix(*i, ".obj")) { - fout << *i << "\n"; + for (std::string const& obj : objs) { + if (cmHasLiteralSuffix(obj, ".obj")) { + fout << obj << "\n"; } } } - for (std::vector<cmSourceFile const*>::const_iterator i = - mdi->Sources.begin(); - i != mdi->Sources.end(); ++i) { - fout << (*i)->GetFullPath() << "\n"; + for (cmSourceFile const* src : mdi->Sources) { + fout << src->GetFullPath() << "\n"; } } // If we have any PRE_LINK commands, we need to go back to CMAKE_BINARY_DIR @@ -1050,11 +1040,9 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement() // Ninja should restat after linking if and only if there are byproducts. vars["RESTAT"] = byproducts.empty() ? "" : "1"; - for (cmNinjaDeps::const_iterator oi = byproducts.begin(), - oe = byproducts.end(); - oi != oe; ++oi) { - this->GetGlobalGenerator()->SeenCustomCommandOutput(*oi); - outputs.push_back(*oi); + for (std::string const& o : byproducts) { + this->GetGlobalGenerator()->SeenCustomCommandOutput(o); + outputs.push_back(o); } // Write the build statement for this target. @@ -1082,7 +1070,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement() if (targetOutputReal == soName || targetOutput == soName) { symlinkVars["SONAME"] = soName; } else { - symlinkVars["SONAME"] = ""; + symlinkVars["SONAME"].clear(); symlinks.push_back(soName); } symlinks.push_back(targetOutput); diff --git a/Source/cmNinjaNormalTargetGenerator.h b/Source/cmNinjaNormalTargetGenerator.h index d8baa67..01cc881 100644 --- a/Source/cmNinjaNormalTargetGenerator.h +++ b/Source/cmNinjaNormalTargetGenerator.h @@ -16,9 +16,9 @@ class cmNinjaNormalTargetGenerator : public cmNinjaTargetGenerator { public: cmNinjaNormalTargetGenerator(cmGeneratorTarget* target); - ~cmNinjaNormalTargetGenerator() CM_OVERRIDE; + ~cmNinjaNormalTargetGenerator() override; - void Generate() CM_OVERRIDE; + void Generate() override; private: std::string LanguageLinkerRule() const; diff --git a/Source/cmNinjaTargetGenerator.cxx b/Source/cmNinjaTargetGenerator.cxx index b08c19b..5805259 100644 --- a/Source/cmNinjaTargetGenerator.cxx +++ b/Source/cmNinjaTargetGenerator.cxx @@ -8,6 +8,7 @@ #include <assert.h> #include <iterator> #include <map> +#include <memory> // IWYU pragma: keep #include <sstream> #include <string.h> @@ -29,7 +30,6 @@ #include "cmState.h" #include "cmStateTypes.h" #include "cmSystemTools.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" cmNinjaTargetGenerator* cmNinjaTargetGenerator::New(cmGeneratorTarget* target) @@ -138,7 +138,7 @@ std::string cmNinjaTargetGenerator::ComputeFlagsForObject( if (const char* cflags = source->GetProperty("COMPILE_FLAGS")) { std::string config = this->LocalGenerator->GetConfigName(); cmGeneratorExpression ge; - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(cflags); + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(cflags); const char* evaluatedFlags = cge->Evaluate(this->LocalGenerator, config, false, this->GeneratorTarget); this->LocalGenerator->AppendFlags(flags, evaluatedFlags); @@ -215,19 +215,16 @@ cmNinjaDeps cmNinjaTargetGenerator::ComputeLinkDeps() const if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi = this->GeneratorTarget->GetModuleDefinitionInfo( this->GetConfigName())) { - for (std::vector<cmSourceFile const*>::const_iterator i = - mdi->Sources.begin(); - i != mdi->Sources.end(); ++i) { - result.push_back(this->ConvertToNinjaPath((*i)->GetFullPath())); + for (cmSourceFile const* src : mdi->Sources) { + result.push_back(this->ConvertToNinjaPath(src->GetFullPath())); } } // Add a dependency on user-specified manifest files, if any. std::vector<cmSourceFile const*> manifest_srcs; this->GeneratorTarget->GetManifests(manifest_srcs, this->ConfigName); - for (std::vector<cmSourceFile const*>::iterator mi = manifest_srcs.begin(); - mi != manifest_srcs.end(); ++mi) { - result.push_back(this->ConvertToNinjaPath((*mi)->GetFullPath())); + for (cmSourceFile const* manifest_src : manifest_srcs) { + result.push_back(this->ConvertToNinjaPath(manifest_src->GetFullPath())); } // Add user-specified dependencies. @@ -428,7 +425,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) // The explicit preprocessing step will handle dependency scanning. } else if (this->NeedDepTypeMSVC(lang)) { deptype = "msvc"; - depfile = ""; + depfile.clear(); flags += " /showIncludes"; } else if (mf->IsOn("CMAKE_NINJA_CMCLDEPS_" + lang)) { // For the MS resource compiler we need cmcldeps, but skip dependencies @@ -441,7 +438,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) : mf->GetSafeDefinition("CMAKE_CXX_COMPILER"); cldeps = "\""; cldeps += cmSystemTools::GetCMClDepsCommand(); - cldeps += "\" " + lang + " " + vars.Source + " \"$DEP_FILE\" $out \""; + cldeps += "\" " + lang + " " + vars.Source + " $DEP_FILE $out \""; cldeps += mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX"); cldeps += "\" \"" + cl + "\" "; } @@ -466,7 +463,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) vars.Flags = flags.c_str(); vars.DependencyFile = depfile.c_str(); - CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander( + std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( this->GetLocalGenerator()->CreateRulePlaceholderExpander()); std::string const tdi = this->GetLocalGenerator()->ConvertToOutputFormat( @@ -519,11 +516,10 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) std::vector<std::string> ppCmds; cmSystemTools::ExpandListArgument(ppCmd, ppCmds); - for (std::vector<std::string>::iterator i = ppCmds.begin(); - i != ppCmds.end(); ++i) { - *i = launcher + *i; + for (std::string& i : ppCmds) { + i = launcher + i; rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), - *i, ppVars); + i, ppVars); } // Run CMake dependency scanner on preprocessed output. @@ -623,7 +619,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) (cppcheck && *cppcheck)) { std::string run_iwyu = this->GetLocalGenerator()->ConvertToOutputFormat( cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL); - run_iwyu += " -E __run_iwyu"; + run_iwyu += " -E __run_co_compile"; if (iwyu && *iwyu) { run_iwyu += " --iwyu="; run_iwyu += this->GetLocalGenerator()->EscapeForShell(iwyu); @@ -657,10 +653,8 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) if (clauncher && *clauncher) { std::vector<std::string> launcher_cmd; cmSystemTools::ExpandListArgument(clauncher, launcher_cmd, true); - for (std::vector<std::string>::iterator i = launcher_cmd.begin(), - e = launcher_cmd.end(); - i != e; ++i) { - *i = this->LocalGenerator->EscapeForShell(*i); + for (std::string& i : launcher_cmd) { + i = this->LocalGenerator->EscapeForShell(i); } std::string const& run_launcher = cmJoin(launcher_cmd, " ") + " "; compileCmds.front().insert(0, run_launcher); @@ -671,10 +665,9 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) compileCmds.front().insert(0, cldeps); } - for (std::vector<std::string>::iterator i = compileCmds.begin(); - i != compileCmds.end(); ++i) { - *i = launcher + *i; - rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), *i, + for (std::string& i : compileCmds) { + i = launcher + i; + rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i, vars); } @@ -705,10 +698,8 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatements() std::string config = this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"); std::vector<cmSourceFile const*> customCommands; this->GeneratorTarget->GetCustomCommands(customCommands, config); - for (std::vector<cmSourceFile const*>::const_iterator si = - customCommands.begin(); - si != customCommands.end(); ++si) { - cmCustomCommand const* cc = (*si)->GetCustomCommand(); + for (cmSourceFile const* sf : customCommands) { + cmCustomCommand const* cc = sf->GetCustomCommand(); this->GetLocalGenerator()->AddCustomCommandTarget( cc, this->GetGeneratorTarget()); // Record the custom commands for this target. The container is used @@ -725,10 +716,8 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatements() extraSources, this->MacOSXContentGenerator); std::vector<cmSourceFile const*> externalObjects; this->GeneratorTarget->GetExternalObjects(externalObjects, config); - for (std::vector<cmSourceFile const*>::const_iterator si = - externalObjects.begin(); - si != externalObjects.end(); ++si) { - this->Objects.push_back(this->GetSourceFilePath(*si)); + for (cmSourceFile const* sf : externalObjects) { + this->Objects.push_back(this->GetSourceFilePath(sf)); } cmNinjaDeps orderOnlyDeps; @@ -740,10 +729,7 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatements() this->ExtraFiles.end()); // Add order-only dependencies on custom command outputs. - for (std::vector<cmCustomCommand const*>::const_iterator cci = - this->CustomCommands.begin(); - cci != this->CustomCommands.end(); ++cci) { - cmCustomCommand const* cc = *cci; + for (cmCustomCommand const* cc : this->CustomCommands) { cmCustomCommandGenerator ccg(*cc, this->GetConfigName(), this->GetLocalGenerator()); const std::vector<std::string>& ccoutputs = ccg.GetOutputs(); @@ -768,10 +754,8 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatements() } std::vector<cmSourceFile const*> objectSources; this->GeneratorTarget->GetObjectSources(objectSources, config); - for (std::vector<cmSourceFile const*>::const_iterator si = - objectSources.begin(); - si != objectSources.end(); ++si) { - this->WriteObjectBuildStatement(*si); + for (cmSourceFile const* sf : objectSources) { + this->WriteObjectBuildStatement(sf); } if (!this->DDIFiles.empty()) { @@ -848,10 +832,9 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement( if (const char* objectDeps = source->GetProperty("OBJECT_DEPENDS")) { std::vector<std::string> depList; cmSystemTools::ExpandListArgument(objectDeps, depList); - for (std::vector<std::string>::iterator odi = depList.begin(); - odi != depList.end(); ++odi) { - if (cmSystemTools::FileIsFullPath(*odi)) { - *odi = cmSystemTools::CollapseFullPath(*odi); + for (std::string& odi : depList) { + if (cmSystemTools::FileIsFullPath(odi)) { + odi = cmSystemTools::CollapseFullPath(odi); } } std::transform(depList.begin(), depList.end(), @@ -1019,19 +1002,17 @@ void cmNinjaTargetGenerator::WriteTargetDependInfo(std::string const& lang) std::vector<std::string> includes; this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget, lang, this->GetConfigName()); - for (std::vector<std::string>::iterator i = includes.begin(); - i != includes.end(); ++i) { + for (std::string const& i : includes) { // Convert the include directories the same way we do for -I flags. // See upstream ninja issue 1251. - tdi_include_dirs.append(this->ConvertToNinjaPath(*i)); + tdi_include_dirs.append(this->ConvertToNinjaPath(i)); } Json::Value& tdi_linked_target_dirs = tdi["linked-target-dirs"] = Json::arrayValue; std::vector<std::string> linked = this->GetLinkedTargetDirectories(); - for (std::vector<std::string>::iterator i = linked.begin(); - i != linked.end(); ++i) { - tdi_linked_target_dirs.append(*i); + for (std::string const& l : linked) { + tdi_linked_target_dirs.append(l); } std::string const tdin = this->GetTargetDependInfoPath(lang); @@ -1096,13 +1077,12 @@ void cmNinjaTargetGenerator::ExportObjectCompileCommand( cmSystemTools::ExpandListArgument(compileCmd, compileCmds); } - CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander( + std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( this->GetLocalGenerator()->CreateRulePlaceholderExpander()); - for (std::vector<std::string>::iterator i = compileCmds.begin(); - i != compileCmds.end(); ++i) { + for (std::string& i : compileCmds) { // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS - rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), *i, + rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i, compileObjectVars); } diff --git a/Source/cmNinjaTargetGenerator.h b/Source/cmNinjaTargetGenerator.h index e15ba25..770a99d 100644 --- a/Source/cmNinjaTargetGenerator.h +++ b/Source/cmNinjaTargetGenerator.h @@ -31,7 +31,7 @@ public: cmNinjaTargetGenerator(cmGeneratorTarget* target); /// Destructor. - ~cmNinjaTargetGenerator() CM_OVERRIDE; + ~cmNinjaTargetGenerator() override; virtual void Generate() = 0; @@ -77,8 +77,7 @@ protected: std::string ComputeFlagsForObject(cmSourceFile const* source, const std::string& language); - void AddIncludeFlags(std::string& flags, - std::string const& lang) CM_OVERRIDE; + void AddIncludeFlags(std::string& flags, std::string const& lang) override; std::string ComputeDefines(cmSourceFile const* source, const std::string& language); @@ -142,8 +141,7 @@ protected: { } - void operator()(cmSourceFile const& source, - const char* pkgloc) CM_OVERRIDE; + void operator()(cmSourceFile const& source, const char* pkgloc) override; private: cmNinjaTargetGenerator* Generator; diff --git a/Source/cmNinjaTypes.h b/Source/cmNinjaTypes.h index ec435d9..9e962f1 100644 --- a/Source/cmNinjaTypes.h +++ b/Source/cmNinjaTypes.h @@ -6,6 +6,7 @@ #include "cmConfigure.h" // IWYU pragma: keep #include <map> +#include <set> #include <string> #include <vector> @@ -16,6 +17,7 @@ enum cmNinjaTargetDepends }; typedef std::vector<std::string> cmNinjaDeps; +typedef std::set<std::string> cmNinjaOuts; typedef std::map<std::string, std::string> cmNinjaVars; #endif // ! cmNinjaTypes_h diff --git a/Source/cmNinjaUtilityTargetGenerator.cxx b/Source/cmNinjaUtilityTargetGenerator.cxx index 500ff4a..7adeb8e 100644 --- a/Source/cmNinjaUtilityTargetGenerator.cxx +++ b/Source/cmNinjaUtilityTargetGenerator.cxx @@ -51,17 +51,15 @@ void cmNinjaUtilityTargetGenerator::Generate() bool uses_terminal = false; for (unsigned i = 0; i != 2; ++i) { - for (std::vector<cmCustomCommand>::const_iterator ci = - cmdLists[i]->begin(); - ci != cmdLists[i]->end(); ++ci) { - cmCustomCommandGenerator ccg(*ci, this->GetConfigName(), + for (cmCustomCommand const& ci : *cmdLists[i]) { + cmCustomCommandGenerator ccg(ci, this->GetConfigName(), this->GetLocalGenerator()); this->GetLocalGenerator()->AppendCustomCommandDeps(ccg, deps); this->GetLocalGenerator()->AppendCustomCommandLines(ccg, commands); std::vector<std::string> const& ccByproducts = ccg.GetByproducts(); std::transform(ccByproducts.begin(), ccByproducts.end(), std::back_inserter(util_outputs), MapToNinjaPath()); - if (ci->GetUsesTerminal()) { + if (ci.GetUsesTerminal()) { uses_terminal = true; } } @@ -71,9 +69,8 @@ void cmNinjaUtilityTargetGenerator::Generate() std::string config = this->GetMakefile()->GetSafeDefinition("CMAKE_BUILD_TYPE"); this->GetGeneratorTarget()->GetSourceFiles(sources, config); - for (std::vector<cmSourceFile*>::const_iterator source = sources.begin(); - source != sources.end(); ++source) { - if (cmCustomCommand* cc = (*source)->GetCustomCommand()) { + for (cmSourceFile const* source : sources) { + if (cmCustomCommand const* cc = source->GetCustomCommand()) { cmCustomCommandGenerator ccg(*cc, this->GetConfigName(), this->GetLocalGenerator()); this->GetLocalGenerator()->AddCustomCommandTarget( @@ -132,10 +129,8 @@ void cmNinjaUtilityTargetGenerator::Generate() return; } - for (cmNinjaDeps::const_iterator oi = util_outputs.begin(), - oe = util_outputs.end(); - oi != oe; ++oi) { - this->GetGlobalGenerator()->SeenCustomCommandOutput(*oi); + for (std::string const& util_output : util_outputs) { + this->GetGlobalGenerator()->SeenCustomCommandOutput(util_output); } this->GetGlobalGenerator()->WriteCustomCommandBuild( diff --git a/Source/cmNinjaUtilityTargetGenerator.h b/Source/cmNinjaUtilityTargetGenerator.h index 361befe..01cc459 100644 --- a/Source/cmNinjaUtilityTargetGenerator.h +++ b/Source/cmNinjaUtilityTargetGenerator.h @@ -13,9 +13,9 @@ class cmNinjaUtilityTargetGenerator : public cmNinjaTargetGenerator { public: cmNinjaUtilityTargetGenerator(cmGeneratorTarget* target); - ~cmNinjaUtilityTargetGenerator() CM_OVERRIDE; + ~cmNinjaUtilityTargetGenerator() override; - void Generate() CM_OVERRIDE; + void Generate() override; }; #endif // ! cmNinjaUtilityTargetGenerator_h diff --git a/Source/cmOSXBundleGenerator.cxx b/Source/cmOSXBundleGenerator.cxx index 847e3f2..c85c82d 100644 --- a/Source/cmOSXBundleGenerator.cxx +++ b/Source/cmOSXBundleGenerator.cxx @@ -195,12 +195,11 @@ void cmOSXBundleGenerator::GenerateMacOSXContentStatements( return; } - for (std::vector<cmSourceFile const*>::const_iterator si = sources.begin(); - si != sources.end(); ++si) { + for (cmSourceFile const* source : sources) { cmGeneratorTarget::SourceFileFlags tsFlags = - this->GT->GetTargetSourceFileFlags(*si); + this->GT->GetTargetSourceFileFlags(source); if (tsFlags.Type != cmGeneratorTarget::SourceFileTypeNormal) { - (*generator)(**si, tsFlags.MacFolder); + (*generator)(*source, tsFlags.MacFolder); } } } diff --git a/Source/cmOptionCommand.h b/Source/cmOptionCommand.h index d6e51a5..34e0e6f 100644 --- a/Source/cmOptionCommand.h +++ b/Source/cmOptionCommand.h @@ -23,14 +23,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmOptionCommand; } + cmCommand* Clone() override { return new cmOptionCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmOrderDirectories.cxx b/Source/cmOrderDirectories.cxx index 333e313..27ad710 100644 --- a/Source/cmOrderDirectories.cxx +++ b/Source/cmOrderDirectories.cxx @@ -75,9 +75,8 @@ public: void FindImplicitConflicts(std::ostringstream& w) { bool first = true; - for (unsigned int i = 0; i < this->OD->OriginalDirectories.size(); ++i) { + for (std::string const& dir : this->OD->OriginalDirectories) { // Check if this directory conflicts with the entry. - std::string const& dir = this->OD->OriginalDirectories[i]; if (dir != this->Directory && cmSystemTools::GetRealPath(dir) != cmSystemTools::GetRealPath(this->Directory) && @@ -150,7 +149,7 @@ public: } } - void Report(std::ostream& e) CM_OVERRIDE + void Report(std::ostream& e) override { e << "runtime library ["; if (this->SOName.empty()) { @@ -161,7 +160,7 @@ public: e << "]"; } - bool FindConflict(std::string const& dir) CM_OVERRIDE; + bool FindConflict(std::string const& dir) override; private: // The soname of the shared library if it is known. @@ -205,12 +204,12 @@ public: { } - void Report(std::ostream& e) CM_OVERRIDE + void Report(std::ostream& e) override { e << "link library [" << this->FileName << "]"; } - bool FindConflict(std::string const& dir) CM_OVERRIDE; + bool FindConflict(std::string const& dir) override; }; bool cmOrderDirectoriesConstraintLibrary::FindConflict(std::string const& dir) @@ -226,12 +225,10 @@ bool cmOrderDirectoriesConstraintLibrary::FindConflict(std::string const& dir) this->OD->RemoveLibraryExtension.find(this->FileName)) { std::string lib = this->OD->RemoveLibraryExtension.match(1); std::string ext = this->OD->RemoveLibraryExtension.match(2); - for (std::vector<std::string>::iterator i = - this->OD->LinkExtensions.begin(); - i != this->OD->LinkExtensions.end(); ++i) { - if (*i != ext) { + for (std::string const& LinkExtension : this->OD->LinkExtensions) { + if (LinkExtension != ext) { std::string fname = lib; - fname += *i; + fname += LinkExtension; if (this->FileMayConflict(dir, fname)) { return true; } @@ -346,9 +343,8 @@ void cmOrderDirectories::SetImplicitDirectories( std::set<std::string> const& implicitDirs) { this->ImplicitDirectories.clear(); - for (std::set<std::string>::const_iterator i = implicitDirs.begin(); - i != implicitDirs.end(); ++i) { - this->ImplicitDirectories.insert(this->GetRealPath(*i)); + for (std::string const& implicitDir : implicitDirs) { + this->ImplicitDirectories.insert(this->GetRealPath(implicitDir)); } } @@ -375,8 +371,8 @@ void cmOrderDirectories::CollectOriginalDirectories() this->AddOriginalDirectories(this->UserDirectories); // Add directories containing constraints. - for (unsigned int i = 0; i < this->ConstraintEntries.size(); ++i) { - this->ConstraintEntries[i]->AddDirectory(); + for (cmOrderDirectoriesConstraint* entry : this->ConstraintEntries) { + entry->AddDirectory(); } // Add language runtime directories last. @@ -400,20 +396,19 @@ int cmOrderDirectories::AddOriginalDirectory(std::string const& dir) void cmOrderDirectories::AddOriginalDirectories( std::vector<std::string> const& dirs) { - for (std::vector<std::string>::const_iterator di = dirs.begin(); - di != dirs.end(); ++di) { + for (std::string const& dir : dirs) { // We never explicitly specify implicit link directories. - if (this->IsImplicitDirectory(*di)) { + if (this->IsImplicitDirectory(dir)) { continue; } // Skip the empty string. - if (di->empty()) { + if (dir.empty()) { continue; } // Add this directory. - this->AddOriginalDirectory(*di); + this->AddOriginalDirectory(dir); } } @@ -442,16 +437,15 @@ void cmOrderDirectories::FindConflicts() } // Clean up the conflict graph representation. - for (std::vector<ConflictList>::iterator i = this->ConflictGraph.begin(); - i != this->ConflictGraph.end(); ++i) { + for (ConflictList& cl : this->ConflictGraph) { // Sort the outgoing edges for each graph node so that the // original order will be preserved as much as possible. - std::sort(i->begin(), i->end()); + std::sort(cl.begin(), cl.end()); // Make the edge list unique so cycle detection will be reliable. ConflictList::iterator last = - std::unique(i->begin(), i->end(), cmOrderDirectoriesCompare()); - i->erase(last, i->end()); + std::unique(cl.begin(), cl.end(), cmOrderDirectoriesCompare()); + cl.erase(last, cl.end()); } // Check items in implicit link directories. @@ -463,12 +457,12 @@ void cmOrderDirectories::FindImplicitConflicts() // Check for items in implicit link directories that have conflicts // in the explicit directories. std::ostringstream conflicts; - for (unsigned int i = 0; i < this->ImplicitDirEntries.size(); ++i) { - this->ImplicitDirEntries[i]->FindImplicitConflicts(conflicts); + for (cmOrderDirectoriesConstraint* entry : this->ImplicitDirEntries) { + entry->FindImplicitConflicts(conflicts); } // Skip warning if there were no conflicts. - std::string text = conflicts.str(); + std::string const text = conflicts.str(); if (text.empty()) { return; } @@ -515,8 +509,8 @@ void cmOrderDirectories::VisitDirectory(unsigned int i) // Visit the neighbors of the node first. ConflictList const& clist = this->ConflictGraph[i]; - for (ConflictList::const_iterator j = clist.begin(); j != clist.end(); ++j) { - this->VisitDirectory(j->first); + for (ConflictPair const& j : clist) { + this->VisitDirectory(j.first); } // Now that all directories required to come before this one have @@ -542,10 +536,9 @@ void cmOrderDirectories::DiagnoseCycle() for (unsigned int i = 0; i < this->ConflictGraph.size(); ++i) { ConflictList const& clist = this->ConflictGraph[i]; e << " dir " << i << " is [" << this->OriginalDirectories[i] << "]\n"; - for (ConflictList::const_iterator j = clist.begin(); j != clist.end(); - ++j) { - e << " dir " << j->first << " must precede it due to "; - this->ConstraintEntries[j->second]->Report(e); + for (ConflictPair const& j : clist) { + e << " dir " << j.first << " must precede it due to "; + this->ConstraintEntries[j.second]->Report(e); e << "\n"; } } diff --git a/Source/cmOutputConverter.cxx b/Source/cmOutputConverter.cxx index f56d212..dac6569 100644 --- a/Source/cmOutputConverter.cxx +++ b/Source/cmOutputConverter.cxx @@ -285,12 +285,11 @@ cmOutputConverter::FortranFormat cmOutputConverter::GetFortranFormat( if (value && *value) { std::vector<std::string> fmt; cmSystemTools::ExpandListArgument(value, fmt); - for (std::vector<std::string>::iterator fi = fmt.begin(); fi != fmt.end(); - ++fi) { - if (*fi == "FIXED") { + for (std::string const& fi : fmt) { + if (fi == "FIXED") { format = FortranFormatFixed; } - if (*fi == "FREE") { + if (fi == "FREE") { format = FortranFormatFree; } } diff --git a/Source/cmOutputRequiredFilesCommand.cxx b/Source/cmOutputRequiredFilesCommand.cxx index 2fd266a..cde9037 100644 --- a/Source/cmOutputRequiredFilesCommand.cxx +++ b/Source/cmOutputRequiredFilesCommand.cxx @@ -5,7 +5,6 @@ #include "cmsys/FStream.hxx" #include "cmsys/RegularExpression.hxx" #include <map> -#include <unordered_map> #include <utility> #include "cmAlgorithms.h" @@ -114,8 +113,9 @@ public: std::set<std::string> uniqueIncludes; std::vector<std::string> orderedAndUniqueIncludes; cmTargets& targets = this->Makefile->GetTargets(); - for (cmTargets::iterator l = targets.begin(); l != targets.end(); ++l) { - const char* incDirProp = l->second.GetProperty("INCLUDE_DIRECTORIES"); + for (auto const& target : targets) { + const char* incDirProp = + target.second.GetProperty("INCLUDE_DIRECTORIES"); if (!incDirProp) { continue; } @@ -126,9 +126,7 @@ public: std::vector<std::string> includes; cmSystemTools::ExpandListArgument(incDirs, includes); - for (std::vector<std::string>::const_iterator j = includes.begin(); - j != includes.end(); ++j) { - std::string path = *j; + for (std::string& path : includes) { this->Makefile->ExpandVariablesInString(path); if (uniqueIncludes.insert(path).second) { orderedAndUniqueIncludes.push_back(path); @@ -136,10 +134,8 @@ public: } } - for (std::vector<std::string>::const_iterator it = - orderedAndUniqueIncludes.begin(); - it != orderedAndUniqueIncludes.end(); ++it) { - this->AddSearchPath(*it); + for (std::string const& inc : orderedAndUniqueIncludes) { + this->AddSearchPath(inc); } } @@ -220,10 +216,7 @@ protected: if (cmSystemTools::FileExists(cxxFile.c_str())) { found = true; } - for (std::vector<std::string>::iterator i = - this->IncludeDirectories.begin(); - i != this->IncludeDirectories.end(); ++i) { - std::string path = *i; + for (std::string path : this->IncludeDirectories) { path = path + "/"; path = path + cxxFile; if (cmSystemTools::FileExists(path.c_str())) { @@ -235,10 +228,7 @@ protected: if (cmSystemTools::FileExists(cxxFile.c_str())) { found = true; } - for (std::vector<std::string>::iterator i = - this->IncludeDirectories.begin(); - i != this->IncludeDirectories.end(); ++i) { - std::string path = *i; + for (std::string path : this->IncludeDirectories) { path = path + "/"; path = path + cxxFile; if (cmSystemTools::FileExists(path.c_str())) { @@ -251,10 +241,7 @@ protected: if (cmSystemTools::FileExists(cxxFile.c_str())) { found = true; } - for (std::vector<std::string>::iterator i = - this->IncludeDirectories.begin(); - i != this->IncludeDirectories.end(); ++i) { - std::string path = *i; + for (std::string path : this->IncludeDirectories) { path = path + "/"; path = path + cxxFile; if (cmSystemTools::FileExists(path.c_str())) { @@ -267,10 +254,7 @@ protected: if (cmSystemTools::FileExists(cxxFile.c_str())) { found = true; } - for (std::vector<std::string>::iterator i = - this->IncludeDirectories.begin(); - i != this->IncludeDirectories.end(); ++i) { - std::string path = *i; + for (std::string path : this->IncludeDirectories) { path = path + "/"; path = path + cxxFile; if (cmSystemTools::FileExists(path.c_str())) { @@ -337,10 +321,8 @@ protected: if (!cFile.GetDepends().empty()) { // Dependency hints have been given. Use them to begin the // recursion. - for (std::vector<std::string>::const_iterator file = - cFile.GetDepends().begin(); - file != cFile.GetDepends().end(); ++file) { - this->AddDependency(info, file->c_str()); + for (std::string const& file : cFile.GetDepends()) { + this->AddDependency(info, file.c_str()); } // Found dependency information. We are done. @@ -357,10 +339,7 @@ protected: found = true; } else { // try to guess which include path to use - for (std::vector<std::string>::iterator t = - this->IncludeDirectories.begin(); - t != this->IncludeDirectories.end(); ++t) { - std::string incpath = *t; + for (std::string incpath : this->IncludeDirectories) { if (!incpath.empty() && incpath[incpath.size() - 1] != '/') { incpath = incpath + "/"; } @@ -383,7 +362,7 @@ protected: } else { // Destroy the name of the file so that it won't be output as a // dependency. - info->FullPath = ""; + info->FullPath.clear(); } } } @@ -442,10 +421,7 @@ protected: return fp; } - for (std::vector<std::string>::iterator i = - this->IncludeDirectories.begin(); - i != this->IncludeDirectories.end(); ++i) { - std::string path = *i; + for (std::string path : this->IncludeDirectories) { if (!path.empty() && path[path.size() - 1] != '/') { path = path + "/"; } @@ -532,19 +508,17 @@ void cmOutputRequiredFilesCommand::ListDependencies( // add info to the visited set visited->insert(info); // now recurse with info's dependencies - for (cmDependInformation::DependencySetType::const_iterator d = - info->DependencySet.begin(); - d != info->DependencySet.end(); ++d) { - if (visited->find(*d) == visited->end()) { - if (info->FullPath != "") { - std::string tmp = (*d)->FullPath; + for (cmDependInformation* d : info->DependencySet) { + if (visited->find(d) == visited->end()) { + if (!info->FullPath.empty()) { + std::string tmp = d->FullPath; std::string::size_type pos = tmp.rfind('.'); if (pos != std::string::npos && (tmp.substr(pos) != ".h")) { tmp = tmp.substr(0, pos); - fprintf(fout, "%s\n", (*d)->FullPath.c_str()); + fprintf(fout, "%s\n", d->FullPath.c_str()); } } - this->ListDependencies(*d, fout, visited); + this->ListDependencies(d, fout, visited); } } } diff --git a/Source/cmOutputRequiredFilesCommand.h b/Source/cmOutputRequiredFilesCommand.h index 6dcb888..09e622b 100644 --- a/Source/cmOutputRequiredFilesCommand.h +++ b/Source/cmOutputRequiredFilesCommand.h @@ -18,9 +18,9 @@ class cmExecutionStatus; class cmOutputRequiredFilesCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE { return new cmOutputRequiredFilesCommand; } + cmCommand* Clone() override { return new cmOutputRequiredFilesCommand; } bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; void ListDependencies(cmDependInformation const* info, FILE* fout, std::set<cmDependInformation const*>* visited); diff --git a/Source/cmParseArgumentsCommand.cxx b/Source/cmParseArgumentsCommand.cxx index d75ee8e..0922e6e 100644 --- a/Source/cmParseArgumentsCommand.cxx +++ b/Source/cmParseArgumentsCommand.cxx @@ -5,7 +5,6 @@ #include <map> #include <set> #include <sstream> -#include <stddef.h> #include <utility> #include "cmAlgorithms.h" @@ -19,11 +18,11 @@ static std::string escape_arg(const std::string& arg) { // replace ";" with "\;" so output argument lists will split correctly std::string escapedArg; - for (size_t i = 0; i < arg.size(); ++i) { - if (arg[i] == ';') { + for (char i : arg) { + if (i == ';') { escapedArg += '\\'; } - escapedArg += arg[i]; + escapedArg += i; } return escapedArg; } @@ -70,7 +69,7 @@ bool cmParseArgumentsCommand::InitialPass(std::vector<std::string> const& args, // options, single values and multi values typedef std::map<std::string, bool> options_map; typedef std::map<std::string, std::string> single_map; - typedef std::map<std::string, std::vector<std::string> > multi_map; + typedef std::map<std::string, std::vector<std::string>> multi_map; options_map options; single_map single; multi_map multi; @@ -85,37 +84,31 @@ bool cmParseArgumentsCommand::InitialPass(std::vector<std::string> const& args, // the second argument is a (cmake) list of options without argument std::vector<std::string> list; cmSystemTools::ExpandListArgument(*argIter++, list); - for (std::vector<std::string>::const_iterator iter = list.begin(), - end = list.end(); - iter != end; ++iter) { - if (!used_keywords.insert(*iter).second) { - this->GetMakefile()->IssueMessage(cmake::WARNING, dup_warning + *iter); + for (std::string const& iter : list) { + if (!used_keywords.insert(iter).second) { + this->GetMakefile()->IssueMessage(cmake::WARNING, dup_warning + iter); } - options[*iter]; // default initialize + options[iter]; // default initialize } // the third argument is a (cmake) list of single argument options list.clear(); cmSystemTools::ExpandListArgument(*argIter++, list); - for (std::vector<std::string>::const_iterator iter = list.begin(), - end = list.end(); - iter != end; ++iter) { - if (!used_keywords.insert(*iter).second) { - this->GetMakefile()->IssueMessage(cmake::WARNING, dup_warning + *iter); + for (std::string const& iter : list) { + if (!used_keywords.insert(iter).second) { + this->GetMakefile()->IssueMessage(cmake::WARNING, dup_warning + iter); } - single[*iter]; // default initialize + single[iter]; // default initialize } // the fourth argument is a (cmake) list of multi argument options list.clear(); cmSystemTools::ExpandListArgument(*argIter++, list); - for (std::vector<std::string>::const_iterator iter = list.begin(), - end = list.end(); - iter != end; ++iter) { - if (!used_keywords.insert(*iter).second) { - this->GetMakefile()->IssueMessage(cmake::WARNING, dup_warning + *iter); + for (std::string const& iter : list) { + if (!used_keywords.insert(iter).second) { + this->GetMakefile()->IssueMessage(cmake::WARNING, dup_warning + iter); } - multi[*iter]; // default initialize + multi[iter]; // default initialize } enum insideValues @@ -160,46 +153,45 @@ bool cmParseArgumentsCommand::InitialPass(std::vector<std::string> const& args, } // iterate over the arguments list and fill in the values where applicable - for (argIter = list.begin(), argEnd = list.end(); argIter != argEnd; - ++argIter) { - const options_map::iterator optIter = options.find(*argIter); + for (std::string const& arg : list) { + const options_map::iterator optIter = options.find(arg); if (optIter != options.end()) { insideValues = NONE; optIter->second = true; continue; } - const single_map::iterator singleIter = single.find(*argIter); + const single_map::iterator singleIter = single.find(arg); if (singleIter != single.end()) { insideValues = SINGLE; - currentArgName = *argIter; + currentArgName = arg; continue; } - const multi_map::iterator multiIter = multi.find(*argIter); + const multi_map::iterator multiIter = multi.find(arg); if (multiIter != multi.end()) { insideValues = MULTI; - currentArgName = *argIter; + currentArgName = arg; continue; } switch (insideValues) { case SINGLE: - single[currentArgName] = *argIter; + single[currentArgName] = arg; insideValues = NONE; break; case MULTI: if (parseFromArgV) { - multi[currentArgName].push_back(escape_arg(*argIter)); + multi[currentArgName].push_back(escape_arg(arg)); } else { - multi[currentArgName].push_back(*argIter); + multi[currentArgName].push_back(arg); } break; default: if (parseFromArgV) { - unparsed.push_back(escape_arg(*argIter)); + unparsed.push_back(escape_arg(arg)); } else { - unparsed.push_back(*argIter); + unparsed.push_back(arg); } break; } @@ -208,28 +200,24 @@ bool cmParseArgumentsCommand::InitialPass(std::vector<std::string> const& args, // now iterate over the collected values and update their definition // within the current scope. undefine if necessary. - for (options_map::const_iterator iter = options.begin(), end = options.end(); - iter != end; ++iter) { - this->Makefile->AddDefinition(prefix + iter->first, - iter->second ? "TRUE" : "FALSE"); + for (auto const& iter : options) { + this->Makefile->AddDefinition(prefix + iter.first, + iter.second ? "TRUE" : "FALSE"); } - for (single_map::const_iterator iter = single.begin(), end = single.end(); - iter != end; ++iter) { - if (!iter->second.empty()) { - this->Makefile->AddDefinition(prefix + iter->first, - iter->second.c_str()); + for (auto const& iter : single) { + if (!iter.second.empty()) { + this->Makefile->AddDefinition(prefix + iter.first, iter.second.c_str()); } else { - this->Makefile->RemoveDefinition(prefix + iter->first); + this->Makefile->RemoveDefinition(prefix + iter.first); } } - for (multi_map::const_iterator iter = multi.begin(), end = multi.end(); - iter != end; ++iter) { - if (!iter->second.empty()) { + for (auto const& iter : multi) { + if (!iter.second.empty()) { this->Makefile->AddDefinition( - prefix + iter->first, cmJoin(cmMakeRange(iter->second), ";").c_str()); + prefix + iter.first, cmJoin(cmMakeRange(iter.second), ";").c_str()); } else { - this->Makefile->RemoveDefinition(prefix + iter->first); + this->Makefile->RemoveDefinition(prefix + iter.first); } } diff --git a/Source/cmParseArgumentsCommand.h b/Source/cmParseArgumentsCommand.h index 469a76a..b8ba61d 100644 --- a/Source/cmParseArgumentsCommand.h +++ b/Source/cmParseArgumentsCommand.h @@ -21,14 +21,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmParseArgumentsCommand; } + cmCommand* Clone() override { return new cmParseArgumentsCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmPathLabel.cxx b/Source/cmPathLabel.cxx index 30ba081..4793206 100644 --- a/Source/cmPathLabel.cxx +++ b/Source/cmPathLabel.cxx @@ -2,15 +2,13 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmPathLabel.h" -#include <stddef.h> - cmPathLabel::cmPathLabel(const std::string& label) : Label(label) , Hash(0) { // Use a Jenkins one-at-a-time hash with under/over-flow protection - for (size_t i = 0; i < this->Label.size(); ++i) { - this->Hash += this->Label[i]; + for (char i : this->Label) { + this->Hash += i; this->Hash += ((this->Hash & 0x003FFFFF) << 10); this->Hash ^= ((this->Hash & 0xFFFFFFC0) >> 6); } diff --git a/Source/cmPipeConnection.cxx b/Source/cmPipeConnection.cxx index b18a1d6..9e565f6 100644 --- a/Source/cmPipeConnection.cxx +++ b/Source/cmPipeConnection.cxx @@ -19,7 +19,8 @@ void cmPipeConnection::Connect(uv_stream_t* server) uv_pipe_init(this->Server->GetLoop(), rejectPipe, 0); uv_accept(server, reinterpret_cast<uv_stream_t*>(rejectPipe)); - uv_close(reinterpret_cast<uv_handle_t*>(rejectPipe), &on_close_delete); + uv_close(reinterpret_cast<uv_handle_t*>(rejectPipe), + &on_close_delete<uv_pipe_t>); return; } @@ -28,7 +29,8 @@ void cmPipeConnection::Connect(uv_stream_t* server) this->ClientPipe->data = static_cast<cmEventBasedConnection*>(this); auto client = reinterpret_cast<uv_stream_t*>(this->ClientPipe); if (uv_accept(server, client) != 0) { - uv_close(reinterpret_cast<uv_handle_t*>(client), &on_close_delete); + uv_close(reinterpret_cast<uv_handle_t*>(client), + &on_close_delete<uv_pipe_t>); this->ClientPipe = nullptr; return; } @@ -65,15 +67,16 @@ bool cmPipeConnection::OnConnectionShuttingDown() { if (this->ClientPipe) { uv_close(reinterpret_cast<uv_handle_t*>(this->ClientPipe), - &on_close_delete); + &on_close_delete<uv_pipe_t>); this->WriteStream->data = nullptr; } - uv_close(reinterpret_cast<uv_handle_t*>(this->ServerPipe), &on_close_delete); + uv_close(reinterpret_cast<uv_handle_t*>(this->ServerPipe), + &on_close_delete<uv_pipe_t>); this->ClientPipe = nullptr; this->ServerPipe = nullptr; this->WriteStream = nullptr; this->ReadStream = nullptr; - return cmConnection::OnConnectionShuttingDown(); + return cmEventBasedConnection::OnConnectionShuttingDown(); } diff --git a/Source/cmPolicies.cxx b/Source/cmPolicies.cxx index 910f6fb..e7d1b72 100644 --- a/Source/cmPolicies.cxx +++ b/Source/cmPolicies.cxx @@ -120,9 +120,8 @@ static void DiagnoseAncientPolicies( e << "The project requests behavior compatible with CMake version \"" << majorVer << "." << minorVer << "." << patchVer << "\", which requires the OLD behavior for some policies:\n"; - for (std::vector<cmPolicies::PolicyID>::const_iterator i = ancient.begin(); - i != ancient.end(); ++i) { - e << " " << idToString(*i) << ": " << idToShortDescription(*i) << "\n"; + for (cmPolicies::PolicyID i : ancient) { + e << " " << idToString(i) << ": " << idToShortDescription(i) << "\n"; } e << "However, this version of CMake no longer supports the OLD " << "behavior for these policies. " @@ -141,7 +140,7 @@ static bool GetPolicyDefault(cmMakefile* mf, std::string const& policy, *defaultSetting = cmPolicies::NEW; } else if (defaultValue == "OLD") { *defaultSetting = cmPolicies::OLD; - } else if (defaultValue == "") { + } else if (defaultValue.empty()) { *defaultSetting = cmPolicies::WARN; } else { std::ostringstream e; diff --git a/Source/cmProcessTools.cxx b/Source/cmProcessTools.cxx index 67b4a97..05b1b00 100644 --- a/Source/cmProcessTools.cxx +++ b/Source/cmProcessTools.cxx @@ -73,11 +73,11 @@ bool cmProcessTools::LineParser::ProcessChunk(const char* first, int length) // Hand this line to the subclass implementation. if (!this->ProcessLine()) { - this->Line = ""; + this->Line.clear(); return false; } - this->Line = ""; + this->Line.clear(); } else if (*c != '\r' || !this->IgnoreCR) { // Append this character to the line under construction. this->Line.append(1, *c); diff --git a/Source/cmProcessTools.h b/Source/cmProcessTools.h index 5b357cd..23fa74e 100644 --- a/Source/cmProcessTools.h +++ b/Source/cmProcessTools.h @@ -59,7 +59,7 @@ public: char Separator; char LineEnd; bool IgnoreCR; - bool ProcessChunk(const char* data, int length) CM_OVERRIDE; + bool ProcessChunk(const char* data, int length) override; /** Implement in a subclass to process one line of input. It should return true only if it is interested in more data. */ @@ -76,7 +76,7 @@ public: } private: - bool ProcessLine() CM_OVERRIDE { return true; } + bool ProcessLine() override { return true; } }; /** Run a process and send output to given parsers. */ diff --git a/Source/cmProjectCommand.cxx b/Source/cmProjectCommand.cxx index d72c790..fea8a9d 100644 --- a/Source/cmProjectCommand.cxx +++ b/Source/cmProjectCommand.cxx @@ -195,15 +195,14 @@ bool cmProjectCommand::InitialPass(std::vector<std::string> const& args, vv.push_back(projectName + "_VERSION_PATCH"); vv.push_back(projectName + "_VERSION_TWEAK"); std::string vw; - for (std::vector<std::string>::iterator i = vv.begin(); i != vv.end(); - ++i) { - const char* v = this->Makefile->GetDefinition(*i); + for (std::string const& i : vv) { + const char* v = this->Makefile->GetDefinition(i); if (v && *v) { if (cmp0048 == cmPolicies::WARN) { vw += "\n "; - vw += *i; + vw += i; } else { - this->Makefile->AddDefinition(*i, ""); + this->Makefile->AddDefinition(i, ""); } } } diff --git a/Source/cmProjectCommand.h b/Source/cmProjectCommand.h index afe489a..80fa235 100644 --- a/Source/cmProjectCommand.h +++ b/Source/cmProjectCommand.h @@ -26,14 +26,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmProjectCommand; } + cmCommand* Clone() override { return new cmProjectCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmPropertyMap.cxx b/Source/cmPropertyMap.cxx index 4905c24..3f6d7c8 100644 --- a/Source/cmPropertyMap.cxx +++ b/Source/cmPropertyMap.cxx @@ -21,9 +21,8 @@ cmProperty* cmPropertyMap::GetOrCreateProperty(const std::string& name) std::vector<std::string> cmPropertyMap::GetPropertyList() const { std::vector<std::string> keyList; - for (cmPropertyMap::const_iterator i = this->begin(), e = this->end(); - i != e; ++i) { - keyList.push_back(i->first); + for (auto const& i : *this) { + keyList.push_back(i.first); } std::sort(keyList.begin(), keyList.end()); return keyList; diff --git a/Source/cmQTWrapCPPCommand.h b/Source/cmQTWrapCPPCommand.h index 014a4ab..c1dcd54 100644 --- a/Source/cmQTWrapCPPCommand.h +++ b/Source/cmQTWrapCPPCommand.h @@ -24,14 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmQTWrapCPPCommand; } + cmCommand* Clone() override { return new cmQTWrapCPPCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmQTWrapUICommand.h b/Source/cmQTWrapUICommand.h index f7e6bdd..15cab40 100644 --- a/Source/cmQTWrapUICommand.h +++ b/Source/cmQTWrapUICommand.h @@ -23,14 +23,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmQTWrapUICommand; } + cmCommand* Clone() override { return new cmQTWrapUICommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmQtAutoGen.cxx b/Source/cmQtAutoGen.cxx new file mode 100644 index 0000000..5e89978 --- /dev/null +++ b/Source/cmQtAutoGen.cxx @@ -0,0 +1,374 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#include "cmQtAutoGen.h" +#include "cmAlgorithms.h" +#include "cmProcessOutput.h" +#include "cmSystemTools.h" + +#include "cmsys/FStream.hxx" +#include "cmsys/RegularExpression.hxx" + +#include <algorithm> +#include <sstream> +#include <stddef.h> + +// - Static variables + +std::string const genNameGen = "AutoGen"; +std::string const genNameMoc = "AutoMoc"; +std::string const genNameUic = "AutoUic"; +std::string const genNameRcc = "AutoRcc"; + +std::string const mcNameSingle = "SINGLE"; +std::string const mcNameWrap = "WRAP"; +std::string const mcNameFull = "FULL"; + +// - Static functions + +/// @brief Merges newOpts into baseOpts +/// @arg valueOpts list of options that accept a value +void MergeOptions(std::vector<std::string>& baseOpts, + std::vector<std::string> const& newOpts, + std::vector<std::string> const& valueOpts, bool isQt5) +{ + typedef std::vector<std::string>::iterator Iter; + typedef std::vector<std::string>::const_iterator CIter; + if (newOpts.empty()) { + return; + } + if (baseOpts.empty()) { + baseOpts = newOpts; + return; + } + + std::vector<std::string> extraOpts; + for (CIter fit = newOpts.begin(), fitEnd = newOpts.end(); fit != fitEnd; + ++fit) { + std::string const& newOpt = *fit; + Iter existIt = std::find(baseOpts.begin(), baseOpts.end(), newOpt); + if (existIt != baseOpts.end()) { + if (newOpt.size() >= 2) { + // Acquire the option name + std::string optName; + { + auto oit = newOpt.begin(); + if (*oit == '-') { + ++oit; + if (isQt5 && (*oit == '-')) { + ++oit; + } + optName.assign(oit, newOpt.end()); + } + } + // Test if this is a value option and change the existing value + if (!optName.empty() && (std::find(valueOpts.begin(), valueOpts.end(), + optName) != valueOpts.end())) { + const Iter existItNext(existIt + 1); + const CIter fitNext(fit + 1); + if ((existItNext != baseOpts.end()) && (fitNext != fitEnd)) { + *existItNext = *fitNext; + ++fit; + } + } + } + } else { + extraOpts.push_back(newOpt); + } + } + // Append options + baseOpts.insert(baseOpts.end(), extraOpts.begin(), extraOpts.end()); +} + +static std::string utilStripCR(std::string const& line) +{ + // Strip CR characters rcc may have printed (possibly more than one!). + std::string::size_type cr = line.find('\r'); + if (cr != std::string::npos) { + return line.substr(0, cr); + } + return line; +} + +/// @brief Reads the resource files list from from a .qrc file - Qt4 version +/// @return True if the .qrc file was successfully parsed +static bool RccListInputsQt4(std::string const& fileName, + std::vector<std::string>& files, + std::string* errorMessage) +{ + bool allGood = true; + // Read qrc file content into string + std::string qrcContents; + { + cmsys::ifstream ifs(fileName.c_str()); + if (ifs) { + std::ostringstream osst; + osst << ifs.rdbuf(); + qrcContents = osst.str(); + } else { + if (errorMessage != nullptr) { + std::ostringstream ost; + ost << "rcc file not readable:\n" + << " " << cmQtAutoGen::Quoted(fileName) << "\n"; + *errorMessage = ost.str(); + } + allGood = false; + } + } + if (allGood) { + // qrc file directory + std::string qrcDir(cmSystemTools::GetFilenamePath(fileName)); + if (!qrcDir.empty()) { + qrcDir += '/'; + } + + cmsys::RegularExpression fileMatchRegex("(<file[^<]+)"); + cmsys::RegularExpression fileReplaceRegex("(^<file[^>]*>)"); + + size_t offset = 0; + while (fileMatchRegex.find(qrcContents.c_str() + offset)) { + std::string qrcEntry = fileMatchRegex.match(1); + offset += qrcEntry.size(); + { + fileReplaceRegex.find(qrcEntry); + std::string tag = fileReplaceRegex.match(1); + qrcEntry = qrcEntry.substr(tag.size()); + } + if (!cmSystemTools::FileIsFullPath(qrcEntry.c_str())) { + qrcEntry = qrcDir + qrcEntry; + } + files.push_back(qrcEntry); + } + } + return allGood; +} + +/// @brief Reads the resource files list from from a .qrc file - Qt5 version +/// @return True if the .qrc file was successfully parsed +static bool RccListInputsQt5(std::string const& rccCommand, + std::string const& fileName, + std::vector<std::string>& files, + std::string* errorMessage) +{ + if (rccCommand.empty()) { + cmSystemTools::Error("rcc executable not available"); + return false; + } + + // Read rcc features + bool hasDashDashList = false; + { + std::vector<std::string> command; + command.push_back(rccCommand); + command.push_back("--help"); + std::string rccStdOut; + std::string rccStdErr; + int retVal = 0; + bool result = cmSystemTools::RunSingleCommand( + command, &rccStdOut, &rccStdErr, &retVal, nullptr, + cmSystemTools::OUTPUT_NONE, 0.0, cmProcessOutput::Auto); + if (result && retVal == 0 && + rccStdOut.find("--list") != std::string::npos) { + hasDashDashList = true; + } + } + + std::string const fileDir = cmSystemTools::GetFilenamePath(fileName); + std::string const fileNameName = cmSystemTools::GetFilenameName(fileName); + + // Run rcc list command + bool result = false; + int retVal = 0; + std::string rccStdOut; + std::string rccStdErr; + { + std::vector<std::string> command; + command.push_back(rccCommand); + command.push_back(hasDashDashList ? "--list" : "-list"); + command.push_back(fileNameName); + result = cmSystemTools::RunSingleCommand( + command, &rccStdOut, &rccStdErr, &retVal, fileDir.c_str(), + cmSystemTools::OUTPUT_NONE, 0.0, cmProcessOutput::Auto); + } + if (!result || retVal) { + if (errorMessage != nullptr) { + std::ostringstream ost; + ost << "rcc list process failed for\n " << cmQtAutoGen::Quoted(fileName) + << "\n" + << rccStdOut << "\n" + << rccStdErr << "\n"; + *errorMessage = ost.str(); + } + return false; + } + + // Parse rcc std output + { + std::istringstream ostr(rccStdOut); + std::string oline; + while (std::getline(ostr, oline)) { + oline = utilStripCR(oline); + if (!oline.empty()) { + files.push_back(oline); + } + } + } + // Parse rcc error output + { + std::istringstream estr(rccStdErr); + std::string eline; + while (std::getline(estr, eline)) { + eline = utilStripCR(eline); + if (cmHasLiteralPrefix(eline, "RCC: Error in")) { + static std::string searchString = "Cannot find file '"; + + std::string::size_type pos = eline.find(searchString); + if (pos == std::string::npos) { + if (errorMessage != nullptr) { + std::ostringstream ost; + ost << "rcc lists unparsable output:\n" + << cmQtAutoGen::Quoted(eline) << "\n"; + *errorMessage = ost.str(); + } + return false; + } + pos += searchString.length(); + std::string::size_type sz = eline.size() - pos - 1; + files.push_back(eline.substr(pos, sz)); + } + } + } + + // Convert relative paths to absolute paths + for (std::string& resFile : files) { + resFile = cmSystemTools::CollapseCombinedPath(fileDir, resFile); + } + + return true; +} + +// - Class definitions + +std::string const cmQtAutoGen::listSep = "@LSEP@"; + +std::string const& cmQtAutoGen::GeneratorName(Generator type) +{ + switch (type) { + case Generator::GEN: + return genNameGen; + case Generator::MOC: + return genNameMoc; + case Generator::UIC: + return genNameUic; + case Generator::RCC: + return genNameRcc; + } + return genNameGen; +} + +std::string cmQtAutoGen::GeneratorNameUpper(Generator genType) +{ + return cmSystemTools::UpperCase(cmQtAutoGen::GeneratorName(genType)); +} + +std::string const& cmQtAutoGen::MultiConfigName(MultiConfig config) +{ + switch (config) { + case MultiConfig::SINGLE: + return mcNameSingle; + case MultiConfig::WRAP: + return mcNameWrap; + case MultiConfig::FULL: + return mcNameFull; + } + return mcNameWrap; +} + +cmQtAutoGen::MultiConfig cmQtAutoGen::MultiConfigType(std::string const& name) +{ + if (name == mcNameSingle) { + return MultiConfig::SINGLE; + } + if (name == mcNameFull) { + return MultiConfig::FULL; + } + return MultiConfig::WRAP; +} + +std::string cmQtAutoGen::Quoted(std::string const& text) +{ + static const char* rep[18] = { "\\", "\\\\", "\"", "\\\"", "\a", "\\a", + "\b", "\\b", "\f", "\\f", "\n", "\\n", + "\r", "\\r", "\t", "\\t", "\v", "\\v" }; + + std::string res = text; + for (const char* const* it = cmArrayBegin(rep); it != cmArrayEnd(rep); + it += 2) { + cmSystemTools::ReplaceString(res, *it, *(it + 1)); + } + res = '"' + res; + res += '"'; + return res; +} + +std::string cmQtAutoGen::AppendFilenameSuffix(std::string const& filename, + std::string const& suffix) +{ + std::string res; + auto pos = filename.rfind('.'); + if (pos != std::string::npos) { + const auto it_dot = filename.begin() + pos; + res.assign(filename.begin(), it_dot); + res.append(suffix); + res.append(it_dot, filename.end()); + } else { + res = filename; + res.append(suffix); + } + return res; +} + +void cmQtAutoGen::UicMergeOptions(std::vector<std::string>& baseOpts, + std::vector<std::string> const& newOpts, + bool isQt5) +{ + static std::vector<std::string> const valueOpts = { + "tr", "translate", "postfix", "generator", + "include", // Since Qt 5.3 + "g" + }; + MergeOptions(baseOpts, newOpts, valueOpts, isQt5); +} + +void cmQtAutoGen::RccMergeOptions(std::vector<std::string>& baseOpts, + std::vector<std::string> const& newOpts, + bool isQt5) +{ + static std::vector<std::string> const valueOpts = { "name", "root", + "compress", + "threshold" }; + MergeOptions(baseOpts, newOpts, valueOpts, isQt5); +} + +bool cmQtAutoGen::RccListInputs(std::string const& qtMajorVersion, + std::string const& rccCommand, + std::string const& fileName, + std::vector<std::string>& files, + std::string* errorMessage) +{ + bool allGood = false; + if (cmSystemTools::FileExists(fileName.c_str())) { + if (qtMajorVersion == "4") { + allGood = RccListInputsQt4(fileName, files, errorMessage); + } else { + allGood = RccListInputsQt5(rccCommand, fileName, files, errorMessage); + } + } else { + if (errorMessage != nullptr) { + std::ostringstream ost; + ost << "rcc file does not exist:\n" + << " " << cmQtAutoGen::Quoted(fileName) << "\n"; + *errorMessage = ost.str(); + } + } + return allGood; +} diff --git a/Source/cmQtAutoGen.h b/Source/cmQtAutoGen.h new file mode 100644 index 0000000..acc092f --- /dev/null +++ b/Source/cmQtAutoGen.h @@ -0,0 +1,72 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#ifndef cmQtAutoGen_h +#define cmQtAutoGen_h + +#include "cmConfigure.h" // IWYU pragma: keep + +#include <string> +#include <vector> + +/** \class cmQtAutoGen + * \brief Class used as namespace for QtAutogen related types and functions + */ +class cmQtAutoGen +{ +public: + static std::string const listSep; + + enum Generator + { + GEN, // General + MOC, + UIC, + RCC + }; + + enum MultiConfig + { + SINGLE, // Single configuration + WRAP, // Multi configuration using wrapper files + FULL // Full multi configuration using per config sources + }; + +public: + /// @brief Returns the generator name + static std::string const& GeneratorName(Generator genType); + /// @brief Returns the generator name in upper case + static std::string GeneratorNameUpper(Generator genType); + + /// @brief Returns the multi configuration name string + static std::string const& MultiConfigName(MultiConfig config); + /// @brief Returns the multi configuration type + static MultiConfig MultiConfigType(std::string const& name); + + /// @brief Returns a the string escaped and enclosed in quotes + static std::string Quoted(std::string const& text); + + /// @brief Appends the suffix to the filename before the last dot + static std::string AppendFilenameSuffix(std::string const& filename, + std::string const& suffix); + + /// @brief Merges newOpts into baseOpts + static void UicMergeOptions(std::vector<std::string>& baseOpts, + std::vector<std::string> const& newOpts, + bool isQt5); + + /// @brief Merges newOpts into baseOpts + static void RccMergeOptions(std::vector<std::string>& baseOpts, + std::vector<std::string> const& newOpts, + bool isQt5); + + /// @brief Reads the resource files list from from a .qrc file + /// @arg fileName Must be the absolute path of the .qrc file + /// @return True if the rcc file was successfully parsed + static bool RccListInputs(std::string const& qtMajorVersion, + std::string const& rccCommand, + std::string const& fileName, + std::vector<std::string>& files, + std::string* errorMessage = nullptr); +}; + +#endif diff --git a/Source/cmQtAutoGenDigest.h b/Source/cmQtAutoGenDigest.h new file mode 100644 index 0000000..677c397 --- /dev/null +++ b/Source/cmQtAutoGenDigest.h @@ -0,0 +1,64 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#ifndef cmQtAutoGenDigest_h +#define cmQtAutoGenDigest_h + +#include "cmConfigure.h" // IWYU pragma: keep + +#include <memory> +#include <string> +#include <vector> + +class cmGeneratorTarget; + +class cmQtAutoGenDigestQrc +{ +public: + cmQtAutoGenDigestQrc() + : Generated(false) + , Unique(false) + { + } + +public: + std::string QrcFile; + std::string QrcName; + std::string PathChecksum; + std::string RccFile; + bool Generated; + bool Unique; + std::vector<std::string> Options; + std::vector<std::string> Resources; +}; + +/** \class cmQtAutoGenDigest + * \brief Filtered set of QtAutogen variables for a specific target + */ +class cmQtAutoGenDigest +{ +public: + cmQtAutoGenDigest(cmGeneratorTarget* target) + : Target(target) + , MocEnabled(false) + , UicEnabled(false) + , RccEnabled(false) + { + } + +public: + cmGeneratorTarget* Target; + std::string QtVersionMajor; + std::string QtVersionMinor; + bool MocEnabled; + bool UicEnabled; + bool RccEnabled; + std::vector<std::string> Headers; + std::vector<std::string> Sources; + std::vector<cmQtAutoGenDigestQrc> Qrcs; +}; + +// Utility types +typedef std::unique_ptr<cmQtAutoGenDigest> cmQtAutoGenDigestUP; +typedef std::vector<cmQtAutoGenDigestUP> cmQtAutoGenDigestUPV; + +#endif diff --git a/Source/cmQtAutoGeneratorCommon.cxx b/Source/cmQtAutoGeneratorCommon.cxx deleted file mode 100644 index a8e6b96..0000000 --- a/Source/cmQtAutoGeneratorCommon.cxx +++ /dev/null @@ -1,216 +0,0 @@ -/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying - file Copyright.txt or https://cmake.org/licensing for details. */ -#include "cmQtAutoGeneratorCommon.h" -#include "cmAlgorithms.h" -#include "cmSystemTools.h" - -#include "cmsys/FStream.hxx" -#include "cmsys/RegularExpression.hxx" - -#include <sstream> -#include <stddef.h> - -// - Static functions - -static std::string utilStripCR(std::string const& line) -{ - // Strip CR characters rcc may have printed (possibly more than one!). - std::string::size_type cr = line.find('\r'); - if (cr != std::string::npos) { - return line.substr(0, cr); - } - return line; -} - -/// @brief Reads the resource files list from from a .qrc file - Qt4 version -/// @return True if the .qrc file was successfully parsed -static bool RccListInputsQt4(const std::string& fileName, - std::vector<std::string>& files, - std::string* errorMessage) -{ - bool allGood = true; - // Read qrc file content into string - std::string qrcContents; - { - cmsys::ifstream ifs(fileName.c_str()); - if (ifs) { - std::ostringstream osst; - osst << ifs.rdbuf(); - qrcContents = osst.str(); - } else { - if (errorMessage != nullptr) { - std::ostringstream ost; - ost << "AutoRcc: Error: Rcc file not readable:\n" - << cmQtAutoGeneratorCommon::Quoted(fileName) << "\n"; - *errorMessage = ost.str(); - } - allGood = false; - } - } - if (allGood) { - // qrc file directory - std::string qrcDir(cmsys::SystemTools::GetFilenamePath(fileName)); - if (!qrcDir.empty()) { - qrcDir += '/'; - } - - cmsys::RegularExpression fileMatchRegex("(<file[^<]+)"); - cmsys::RegularExpression fileReplaceRegex("(^<file[^>]*>)"); - - size_t offset = 0; - while (fileMatchRegex.find(qrcContents.c_str() + offset)) { - std::string qrcEntry = fileMatchRegex.match(1); - offset += qrcEntry.size(); - { - fileReplaceRegex.find(qrcEntry); - std::string tag = fileReplaceRegex.match(1); - qrcEntry = qrcEntry.substr(tag.size()); - } - if (!cmSystemTools::FileIsFullPath(qrcEntry.c_str())) { - qrcEntry = qrcDir + qrcEntry; - } - files.push_back(qrcEntry); - } - } - return allGood; -} - -/// @brief Reads the resource files list from from a .qrc file - Qt5 version -/// @return True if the .qrc file was successfully parsed -static bool RccListInputsQt5(const std::string& rccCommand, - const std::string& fileName, - std::vector<std::string>& files, - std::string* errorMessage) -{ - if (rccCommand.empty()) { - cmSystemTools::Error("AutoRcc: Error: rcc executable not available\n"); - return false; - } - - // Read rcc features - bool hasDashDashList = false; - { - std::vector<std::string> command; - command.push_back(rccCommand); - command.push_back("--help"); - std::string rccStdOut; - std::string rccStdErr; - int retVal = 0; - bool result = - cmSystemTools::RunSingleCommand(command, &rccStdOut, &rccStdErr, &retVal, - nullptr, cmSystemTools::OUTPUT_NONE); - if (result && retVal == 0 && - rccStdOut.find("--list") != std::string::npos) { - hasDashDashList = true; - } - } - - // Run rcc list command - bool result = false; - int retVal = 0; - std::string rccStdOut; - std::string rccStdErr; - { - std::vector<std::string> command; - command.push_back(rccCommand); - command.push_back(hasDashDashList ? "--list" : "-list"); - command.push_back(fileName); - result = - cmSystemTools::RunSingleCommand(command, &rccStdOut, &rccStdErr, &retVal, - nullptr, cmSystemTools::OUTPUT_NONE); - } - if (!result || retVal) { - if (errorMessage != nullptr) { - std::ostringstream ost; - ost << "AutoRcc: Error: Rcc list process for " << fileName - << " failed:\n" - << rccStdOut << "\n" - << rccStdErr << "\n"; - *errorMessage = ost.str(); - } - return false; - } - - // Parse rcc std output - { - std::istringstream ostr(rccStdOut); - std::string oline; - while (std::getline(ostr, oline)) { - oline = utilStripCR(oline); - if (!oline.empty()) { - files.push_back(oline); - } - } - } - // Parse rcc error output - { - std::istringstream estr(rccStdErr); - std::string eline; - while (std::getline(estr, eline)) { - eline = utilStripCR(eline); - if (cmHasLiteralPrefix(eline, "RCC: Error in")) { - static std::string searchString = "Cannot find file '"; - - std::string::size_type pos = eline.find(searchString); - if (pos == std::string::npos) { - if (errorMessage != nullptr) { - std::ostringstream ost; - ost << "AutoRcc: Error: Rcc lists unparsable output:\n" - << cmQtAutoGeneratorCommon::Quoted(eline) << "\n"; - *errorMessage = ost.str(); - } - return false; - } - pos += searchString.length(); - std::string::size_type sz = eline.size() - pos - 1; - files.push_back(eline.substr(pos, sz)); - } - } - } - - return true; -} - -// - Class definitions - -const char* cmQtAutoGeneratorCommon::listSep = "@LSEP@"; - -std::string cmQtAutoGeneratorCommon::Quoted(const std::string& text) -{ - static const char* rep[18] = { "\\", "\\\\", "\"", "\\\"", "\a", "\\a", - "\b", "\\b", "\f", "\\f", "\n", "\\n", - "\r", "\\r", "\t", "\\t", "\v", "\\v" }; - - std::string res = text; - for (const char* const* it = cmArrayBegin(rep); it != cmArrayEnd(rep); - it += 2) { - cmSystemTools::ReplaceString(res, *it, *(it + 1)); - } - res = '"' + res; - res += '"'; - return res; -} - -bool cmQtAutoGeneratorCommon::RccListInputs(const std::string& qtMajorVersion, - const std::string& rccCommand, - const std::string& fileName, - std::vector<std::string>& files, - std::string* errorMessage) -{ - bool allGood = false; - if (cmsys::SystemTools::FileExists(fileName.c_str())) { - if (qtMajorVersion == "4") { - allGood = RccListInputsQt4(fileName, files, errorMessage); - } else { - allGood = RccListInputsQt5(rccCommand, fileName, files, errorMessage); - } - } else { - if (errorMessage != nullptr) { - std::ostringstream ost; - ost << "AutoRcc: Error: Rcc file does not exist:\n" - << cmQtAutoGeneratorCommon::Quoted(fileName) << "\n"; - *errorMessage = ost.str(); - } - } - return allGood; -} diff --git a/Source/cmQtAutoGeneratorCommon.h b/Source/cmQtAutoGeneratorCommon.h deleted file mode 100644 index 23a882a..0000000 --- a/Source/cmQtAutoGeneratorCommon.h +++ /dev/null @@ -1,39 +0,0 @@ -/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying - file Copyright.txt or https://cmake.org/licensing for details. */ -#ifndef cmQtAutoGeneratorCommon_h -#define cmQtAutoGeneratorCommon_h - -#include "cmConfigure.h" // IWYU pragma: keep - -#include <string> -#include <vector> - -class cmQtAutoGeneratorCommon -{ - // - Types and statics -public: - static const char* listSep; - - enum GeneratorType - { - MOC, - UIC, - RCC - }; - -public: - /// @brief Returns a the string escaped and enclosed in quotes - /// - static std::string Quoted(const std::string& text); - - /// @brief Reads the resource files list from from a .qrc file - /// @arg fileName Must be the absolute path of the .qrc file - /// @return True if the rcc file was successfully parsed - static bool RccListInputs(const std::string& qtMajorVersion, - const std::string& rccCommand, - const std::string& fileName, - std::vector<std::string>& files, - std::string* errorMessage = nullptr); -}; - -#endif diff --git a/Source/cmQtAutoGeneratorInitializer.cxx b/Source/cmQtAutoGeneratorInitializer.cxx index 07fb528..9befd65 100644 --- a/Source/cmQtAutoGeneratorInitializer.cxx +++ b/Source/cmQtAutoGeneratorInitializer.cxx @@ -1,7 +1,7 @@ /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ +#include "cmQtAutoGen.h" #include "cmQtAutoGeneratorInitializer.h" -#include "cmQtAutoGeneratorCommon.h" #include "cmAlgorithms.h" #include "cmCustomCommand.h" @@ -23,6 +23,7 @@ #include "cmsys/FStream.hxx" #include <algorithm> +#include <array> #include <map> #include <set> #include <sstream> @@ -35,15 +36,38 @@ inline static const char* SafeString(const char* value) return (value != nullptr) ? value : ""; } -static std::string GetSafeProperty(cmGeneratorTarget const* target, - const char* key) +inline static std::string GetSafeProperty(cmGeneratorTarget const* target, + const char* key) { return std::string(SafeString(target->GetProperty(key))); } -inline static bool AutogenMultiConfig(cmGlobalGenerator* globalGen) +inline static std::string GetSafeProperty(cmSourceFile const* sf, + const char* key) { - return globalGen->IsMultiConfig(); + return std::string(SafeString(sf->GetProperty(key))); +} + +static cmQtAutoGen::MultiConfig AutogenMultiConfig( + cmGlobalGenerator* globalGen) +{ + if (!globalGen->IsMultiConfig()) { + return cmQtAutoGen::SINGLE; + } + + // FIXME: Xcode does not support per-config sources, yet. + // (EXCLUDED_SOURCE_FILE_NAMES) + // if (globalGen->GetName().find("Xcode") != std::string::npos) { + // return cmQtAutoGen::FULL; + //} + + // FIXME: Visual Studio does not support per-config sources, yet. + // (EXCLUDED_SOURCE_FILE_NAMES) + // if (globalGen->GetName().find("Visual Studio") != std::string::npos) { + // return cmQtAutoGen::FULL; + //} + + return cmQtAutoGen::WRAP; } static std::string GetAutogenTargetName(cmGeneratorTarget const* target) @@ -76,43 +100,44 @@ static std::string GetAutogenTargetBuildDir(cmGeneratorTarget const* target) return targetDir; } -static std::string GetQtMajorVersion(cmGeneratorTarget const* target) +std::string cmQtAutoGeneratorInitializer::GetQtMajorVersion( + cmGeneratorTarget const* target) { cmMakefile* makefile = target->Target->GetMakefile(); - std::string qtMajorVersion = makefile->GetSafeDefinition("QT_VERSION_MAJOR"); - if (qtMajorVersion.empty()) { - qtMajorVersion = makefile->GetSafeDefinition("Qt5Core_VERSION_MAJOR"); + std::string qtMajor = makefile->GetSafeDefinition("QT_VERSION_MAJOR"); + if (qtMajor.empty()) { + qtMajor = makefile->GetSafeDefinition("Qt5Core_VERSION_MAJOR"); } const char* targetQtVersion = target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION", ""); if (targetQtVersion != nullptr) { - qtMajorVersion = targetQtVersion; + qtMajor = targetQtVersion; } - return qtMajorVersion; + return qtMajor; } -static std::string GetQtMinorVersion(cmGeneratorTarget const* target, - const std::string& qtMajorVersion) +std::string cmQtAutoGeneratorInitializer::GetQtMinorVersion( + cmGeneratorTarget const* target, std::string const& qtVersionMajor) { cmMakefile* makefile = target->Target->GetMakefile(); - std::string qtMinorVersion; - if (qtMajorVersion == "5") { - qtMinorVersion = makefile->GetSafeDefinition("Qt5Core_VERSION_MINOR"); + std::string qtMinor; + if (qtVersionMajor == "5") { + qtMinor = makefile->GetSafeDefinition("Qt5Core_VERSION_MINOR"); } - if (qtMinorVersion.empty()) { - qtMinorVersion = makefile->GetSafeDefinition("QT_VERSION_MINOR"); + if (qtMinor.empty()) { + qtMinor = makefile->GetSafeDefinition("QT_VERSION_MINOR"); } const char* targetQtVersion = target->GetLinkInterfaceDependentStringProperty("QT_MINOR_VERSION", ""); if (targetQtVersion != nullptr) { - qtMinorVersion = targetQtVersion; + qtMinor = targetQtVersion; } - return qtMinorVersion; + return qtMinor; } -static bool QtVersionGreaterOrEqual(const std::string& major, - const std::string& minor, +static bool QtVersionGreaterOrEqual(std::string const& major, + std::string const& minor, unsigned long requestMajor, unsigned long requestMinor) { @@ -126,61 +151,17 @@ static bool QtVersionGreaterOrEqual(const std::string& major, return false; } -static void GetCompileDefinitionsAndDirectories( - cmGeneratorTarget const* target, const std::string& config, - std::string& incs, std::string& defs) +static void GetConfigs(cmMakefile* makefile, std::string& configDefault, + std::vector<std::string>& configsList) { - cmLocalGenerator* localGen = target->GetLocalGenerator(); - { - std::vector<std::string> includeDirs; - // Get the include dirs for this target, without stripping the implicit - // include dirs off, see - // https://gitlab.kitware.com/cmake/cmake/issues/13667 - localGen->GetIncludeDirectories(includeDirs, target, "CXX", config, false); - incs = cmJoin(includeDirs, ";"); - } - { - std::set<std::string> defines; - localGen->AddCompileDefinitions(defines, target, config, "CXX"); - defs += cmJoin(defines, ";"); + configDefault = makefile->GetConfigurations(configsList); + if (configsList.empty()) { + configsList.push_back(""); } } -static std::vector<std::string> GetConfigurations( - cmMakefile* makefile, std::string* config = nullptr) -{ - std::vector<std::string> configs; - { - std::string cfg = makefile->GetConfigurations(configs); - if (config != nullptr) { - *config = cfg; - } - } - // Add empty configuration on demand - if (configs.empty()) { - configs.push_back(""); - } - return configs; -} - -static std::vector<std::string> GetConfigurationSuffixes(cmMakefile* makefile) -{ - std::vector<std::string> suffixes; - if (AutogenMultiConfig(makefile->GetGlobalGenerator())) { - makefile->GetConfigurations(suffixes); - for (std::vector<std::string>::iterator it = suffixes.begin(); - it != suffixes.end(); ++it) { - it->insert(0, "_"); - } - } - if (suffixes.empty()) { - suffixes.push_back(""); - } - return suffixes; -} - static void AddDefinitionEscaped(cmMakefile* makefile, const char* key, - const std::string& value) + std::string const& value) { makefile->AddDefinition(key, cmOutputConverter::EscapeForCMake(value).c_str()); @@ -200,51 +181,64 @@ static void AddDefinitionEscaped(cmMakefile* makefile, const char* key, key, cmOutputConverter::EscapeForCMake(cmJoin(values, ";")).c_str()); } -static bool AddToSourceGroup(cmMakefile* makefile, const std::string& fileName, - cmQtAutoGeneratorCommon::GeneratorType genType) +static void AddDefinitionEscaped( + cmMakefile* makefile, const char* key, + const std::vector<std::vector<std::string>>& lists) +{ + std::vector<std::string> seplist; + for (const std::vector<std::string>& list : lists) { + std::string blist = "{"; + blist += cmJoin(list, ";"); + blist += "}"; + seplist.push_back(std::move(blist)); + } + makefile->AddDefinition(key, cmOutputConverter::EscapeForCMake( + cmJoin(seplist, cmQtAutoGen::listSep)) + .c_str()); +} + +static bool AddToSourceGroup(cmMakefile* makefile, std::string const& fileName, + cmQtAutoGen::Generator genType) { cmSourceGroup* sourceGroup = nullptr; // Acquire source group { - const char* groupName = nullptr; - // Use generator specific group name - switch (genType) { - case cmQtAutoGeneratorCommon::MOC: - groupName = - makefile->GetState()->GetGlobalProperty("AUTOMOC_SOURCE_GROUP"); - break; - case cmQtAutoGeneratorCommon::RCC: - groupName = - makefile->GetState()->GetGlobalProperty("AUTORCC_SOURCE_GROUP"); - break; - default: - break; - } - // Use default group name on demand - if ((groupName == nullptr) || (*groupName == 0)) { - groupName = - makefile->GetState()->GetGlobalProperty("AUTOGEN_SOURCE_GROUP"); - } - // Generate a source group on demand - if ((groupName != nullptr) && (*groupName != 0)) { - { - const char* delimiter = - makefile->GetDefinition("SOURCE_GROUP_DELIMITER"); - if (delimiter == nullptr) { - delimiter = "\\"; - } - std::vector<std::string> folders = - cmSystemTools::tokenize(groupName, delimiter); - sourceGroup = makefile->GetSourceGroup(folders); - if (sourceGroup == nullptr) { - makefile->AddSourceGroup(folders); - sourceGroup = makefile->GetSourceGroup(folders); + std::string property; + std::string groupName; + { + std::array<std::string, 2> props; + // Use generator specific group name + switch (genType) { + case cmQtAutoGen::MOC: + props[0] = "AUTOMOC_SOURCE_GROUP"; + break; + case cmQtAutoGen::RCC: + props[0] = "AUTORCC_SOURCE_GROUP"; + break; + default: + props[0] = "AUTOGEN_SOURCE_GROUP"; + break; + } + props[1] = "AUTOGEN_SOURCE_GROUP"; + for (std::string& prop : props) { + const char* propName = makefile->GetState()->GetGlobalProperty(prop); + if ((propName != nullptr) && (*propName != '\0')) { + groupName = propName; + property = std::move(prop); + break; } } + } + // Generate a source group on demand + if (!groupName.empty()) { + sourceGroup = makefile->GetOrCreateSourceGroup(groupName); if (sourceGroup == nullptr) { - cmSystemTools::Error( - "Autogen: Could not create or find source group: ", - cmQtAutoGeneratorCommon::Quoted(groupName).c_str()); + std::ostringstream ost; + ost << cmQtAutoGen::GeneratorNameUpper(genType); + ost << ": " << property; + ost << ": Could not find or create the source group "; + ost << cmQtAutoGen::Quoted(groupName); + cmSystemTools::Error(ost.str().c_str()); return false; } } @@ -255,151 +249,110 @@ static bool AddToSourceGroup(cmMakefile* makefile, const std::string& fileName, return true; } -static void AddCleanFile(cmMakefile* makefile, const std::string& fileName) +static void AddCleanFile(cmMakefile* makefile, std::string const& fileName) { makefile->AppendProperty("ADDITIONAL_MAKE_CLEAN_FILES", fileName.c_str(), false); } -static void AddGeneratedSource(cmGeneratorTarget* target, - const std::string& filename, - cmQtAutoGeneratorCommon::GeneratorType genType) +static std::vector<std::string> AddGeneratedSource( + cmGeneratorTarget* target, std::string const& filename, + cmQtAutoGen::MultiConfig multiConfig, + const std::vector<std::string>& configsList, cmQtAutoGen::Generator genType) { - cmMakefile* makefile = target->Target->GetMakefile(); + std::vector<std::string> genFiles; + // Register source file in makefile and source group + if (multiConfig != cmQtAutoGen::FULL) { + genFiles.push_back(filename); + } else { + for (std::string const& cfg : configsList) { + genFiles.push_back( + cmQtAutoGen::AppendFilenameSuffix(filename, "_" + cfg)); + } + } { - cmSourceFile* gFile = makefile->GetOrCreateSource(filename, true); - gFile->SetProperty("GENERATED", "1"); - gFile->SetProperty("SKIP_AUTOGEN", "On"); + cmMakefile* makefile = target->Target->GetMakefile(); + for (std::string const& genFile : genFiles) { + { + cmSourceFile* gFile = makefile->GetOrCreateSource(genFile, true); + gFile->SetProperty("GENERATED", "1"); + gFile->SetProperty("SKIP_AUTOGEN", "On"); + } + AddToSourceGroup(makefile, genFile, genType); + } + } + + // Add source file to target + if (multiConfig != cmQtAutoGen::FULL) { + target->AddSource(filename); + } else { + for (std::string const& cfg : configsList) { + std::string src = "$<$<CONFIG:"; + src += cfg; + src += ">:"; + src += cmQtAutoGen::AppendFilenameSuffix(filename, "_" + cfg); + src += ">"; + target->AddSource(src); + } } - target->AddSource(filename); - AddToSourceGroup(makefile, filename, genType); + return genFiles; } -struct AutogenSetup +struct cmQtAutoGenSetup { - std::vector<std::string> sources; - std::vector<std::string> headers; + std::set<std::string> MocSkip; + std::set<std::string> UicSkip; - std::set<std::string> mocSkip; - std::set<std::string> uicSkip; - - std::map<std::string, std::string> configSuffix; - std::map<std::string, std::string> configMocIncludes; - std::map<std::string, std::string> configMocDefines; - std::map<std::string, std::string> configUicOptions; + std::map<std::string, std::string> ConfigMocIncludes; + std::map<std::string, std::string> ConfigMocDefines; + std::map<std::string, std::string> ConfigUicOptions; }; -static void SetupAcquireScanFiles(cmGeneratorTarget const* target, - bool mocEnabled, bool uicEnabled, - const std::vector<cmSourceFile*>& srcFiles, - AutogenSetup& setup) +static void SetupAcquireSkipFiles(cmQtAutoGenDigest const& digest, + cmQtAutoGenSetup& setup) { // Read skip files from makefile sources { const std::vector<cmSourceFile*>& allSources = - target->Makefile->GetSourceFiles(); - for (std::vector<cmSourceFile*>::const_iterator fit = allSources.begin(); - fit != allSources.end(); ++fit) { - cmSourceFile* sf = *fit; + digest.Target->Makefile->GetSourceFiles(); + for (cmSourceFile* sf : allSources) { // sf->GetExtension() is only valid after sf->GetFullPath() ... - const std::string& fPath = sf->GetFullPath(); - const cmSystemTools::FileFormat fileType = + std::string const& fPath = sf->GetFullPath(); + cmSystemTools::FileFormat const fileType = cmSystemTools::GetFileFormat(sf->GetExtension().c_str()); if (!(fileType == cmSystemTools::CXX_FILE_FORMAT) && !(fileType == cmSystemTools::HEADER_FILE_FORMAT)) { continue; } const bool skipAll = sf->GetPropertyAsBool("SKIP_AUTOGEN"); - const bool mocSkip = - mocEnabled && (skipAll || sf->GetPropertyAsBool("SKIP_AUTOMOC")); - const bool uicSkip = - uicEnabled && (skipAll || sf->GetPropertyAsBool("SKIP_AUTOUIC")); + const bool mocSkip = digest.MocEnabled && + (skipAll || sf->GetPropertyAsBool("SKIP_AUTOMOC")); + const bool uicSkip = digest.UicEnabled && + (skipAll || sf->GetPropertyAsBool("SKIP_AUTOUIC")); if (mocSkip || uicSkip) { - const std::string absFile = cmsys::SystemTools::GetRealPath(fPath); + std::string const absFile = cmSystemTools::GetRealPath(fPath); if (mocSkip) { - setup.mocSkip.insert(absFile); + setup.MocSkip.insert(absFile); } if (uicSkip) { - setup.uicSkip.insert(absFile); + setup.UicSkip.insert(absFile); } } } } - - const cmPolicies::PolicyStatus CMP0071_status = - target->Makefile->GetPolicyStatus(cmPolicies::CMP0071); - for (std::vector<cmSourceFile*>::const_iterator fileIt = srcFiles.begin(); - fileIt != srcFiles.end(); ++fileIt) { - cmSourceFile* sf = *fileIt; - // sf->GetExtension() is only valid after sf->GetFullPath() ... - const std::string& fPath = sf->GetFullPath(); - const cmSystemTools::FileFormat fileType = - cmSystemTools::GetFileFormat(sf->GetExtension().c_str()); - if (!(fileType == cmSystemTools::CXX_FILE_FORMAT) && - !(fileType == cmSystemTools::HEADER_FILE_FORMAT)) { - continue; - } - // Real file path - const std::string absFile = cmsys::SystemTools::GetRealPath(fPath); - // Skip test - const bool mocSkip = !mocEnabled || (setup.mocSkip.count(absFile) != 0); - const bool uicSkip = !uicEnabled || (setup.uicSkip.count(absFile) != 0); - if (mocSkip && uicSkip) { - continue; - } - - // For GENERATED files check status of policy CMP0071 - if (sf->GetPropertyAsBool("GENERATED")) { - bool policyAccept = false; - switch (CMP0071_status) { - case cmPolicies::WARN: { - std::ostringstream ost; - ost << cmPolicies::GetPolicyWarning(cmPolicies::CMP0071) << "\n"; - ost << "AUTOMOC/AUTOUIC: Ignoring GENERATED source file:\n"; - ost << " " << cmQtAutoGeneratorCommon::Quoted(absFile) << "\n"; - target->Makefile->IssueMessage(cmake::AUTHOR_WARNING, ost.str()); - } - CM_FALLTHROUGH; - case cmPolicies::OLD: - // Ignore GENERATED file - break; - case cmPolicies::REQUIRED_IF_USED: - case cmPolicies::REQUIRED_ALWAYS: - case cmPolicies::NEW: - // Process GENERATED file - policyAccept = true; - break; - } - if (!policyAccept) { - continue; - } - } - - // Add file name to sources or headers list - switch (fileType) { - case cmSystemTools::CXX_FILE_FORMAT: - setup.sources.push_back(absFile); - break; - case cmSystemTools::HEADER_FILE_FORMAT: - setup.headers.push_back(absFile); - break; - default: - break; - } - } } -static void SetupAutoTargetMoc(cmGeneratorTarget const* target, - std::string const& qtMajorVersion, - std::string const& config, - std::vector<std::string> const& configs, - AutogenSetup& setup) +static void SetupAutoTargetMoc(cmQtAutoGenDigest const& digest, + std::string const& configDefault, + std::vector<std::string> const& configsList, + cmQtAutoGenSetup& setup) { + cmGeneratorTarget const* target = digest.Target; cmLocalGenerator* localGen = target->GetLocalGenerator(); cmMakefile* makefile = target->Target->GetMakefile(); - AddDefinitionEscaped(makefile, "_moc_skip", setup.mocSkip); + AddDefinitionEscaped(makefile, "_moc_skip", setup.MocSkip); AddDefinitionEscaped(makefile, "_moc_options", GetSafeProperty(target, "AUTOMOC_MOC_OPTIONS")); AddDefinitionEscaped(makefile, "_moc_relaxed_mode", @@ -410,35 +363,50 @@ static void SetupAutoTargetMoc(cmGeneratorTarget const* target, AddDefinitionEscaped(makefile, "_moc_depend_filters", GetSafeProperty(target, "AUTOMOC_DEPEND_FILTERS")); - if (QtVersionGreaterOrEqual( - qtMajorVersion, GetQtMinorVersion(target, qtMajorVersion), 5, 8)) { + if (QtVersionGreaterOrEqual(digest.QtVersionMajor, digest.QtVersionMinor, 5, + 8)) { AddDefinitionEscaped( makefile, "_moc_predefs_cmd", makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_PREDEFINES_COMMAND")); } // Moc includes and compile definitions { - // Default settings - std::string incs; - std::string compileDefs; - GetCompileDefinitionsAndDirectories(target, config, incs, compileDefs); - AddDefinitionEscaped(makefile, "_moc_incs", incs); - AddDefinitionEscaped(makefile, "_moc_compile_defs", compileDefs); - - // Configuration specific settings - for (std::vector<std::string>::const_iterator li = configs.begin(); - li != configs.end(); ++li) { - std::string configIncs; - std::string configCompileDefs; - GetCompileDefinitionsAndDirectories(target, *li, configIncs, - configCompileDefs); - if (configIncs != incs) { - setup.configMocIncludes[*li] = configIncs; + auto GetIncludeDirs = [target, + localGen](std::string const& cfg) -> std::string { + // Get the include dirs for this target, without stripping the implicit + // include dirs off, see + // https://gitlab.kitware.com/cmake/cmake/issues/13667 + std::vector<std::string> includeDirs; + localGen->GetIncludeDirectories(includeDirs, target, "CXX", cfg, false); + return cmJoin(includeDirs, ";"); + }; + auto GetCompileDefinitions = + [target, localGen](std::string const& cfg) -> std::string { + std::set<std::string> defines; + localGen->AddCompileDefinitions(defines, target, cfg, "CXX"); + return cmJoin(defines, ";"); + }; + + // Default configuration settings + std::string const includeDirs = GetIncludeDirs(configDefault); + std::string const compileDefs = GetCompileDefinitions(configDefault); + // Other configuration settings + for (std::string const& cfg : configsList) { + { + std::string const configIncludeDirs = GetIncludeDirs(cfg); + if (configIncludeDirs != includeDirs) { + setup.ConfigMocIncludes[cfg] = configIncludeDirs; + } } - if (configCompileDefs != compileDefs) { - setup.configMocDefines[*li] = configCompileDefs; + { + std::string const configCompileDefs = GetCompileDefinitions(cfg); + if (configCompileDefs != compileDefs) { + setup.ConfigMocDefines[cfg] = configCompileDefs; + } } } + AddDefinitionEscaped(makefile, "_moc_include_dirs", includeDirs); + AddDefinitionEscaped(makefile, "_moc_compile_defs", compileDefs); } // Moc executable @@ -446,14 +414,14 @@ static void SetupAutoTargetMoc(cmGeneratorTarget const* target, std::string mocExec; std::string err; - if (qtMajorVersion == "5") { + if (digest.QtVersionMajor == "5") { cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt5::moc"); if (tgt != nullptr) { mocExec = SafeString(tgt->ImportedGetLocation("")); } else { err = "AUTOMOC: Qt5::moc target not found"; } - } else if (qtMajorVersion == "4") { + } else if (digest.QtVersionMajor == "4") { cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt4::moc"); if (tgt != nullptr) { mocExec = SafeString(tgt->ImportedGetLocation("")); @@ -473,36 +441,26 @@ static void SetupAutoTargetMoc(cmGeneratorTarget const* target, } } -static void UicGetOpts(cmGeneratorTarget const* target, - const std::string& config, std::string& optString) -{ - std::vector<std::string> opts; - target->GetAutoUicOptions(opts, config); - optString = cmJoin(opts, ";"); -} - -static void SetupAutoTargetUic(cmGeneratorTarget const* target, - std::string const& qtMajorVersion, +static void SetupAutoTargetUic(cmQtAutoGenDigest const& digest, std::string const& config, std::vector<std::string> const& configs, - AutogenSetup& setup) + cmQtAutoGenSetup& setup) { - cmLocalGenerator* localGen = target->GetLocalGenerator(); + cmGeneratorTarget const* target = digest.Target; cmMakefile* makefile = target->Target->GetMakefile(); - AddDefinitionEscaped(makefile, "_uic_skip", setup.uicSkip); + AddDefinitionEscaped(makefile, "_uic_skip", setup.UicSkip); // Uic search paths { std::vector<std::string> uicSearchPaths; { - const std::string usp = GetSafeProperty(target, "AUTOUIC_SEARCH_PATHS"); + std::string const usp = GetSafeProperty(target, "AUTOUIC_SEARCH_PATHS"); if (!usp.empty()) { cmSystemTools::ExpandListArgument(usp, uicSearchPaths); - const std::string srcDir = makefile->GetCurrentSourceDirectory(); - for (std::vector<std::string>::iterator it = uicSearchPaths.begin(); - it != uicSearchPaths.end(); ++it) { - *it = cmSystemTools::CollapseFullPath(*it, srcDir); + std::string const srcDir = makefile->GetCurrentSourceDirectory(); + for (std::string& path : uicSearchPaths) { + path = cmSystemTools::CollapseFullPath(path, srcDir); } } } @@ -510,44 +468,45 @@ static void SetupAutoTargetUic(cmGeneratorTarget const* target, } // Uic target options { + auto UicGetOpts = [target](std::string const& cfg) -> std::string { + std::vector<std::string> opts; + target->GetAutoUicOptions(opts, cfg); + return cmJoin(opts, ";"); + }; + // Default settings - std::string uicOpts; - UicGetOpts(target, config, uicOpts); + std::string const uicOpts = UicGetOpts(config); AddDefinitionEscaped(makefile, "_uic_target_options", uicOpts); // Configuration specific settings - for (std::vector<std::string>::const_iterator li = configs.begin(); - li != configs.end(); ++li) { - std::string configUicOpts; - UicGetOpts(target, *li, configUicOpts); + for (std::string const& cfg : configs) { + std::string const configUicOpts = UicGetOpts(cfg); if (configUicOpts != uicOpts) { - setup.configUicOptions[*li] = configUicOpts; + setup.ConfigUicOptions[cfg] = configUicOpts; } } } // Uic files options { std::vector<std::string> uiFileFiles; - std::vector<std::string> uiFileOptions; + std::vector<std::vector<std::string>> uiFileOptions; { - const std::string uiExt = "ui"; + std::string const uiExt = "ui"; const std::vector<cmSourceFile*>& srcFiles = makefile->GetSourceFiles(); - for (std::vector<cmSourceFile*>::const_iterator fit = srcFiles.begin(); - fit != srcFiles.end(); ++fit) { - cmSourceFile* sf = *fit; + for (cmSourceFile* sf : srcFiles) { // sf->GetExtension() is only valid after sf->GetFullPath() ... - const std::string& fPath = sf->GetFullPath(); + std::string const& fPath = sf->GetFullPath(); if (sf->GetExtension() == uiExt) { // Check if the files has uic options - std::string uicOpts = sf->GetProperty("AUTOUIC_OPTIONS"); + std::string const uicOpts = GetSafeProperty(sf, "AUTOUIC_OPTIONS"); if (!uicOpts.empty()) { - const std::string absFile = cmsys::SystemTools::GetRealPath(fPath); + std::string const absFile = cmSystemTools::GetRealPath(fPath); // Check if file isn't skipped - if (setup.uicSkip.count(absFile) == 0) { + if (setup.UicSkip.count(absFile) == 0) { uiFileFiles.push_back(absFile); - cmSystemTools::ReplaceString(uicOpts, ";", - cmQtAutoGeneratorCommon::listSep); - uiFileOptions.push_back(uicOpts); + std::vector<std::string> optsVec; + cmSystemTools::ExpandListArgument(uicOpts, optsVec); + uiFileOptions.push_back(std::move(optsVec)); } } } @@ -562,14 +521,15 @@ static void SetupAutoTargetUic(cmGeneratorTarget const* target, std::string err; std::string uicExec; - if (qtMajorVersion == "5") { + cmLocalGenerator* localGen = target->GetLocalGenerator(); + if (digest.QtVersionMajor == "5") { cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt5::uic"); if (tgt != nullptr) { uicExec = SafeString(tgt->ImportedGetLocation("")); } else { // Project does not use Qt5Widgets, but has AUTOUIC ON anyway } - } else if (qtMajorVersion == "4") { + } else if (digest.QtVersionMajor == "4") { cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt4::uic"); if (tgt != nullptr) { uicExec = SafeString(tgt->ImportedGetLocation("")); @@ -590,7 +550,7 @@ static void SetupAutoTargetUic(cmGeneratorTarget const* target, } static std::string RccGetExecutable(cmGeneratorTarget const* target, - const std::string& qtMajorVersion) + std::string const& qtMajorVersion) { std::string rccExec; std::string err; @@ -621,151 +581,67 @@ static std::string RccGetExecutable(cmGeneratorTarget const* target, return rccExec; } -static void RccMergeOptions(std::vector<std::string>& opts, - const std::vector<std::string>& fileOpts, - bool isQt5) -{ - static const char* valueOptions[] = { "name", "root", "compress", - "threshold" }; - std::vector<std::string> extraOpts; - for (std::vector<std::string>::const_iterator fit = fileOpts.begin(); - fit != fileOpts.end(); ++fit) { - std::vector<std::string>::iterator existingIt = - std::find(opts.begin(), opts.end(), *fit); - if (existingIt != opts.end()) { - const char* optName = fit->c_str(); - if (*optName == '-') { - ++optName; - if (isQt5 && *optName == '-') { - ++optName; - } - } - // Test if this is a value option and change the existing value - if ((optName != fit->c_str()) && - std::find_if(cmArrayBegin(valueOptions), cmArrayEnd(valueOptions), - cmStrCmp(optName)) != cmArrayEnd(valueOptions)) { - const std::vector<std::string>::iterator existValueIt(existingIt + 1); - const std::vector<std::string>::const_iterator fileValueIt(fit + 1); - if ((existValueIt != opts.end()) && (fileValueIt != fileOpts.end())) { - *existValueIt = *fileValueIt; - ++fit; - } - } - } else { - extraOpts.push_back(*fit); - } - } - opts.insert(opts.end(), extraOpts.begin(), extraOpts.end()); -} - -static void SetupAutoTargetRcc(cmGeneratorTarget const* target, - const std::string& qtMajorVersion, - const std::vector<cmSourceFile*>& srcFiles) +static void SetupAutoTargetRcc(cmQtAutoGenDigest const& digest) { - cmMakefile* makefile = target->Target->GetMakefile(); - const bool qtMajorVersion5 = (qtMajorVersion == "5"); - const std::string rccCommand = RccGetExecutable(target, qtMajorVersion); std::vector<std::string> rccFiles; - std::vector<std::string> rccInputs; - std::vector<std::string> rccFileFiles; - std::vector<std::string> rccFileOptions; - std::vector<std::string> rccOptionsTarget; - - cmSystemTools::ExpandListArgument(GetSafeProperty(target, "AUTORCC_OPTIONS"), - rccOptionsTarget); - - for (std::vector<cmSourceFile*>::const_iterator fileIt = srcFiles.begin(); - fileIt != srcFiles.end(); ++fileIt) { - cmSourceFile* sf = *fileIt; - // sf->GetExtension() is only valid after sf->GetFullPath() ... - const std::string& fPath = sf->GetFullPath(); - if ((sf->GetExtension() == "qrc") && - !sf->GetPropertyAsBool("SKIP_AUTOGEN") && - !sf->GetPropertyAsBool("SKIP_AUTORCC")) { - const std::string absFile = cmsys::SystemTools::GetRealPath(fPath); - // qrc file - rccFiles.push_back(absFile); - // qrc file entries - { - std::string entriesList = "{"; - // Read input file list only for non generated .qrc files. - if (!sf->GetPropertyAsBool("GENERATED")) { - std::string error; - std::vector<std::string> files; - if (cmQtAutoGeneratorCommon::RccListInputs( - qtMajorVersion, rccCommand, absFile, files, &error)) { - entriesList += cmJoin(files, cmQtAutoGeneratorCommon::listSep); - } else { - cmSystemTools::Error(error.c_str()); - } - } - entriesList += "}"; - rccInputs.push_back(entriesList); - } - // rcc options for this qrc file - { - // Merged target and file options - std::vector<std::string> rccOptions(rccOptionsTarget); - if (const char* prop = sf->GetProperty("AUTORCC_OPTIONS")) { - std::vector<std::string> optsVec; - cmSystemTools::ExpandListArgument(prop, optsVec); - RccMergeOptions(rccOptions, optsVec, qtMajorVersion5); - } - // Only store non empty options lists - if (!rccOptions.empty()) { - rccFileFiles.push_back(absFile); - rccFileOptions.push_back( - cmJoin(rccOptions, cmQtAutoGeneratorCommon::listSep)); - } - } - } + std::vector<std::string> rccBuilds; + std::vector<std::vector<std::string>> rccOptions; + std::vector<std::vector<std::string>> rccInputs; + + for (cmQtAutoGenDigestQrc const& qrcDigest : digest.Qrcs) { + rccFiles.push_back(qrcDigest.QrcFile); + rccBuilds.push_back(qrcDigest.RccFile); + rccOptions.push_back(qrcDigest.Options); + rccInputs.push_back(qrcDigest.Resources); } - AddDefinitionEscaped(makefile, "_qt_rcc_executable", rccCommand); + cmMakefile* makefile = digest.Target->Target->GetMakefile(); + AddDefinitionEscaped(makefile, "_qt_rcc_executable", + RccGetExecutable(digest.Target, digest.QtVersionMajor)); AddDefinitionEscaped(makefile, "_rcc_files", rccFiles); + AddDefinitionEscaped(makefile, "_rcc_builds", rccBuilds); + AddDefinitionEscaped(makefile, "_rcc_options", rccOptions); AddDefinitionEscaped(makefile, "_rcc_inputs", rccInputs); - AddDefinitionEscaped(makefile, "_rcc_options_files", rccFileFiles); - AddDefinitionEscaped(makefile, "_rcc_options_options", rccFileOptions); } void cmQtAutoGeneratorInitializer::InitializeAutogenTarget( - cmLocalGenerator* localGen, cmGeneratorTarget* target) + cmQtAutoGenDigest& digest) { + cmGeneratorTarget* target = digest.Target; cmMakefile* makefile = target->Target->GetMakefile(); + cmLocalGenerator* localGen = target->GetLocalGenerator(); cmGlobalGenerator* globalGen = localGen->GetGlobalGenerator(); - // Create a custom target for running generators at buildtime - const bool mocEnabled = target->GetPropertyAsBool("AUTOMOC"); - const bool uicEnabled = target->GetPropertyAsBool("AUTOUIC"); - const bool rccEnabled = target->GetPropertyAsBool("AUTORCC"); - const bool multiConfig = AutogenMultiConfig(globalGen); - const std::string autogenTargetName = GetAutogenTargetName(target); - const std::string autogenBuildDir = GetAutogenTargetBuildDir(target); - const std::string workingDirectory = + std::string const autogenTargetName = GetAutogenTargetName(target); + std::string const autogenBuildDir = GetAutogenTargetBuildDir(target); + std::string const workingDirectory = cmSystemTools::CollapseFullPath("", makefile->GetCurrentBinaryDirectory()); - const std::vector<std::string> suffixes = GetConfigurationSuffixes(makefile); - std::set<std::string> autogenDependsSet; - std::vector<std::string> autogenProvides; - bool usePRE_BUILD = false; - if (globalGen->GetName().find("Visual Studio") != std::string::npos) { - // Under VS use a PRE_BUILD event instead of a separate target to - // reduce the number of targets loaded into the IDE. - // This also works around a VS 11 bug that may skip updating the target: - // https://connect.microsoft.com/VisualStudio/feedback/details/769495 - usePRE_BUILD = true; - } + cmQtAutoGen::MultiConfig const multiConfig = AutogenMultiConfig(globalGen); + std::string configDefault; + std::vector<std::string> configsList; + GetConfigs(makefile, configDefault, configsList); + + std::set<std::string> autogenDependFiles; + std::set<std::string> autogenDependTargets; + std::vector<std::string> autogenProvides; // Remove build directories on cleanup AddCleanFile(makefile, autogenBuildDir); - // Remove old settings on cleanup { std::string base = GetAutogenTargetFilesDir(target); base += "/AutogenOldSettings"; - for (std::vector<std::string>::const_iterator it = suffixes.begin(); - it != suffixes.end(); ++it) { - AddCleanFile(makefile, base + *it + ".cmake"); + if (multiConfig == cmQtAutoGen::SINGLE) { + AddCleanFile(makefile, base.append(".cmake")); + } else { + for (std::string const& cfg : configsList) { + std::string filename = base; + filename += "_"; + filename += cfg; + filename += ".cmake"; + AddCleanFile(makefile, filename); + } } } @@ -785,13 +661,13 @@ void cmQtAutoGeneratorInitializer::InitializeAutogenTarget( std::string autogenComment; { std::vector<std::string> toolNames; - if (mocEnabled) { + if (digest.MocEnabled) { toolNames.push_back("MOC"); } - if (uicEnabled) { + if (digest.UicEnabled) { toolNames.push_back("UIC"); } - if (rccEnabled) { + if (digest.RccEnabled) { toolNames.push_back("RCC"); } @@ -808,91 +684,84 @@ void cmQtAutoGeneratorInitializer::InitializeAutogenTarget( } // Add moc compilation to generated files list - if (mocEnabled) { - const std::string mocsComp = autogenBuildDir + "/mocs_compilation.cpp"; - AddGeneratedSource(target, mocsComp, cmQtAutoGeneratorCommon::MOC); - autogenProvides.push_back(mocsComp); + if (digest.MocEnabled) { + std::string const mocsComp = autogenBuildDir + "/mocs_compilation.cpp"; + auto files = AddGeneratedSource(target, mocsComp, multiConfig, configsList, + cmQtAutoGen::MOC); + for (std::string& file : files) { + autogenProvides.push_back(std::move(file)); + } } // Add autogen includes directory to the origin target INCLUDE_DIRECTORIES - if (mocEnabled || uicEnabled) { + if (digest.MocEnabled || digest.UicEnabled) { std::string includeDir = autogenBuildDir + "/include"; - if (multiConfig) { + if (multiConfig != cmQtAutoGen::SINGLE) { includeDir += "_$<CONFIG>"; } target->AddIncludeDirectory(includeDir, true); } - // Add user defined autogen target dependencies - { - const std::string deps = GetSafeProperty(target, "AUTOGEN_TARGET_DEPENDS"); - if (!deps.empty()) { - std::vector<std::string> extraDepends; - cmSystemTools::ExpandListArgument(deps, extraDepends); - autogenDependsSet.insert(extraDepends.begin(), extraDepends.end()); - } - } - // Add utility target dependencies to the autogen dependencies - { - const std::set<std::string>& utils = target->Target->GetUtilities(); - for (std::set<std::string>::const_iterator it = utils.begin(); - it != utils.end(); ++it) { - const std::string& targetName = *it; - if (makefile->FindTargetToUse(targetName) != nullptr) { - autogenDependsSet.insert(targetName); - } - } - } - // Add link library target dependencies to the autogen dependencies - { - const cmTarget::LinkLibraryVectorType& libVec = - target->Target->GetOriginalLinkLibraries(); - for (cmTarget::LinkLibraryVectorType::const_iterator it = libVec.begin(); - it != libVec.end(); ++it) { - const std::string& libName = it->first; - if (makefile->FindTargetToUse(libName) != nullptr) { - autogenDependsSet.insert(libName); - } - } - } - // Extract relevant source files std::vector<std::string> generatedSources; - std::vector<std::pair<std::string, bool> > qrcSources; + std::vector<std::string> generatedHeaders; { - const std::string qrcExt = "qrc"; + std::string const qrcExt = "qrc"; std::vector<cmSourceFile*> srcFiles; target->GetConfigCommonSourceFiles(srcFiles); - for (std::vector<cmSourceFile*>::const_iterator fileIt = srcFiles.begin(); - fileIt != srcFiles.end(); ++fileIt) { - cmSourceFile* sf = *fileIt; + for (cmSourceFile* sf : srcFiles) { if (sf->GetPropertyAsBool("SKIP_AUTOGEN")) { continue; } // sf->GetExtension() is only valid after sf->GetFullPath() ... - const std::string& fPath = sf->GetFullPath(); - const std::string& ext = sf->GetExtension(); + std::string const& fPath = sf->GetFullPath(); + std::string const& ext = sf->GetExtension(); // Register generated files that will be scanned by moc or uic - if (mocEnabled || uicEnabled) { - const cmSystemTools::FileFormat fileType = + if (digest.MocEnabled || digest.UicEnabled) { + cmSystemTools::FileFormat const fileType = cmSystemTools::GetFileFormat(ext.c_str()); if ((fileType == cmSystemTools::CXX_FILE_FORMAT) || (fileType == cmSystemTools::HEADER_FILE_FORMAT)) { - if (sf->GetPropertyAsBool("GENERATED")) { - if ((mocEnabled && !sf->GetPropertyAsBool("SKIP_AUTOMOC")) || - (uicEnabled && !sf->GetPropertyAsBool("SKIP_AUTOUIC"))) { - generatedSources.push_back( - cmsys::SystemTools::GetRealPath(fPath)); + std::string const absPath = cmSystemTools::GetRealPath(fPath); + if ((digest.MocEnabled && !sf->GetPropertyAsBool("SKIP_AUTOMOC")) || + (digest.UicEnabled && !sf->GetPropertyAsBool("SKIP_AUTOUIC"))) { + // Register source + const bool generated = sf->GetPropertyAsBool("GENERATED"); + if (fileType == cmSystemTools::HEADER_FILE_FORMAT) { + if (generated) { + generatedHeaders.push_back(absPath); + } else { + digest.Headers.push_back(absPath); + } + } else { + if (generated) { + generatedSources.push_back(absPath); + } else { + digest.Sources.push_back(absPath); + } } } } } // Register rcc enabled files - if (rccEnabled && (ext == qrcExt) && + if (digest.RccEnabled && (ext == qrcExt) && !sf->GetPropertyAsBool("SKIP_AUTORCC")) { - qrcSources.push_back( - std::pair<std::string, bool>(cmsys::SystemTools::GetRealPath(fPath), - sf->GetPropertyAsBool("GENERATED"))); + // Register qrc file + { + cmQtAutoGenDigestQrc qrcDigest; + qrcDigest.QrcFile = cmSystemTools::GetRealPath(fPath); + qrcDigest.QrcName = + cmSystemTools::GetFilenameWithoutLastExtension(qrcDigest.QrcFile); + qrcDigest.Generated = sf->GetPropertyAsBool("GENERATED"); + // RCC options + { + std::string const opts = GetSafeProperty(sf, "AUTORCC_OPTIONS"); + if (!opts.empty()) { + cmSystemTools::ExpandListArgument(opts, qrcDigest.Options); + } + } + digest.Qrcs.push_back(std::move(qrcDigest)); + } } } // cmGeneratorTarget::GetConfigCommonSourceFiles computes the target's @@ -902,104 +771,247 @@ void cmQtAutoGeneratorInitializer::InitializeAutogenTarget( target->ClearSourcesCache(); } - if (!generatedSources.empty()) { - for (std::vector<std::string>::const_iterator it = - generatedSources.begin(); - it != generatedSources.end(); ++it) { - autogenDependsSet.insert(*it); + // Process GENERATED sources and headers + if (!generatedSources.empty() || !generatedHeaders.empty()) { + // Check status of policy CMP0071 + bool policyAccept = false; + bool policyWarn = false; + cmPolicies::PolicyStatus const CMP0071_status = + target->Makefile->GetPolicyStatus(cmPolicies::CMP0071); + switch (CMP0071_status) { + case cmPolicies::WARN: + policyWarn = true; + CM_FALLTHROUGH; + case cmPolicies::OLD: + // Ignore GENERATED file + break; + case cmPolicies::REQUIRED_IF_USED: + case cmPolicies::REQUIRED_ALWAYS: + case cmPolicies::NEW: + // Process GENERATED file + policyAccept = true; + break; } - } - - if (!qrcSources.empty()) { - const std::string qtMajorVersion = GetQtMajorVersion(target); - const std::string rccCommand = RccGetExecutable(target, qtMajorVersion); - const cmFilePathChecksum fpathCheckSum(makefile); - for (std::vector<std::pair<std::string, bool> >::const_iterator it = - qrcSources.begin(); - it != qrcSources.end(); ++it) { - const std::string& absFile = it->first; - // Compose rcc output file name + if (policyAccept) { + // Accept GENERATED sources + for (std::string const& absFile : generatedHeaders) { + digest.Headers.push_back(absFile); + autogenDependFiles.insert(absFile); + } + for (std::string const& absFile : generatedSources) { + digest.Sources.push_back(absFile); + autogenDependFiles.insert(absFile); + } + } else { + if (policyWarn) { + std::string msg; + msg += cmPolicies::GetPolicyWarning(cmPolicies::CMP0071); + msg += "\n"; + std::string tools; + if (digest.MocEnabled) { + tools += "AUTOMOC"; + } + if (digest.UicEnabled) { + if (!tools.empty()) { + tools += ","; + } + tools += "AUTOUIC"; + } + if (!generatedHeaders.empty()) { + msg.append(tools).append(": Ignoring GENERATED header file(s):\n"); + for (std::string const& absFile : generatedHeaders) { + msg.append(" ").append(cmQtAutoGen::Quoted(absFile)).append("\n"); + } + } + if (!generatedSources.empty()) { + msg.append(tools).append(": Ignoring GENERATED source file(s):\n"); + for (std::string const& absFile : generatedSources) { + msg.append(" ").append(cmQtAutoGen::Quoted(absFile)).append("\n"); + } + } + makefile->IssueMessage(cmake::AUTHOR_WARNING, msg); + } + } + } + // Sort headers and sources + std::sort(digest.Headers.begin(), digest.Headers.end()); + std::sort(digest.Sources.begin(), digest.Sources.end()); + + // Process qrc files + if (!digest.Qrcs.empty()) { + const bool QtV5 = (digest.QtVersionMajor == "5"); + std::string const rcc = RccGetExecutable(target, digest.QtVersionMajor); + // Target rcc options + std::vector<std::string> optionsTarget; + cmSystemTools::ExpandListArgument( + GetSafeProperty(target, "AUTORCC_OPTIONS"), optionsTarget); + + // Check if file name is unique + for (cmQtAutoGenDigestQrc& qrcDigest : digest.Qrcs) { + qrcDigest.Unique = true; + for (cmQtAutoGenDigestQrc const& qrcDig2 : digest.Qrcs) { + if ((&qrcDigest != &qrcDig2) && + (qrcDigest.QrcName == qrcDig2.QrcName)) { + qrcDigest.Unique = false; + break; + } + } + } + // Path checksum + { + cmFilePathChecksum const fpathCheckSum(makefile); + for (cmQtAutoGenDigestQrc& qrcDigest : digest.Qrcs) { + qrcDigest.PathChecksum = fpathCheckSum.getPart(qrcDigest.QrcFile); + // RCC output file name + std::string rccFile = autogenBuildDir + "/"; + rccFile += qrcDigest.PathChecksum; + rccFile += "/qrc_"; + rccFile += qrcDigest.QrcName; + rccFile += ".cpp"; + qrcDigest.RccFile = std::move(rccFile); + } + } + // RCC options + for (cmQtAutoGenDigestQrc& qrcDigest : digest.Qrcs) { + // Target options + std::vector<std::string> opts = optionsTarget; + // Merge computed "-name XYZ" option { - std::string rccBuildFile = autogenBuildDir + "/"; - rccBuildFile += fpathCheckSum.getPart(absFile); - rccBuildFile += "/qrc_"; - rccBuildFile += - cmsys::SystemTools::GetFilenameWithoutLastExtension(absFile); - rccBuildFile += ".cpp"; - - // Register rcc ouput file as generated - AddGeneratedSource(target, rccBuildFile, cmQtAutoGeneratorCommon::RCC); - // Register rcc ouput file as generated by the _autogen target - autogenProvides.push_back(rccBuildFile); + std::string name = qrcDigest.QrcName; + // Replace '-' with '_'. The former is not valid for symbol names. + std::replace(name.begin(), name.end(), '-', '_'); + if (!qrcDigest.Unique) { + name += "_"; + name += qrcDigest.PathChecksum; + } + std::vector<std::string> nameOpts; + nameOpts.emplace_back("-name"); + nameOpts.emplace_back(std::move(name)); + cmQtAutoGen::RccMergeOptions(opts, nameOpts, QtV5); } - - if (it->second) { - // Add generated qrc file to the dependencies - autogenDependsSet.insert(absFile); + // Merge file option + cmQtAutoGen::RccMergeOptions(opts, qrcDigest.Options, QtV5); + qrcDigest.Options = std::move(opts); + } + for (cmQtAutoGenDigestQrc& qrcDigest : digest.Qrcs) { + // Register file at target + { + auto files = AddGeneratedSource(target, qrcDigest.RccFile, multiConfig, + configsList, cmQtAutoGen::RCC); + for (std::string& file : files) { + autogenProvides.push_back(std::move(file)); + } + } + // Dependencies + if (qrcDigest.Generated) { + // Add the GENERATED .qrc file to the dependencies + autogenDependFiles.insert(qrcDigest.QrcFile); } else { - // Run cmake again when .qrc file changes - makefile->AddCMakeDependFile(absFile); - // Add the qrc input files to the dependencies + // Add the resource files to the dependencies { std::string error; - std::vector<std::string> extraDepends; - if (cmQtAutoGeneratorCommon::RccListInputs( - qtMajorVersion, rccCommand, absFile, extraDepends, &error)) { - autogenDependsSet.insert(extraDepends.begin(), extraDepends.end()); + if (cmQtAutoGen::RccListInputs(digest.QtVersionMajor, rcc, + qrcDigest.QrcFile, + qrcDigest.Resources, &error)) { + for (std::string const& fileName : qrcDigest.Resources) { + autogenDependFiles.insert(fileName); + } } else { cmSystemTools::Error(error.c_str()); } } + // Run cmake again when .qrc file changes + makefile->AddCMakeDependFile(qrcDigest.QrcFile); } } } - // Convert std::set to std::vector - const std::vector<std::string> autogenDepends(autogenDependsSet.begin(), - autogenDependsSet.end()); - // Disable PRE_BUILD on demand - if (usePRE_BUILD) { - if (!generatedSources.empty() || !qrcSources.empty()) { - // - Cannot use PRE_BUILD with generated files - // - Cannot use PRE_BUILD because the resource files themselves - // may not be sources within the target so VS may not know the - // target needs to re-build at all. - usePRE_BUILD = false; - } - if (usePRE_BUILD) { - // If the autogen target depends on an other target don't use PRE_BUILD - for (std::vector<std::string>::const_iterator it = - autogenDepends.begin(); - it != autogenDepends.end(); ++it) { - if (makefile->FindTargetToUse(*it) != nullptr) { - usePRE_BUILD = false; - break; + // Add user defined autogen target dependencies + { + std::string const deps = GetSafeProperty(target, "AUTOGEN_TARGET_DEPENDS"); + if (!deps.empty()) { + std::vector<std::string> extraDeps; + cmSystemTools::ExpandListArgument(deps, extraDeps); + for (std::string const& depName : extraDeps) { + // Allow target and file dependencies + auto* depTarget = makefile->FindTargetToUse(depName); + if (depTarget != nullptr) { + autogenDependTargets.insert(depTarget->GetName()); + } else { + autogenDependFiles.insert(depName); } } } } + + // Use PRE_BUILD on demand + bool usePRE_BUILD = false; + if (globalGen->GetName().find("Visual Studio") != std::string::npos) { + // Under VS use a PRE_BUILD event instead of a separate target to + // reduce the number of targets loaded into the IDE. + // This also works around a VS 11 bug that may skip updating the target: + // https://connect.microsoft.com/VisualStudio/feedback/details/769495 + usePRE_BUILD = true; + } + // Disable PRE_BUILD in some cases if (usePRE_BUILD) { + // Cannot use PRE_BUILD with file depends + if (!autogenDependFiles.empty()) { + usePRE_BUILD = false; + } + } + // Create the autogen target/command + if (usePRE_BUILD) { + // Add additional autogen target dependencies to origin target + for (std::string const& depTarget : autogenDependTargets) { + target->Target->AddUtility(depTarget, makefile); + } + // Add the pre-build command directly to bypass the OBJECT_LIBRARY // rejection in cmMakefile::AddCustomCommandToTarget because we know // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case. - std::vector<std::string> no_output; - cmCustomCommand cc(makefile, no_output, autogenProvides, autogenDepends, + // + // PRE_BUILD does not support file dependencies! + const std::vector<std::string> no_output; + const std::vector<std::string> no_deps; + cmCustomCommand cc(makefile, no_output, autogenProvides, no_deps, commandLines, autogenComment.c_str(), workingDirectory.c_str()); cc.SetEscapeOldStyle(false); cc.SetEscapeAllowMakeVars(true); target->Target->AddPreBuildCommand(cc); } else { + + // Add utility target dependencies to the autogen target dependencies + for (std::string const& depTarget : target->Target->GetUtilities()) { + autogenDependTargets.insert(depTarget); + } + // Add link library target dependencies to the autogen target dependencies + for (const auto& item : target->Target->GetOriginalLinkLibraries()) { + if (makefile->FindTargetToUse(item.first) != nullptr) { + autogenDependTargets.insert(item.first); + } + } + + // Convert file dependencies std::set to std::vector + const std::vector<std::string> autogenDepends(autogenDependFiles.begin(), + autogenDependFiles.end()); + // Create autogen target cmTarget* autogenTarget = makefile->AddUtilityCommand( autogenTargetName, true, workingDirectory.c_str(), /*byproducts=*/autogenProvides, autogenDepends, commandLines, false, autogenComment.c_str()); - + // Create autogen generator target localGen->AddGeneratorTarget( new cmGeneratorTarget(autogenTarget, localGen)); - // Set autogen target FOLDER + // Add additional autogen target dependencies to autogen target + for (std::string const& depTarget : autogenDependTargets) { + autogenTarget->AddUtility(depTarget, makefile); + } + + // Set FOLDER property in autogen target { const char* autogenFolder = makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER"); @@ -1009,7 +1021,7 @@ void cmQtAutoGeneratorInitializer::InitializeAutogenTarget( } // Inherit FOLDER property from target (#13688) if (autogenFolder == nullptr) { - autogenFolder = target->Target->GetProperty("FOLDER"); + autogenFolder = SafeString(target->Target->GetProperty("FOLDER")); } if ((autogenFolder != nullptr) && (*autogenFolder != '\0')) { autogenTarget->SetProperty("FOLDER", autogenFolder); @@ -1017,77 +1029,76 @@ void cmQtAutoGeneratorInitializer::InitializeAutogenTarget( } // Add autogen target to the origin target dependencies - target->Target->AddUtility(autogenTargetName); + target->Target->AddUtility(autogenTargetName, makefile); } } void cmQtAutoGeneratorInitializer::SetupAutoGenerateTarget( - cmGeneratorTarget const* target) + cmQtAutoGenDigest const& digest) { + cmGeneratorTarget const* target = digest.Target; cmMakefile* makefile = target->Target->GetMakefile(); + cmQtAutoGen::MultiConfig const multiConfig = + AutogenMultiConfig(target->GetGlobalGenerator()); // forget the variables added here afterwards again: cmMakefile::ScopePushPop varScope(makefile); static_cast<void>(varScope); - // Get configurations - std::string config; - const std::vector<std::string> configs(GetConfigurations(makefile, &config)); - - // Configuration suffixes - std::map<std::string, std::string> configSuffix; - if (AutogenMultiConfig(target->GetGlobalGenerator())) { - for (std::vector<std::string>::const_iterator it = configs.begin(); - it != configs.end(); ++it) { - configSuffix[*it] = "_" + *it; + // Configurations + std::string configDefault; + std::vector<std::string> configsList; + std::map<std::string, std::string> configSuffixes; + { + configDefault = makefile->GetConfigurations(configsList); + if (configsList.empty()) { + configsList.push_back(""); } } + for (std::string const& cfg : configsList) { + configSuffixes[cfg] = "_" + cfg; + } // Configurations settings buffers - AutogenSetup setup; + cmQtAutoGenSetup setup; // Basic setup + AddDefinitionEscaped(makefile, "_multi_config", + cmQtAutoGen::MultiConfigName(multiConfig)); + AddDefinitionEscaped(makefile, "_build_dir", + GetAutogenTargetBuildDir(target)); + AddDefinitionEscaped(makefile, "_sources", digest.Sources); + AddDefinitionEscaped(makefile, "_headers", digest.Headers); + AddDefinitionEscaped(makefile, "_qt_version_major", digest.QtVersionMajor); + AddDefinitionEscaped(makefile, "_qt_version_minor", digest.QtVersionMinor); { - const bool mocEnabled = target->GetPropertyAsBool("AUTOMOC"); - const bool uicEnabled = target->GetPropertyAsBool("AUTOUIC"); - const bool rccEnabled = target->GetPropertyAsBool("AUTORCC"); - const std::string qtMajorVersion = GetQtMajorVersion(target); - { - std::vector<cmSourceFile*> srcFiles; - target->GetConfigCommonSourceFiles(srcFiles); - if (mocEnabled || uicEnabled) { - SetupAcquireScanFiles(target, mocEnabled, uicEnabled, srcFiles, setup); - if (mocEnabled) { - SetupAutoTargetMoc(target, qtMajorVersion, config, configs, setup); - } - if (uicEnabled) { - SetupAutoTargetUic(target, qtMajorVersion, config, configs, setup); - } + if (digest.MocEnabled || digest.UicEnabled) { + SetupAcquireSkipFiles(digest, setup); + if (digest.MocEnabled) { + SetupAutoTargetMoc(digest, configDefault, configsList, setup); } - if (rccEnabled) { - SetupAutoTargetRcc(target, qtMajorVersion, srcFiles); + if (digest.UicEnabled) { + SetupAutoTargetUic(digest, configDefault, configsList, setup); } } - - AddDefinitionEscaped(makefile, "_build_dir", - GetAutogenTargetBuildDir(target)); - AddDefinitionEscaped(makefile, "_qt_version_major", qtMajorVersion); - AddDefinitionEscaped(makefile, "_sources", setup.sources); - AddDefinitionEscaped(makefile, "_headers", setup.headers); + if (digest.RccEnabled) { + SetupAutoTargetRcc(digest); + } } // Generate info file - std::string infoFile = GetAutogenTargetFilesDir(target); - infoFile += "/AutogenInfo.cmake"; { - std::string inf = cmSystemTools::GetCMakeRoot(); - inf += "/Modules/AutogenInfo.cmake.in"; - makefile->ConfigureFile(inf.c_str(), infoFile.c_str(), false, true, false); - } + std::string infoFile = GetAutogenTargetFilesDir(target); + infoFile += "/AutogenInfo.cmake"; + { + std::string infoFileIn = cmSystemTools::GetCMakeRoot(); + infoFileIn += "/Modules/AutogenInfo.cmake.in"; + makefile->ConfigureFile(infoFileIn.c_str(), infoFile.c_str(), false, + true, false); + } - // Append custom definitions to info file on demand - if (!configSuffix.empty() || !setup.configMocDefines.empty() || - !setup.configMocIncludes.empty() || !setup.configUicOptions.empty()) { + // Append custom definitions to info file + // -------------------------------------- // Ensure we have write permission in case .in was read-only. mode_t perm = 0; @@ -1104,39 +1115,22 @@ void cmQtAutoGeneratorInitializer::SetupAutoGenerateTarget( // Open and write file cmsys::ofstream ofs(infoFile.c_str(), std::ios::app); if (ofs) { - ofs << "# Configuration specific options\n"; - for (std::map<std::string, std::string>::iterator - it = configSuffix.begin(), - end = configSuffix.end(); - it != end; ++it) { - ofs << "set(AM_CONFIG_SUFFIX_" << it->first << " " - << cmOutputConverter::EscapeForCMake(it->second) << ")\n"; - } - for (std::map<std::string, std::string>::iterator - it = setup.configMocDefines.begin(), - end = setup.configMocDefines.end(); - it != end; ++it) { - ofs << "set(AM_MOC_DEFINITIONS_" << it->first << " " - << cmOutputConverter::EscapeForCMake(it->second) << ")\n"; - } - for (std::map<std::string, std::string>::iterator - it = setup.configMocIncludes.begin(), - end = setup.configMocIncludes.end(); - it != end; ++it) { - ofs << "set(AM_MOC_INCLUDES_" << it->first << " " - << cmOutputConverter::EscapeForCMake(it->second) << ")\n"; - } - for (std::map<std::string, std::string>::iterator - it = setup.configUicOptions.begin(), - end = setup.configUicOptions.end(); - it != end; ++it) { - ofs << "set(AM_UIC_TARGET_OPTIONS_" << it->first << " " - << cmOutputConverter::EscapeForCMake(it->second) << ")\n"; - } + auto OfsWriteMap = [&ofs]( + const char* key, std::map<std::string, std::string> const& map) { + for (auto const& item : map) { + ofs << "set(" << key << "_" << item.first << " " + << cmOutputConverter::EscapeForCMake(item.second) << ")\n"; + } + }; + ofs << "# Configurations options\n"; + OfsWriteMap("AM_CONFIG_SUFFIX", configSuffixes); + OfsWriteMap("AM_MOC_DEFINITIONS", setup.ConfigMocDefines); + OfsWriteMap("AM_MOC_INCLUDES", setup.ConfigMocIncludes); + OfsWriteMap("AM_UIC_TARGET_OPTIONS", setup.ConfigUicOptions); } else { // File open error std::string error = "Internal CMake error when trying to open file: "; - error += cmQtAutoGeneratorCommon::Quoted(infoFile); + error += cmQtAutoGen::Quoted(infoFile); error += " for writing."; cmSystemTools::Error(error.c_str()); } diff --git a/Source/cmQtAutoGeneratorInitializer.h b/Source/cmQtAutoGeneratorInitializer.h index 48ae70e..b8a5ae4 100644 --- a/Source/cmQtAutoGeneratorInitializer.h +++ b/Source/cmQtAutoGeneratorInitializer.h @@ -4,16 +4,21 @@ #define cmQtAutoGeneratorInitializer_h #include "cmConfigure.h" // IWYU pragma: keep +#include "cmQtAutoGenDigest.h" + +#include <string> class cmGeneratorTarget; -class cmLocalGenerator; class cmQtAutoGeneratorInitializer { public: - static void InitializeAutogenTarget(cmLocalGenerator* localGen, - cmGeneratorTarget* target); - static void SetupAutoGenerateTarget(cmGeneratorTarget const* target); + static std::string GetQtMajorVersion(cmGeneratorTarget const* target); + static std::string GetQtMinorVersion(cmGeneratorTarget const* target, + std::string const& qtVersionMajor); + + static void InitializeAutogenTarget(cmQtAutoGenDigest& digest); + static void SetupAutoGenerateTarget(cmQtAutoGenDigest const& digest); }; #endif diff --git a/Source/cmQtAutoGenerators.cxx b/Source/cmQtAutoGenerators.cxx index e51033a..bd0fb9a 100644 --- a/Source/cmQtAutoGenerators.cxx +++ b/Source/cmQtAutoGenerators.cxx @@ -1,15 +1,15 @@ /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ +#include "cmQtAutoGen.h" #include "cmQtAutoGenerators.h" -#include "cmQtAutoGeneratorCommon.h" #include "cmsys/FStream.hxx" #include "cmsys/Terminal.h" #include <algorithm> -#include <assert.h> +#include <array> #include <list> +#include <memory> #include <sstream> -#include <stdlib.h> #include <string.h> #include <utility> @@ -22,7 +22,6 @@ #include "cmStateDirectory.h" #include "cmStateSnapshot.h" #include "cmSystemTools.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" #if defined(__APPLE__) @@ -37,252 +36,124 @@ static const char* SettingsKeyRcc = "AM_RCC_SETTINGS_HASH"; // -- Static functions -inline static std::string Quoted(const std::string& text) +static std::string HeadLine(std::string const& title) { - return cmQtAutoGeneratorCommon::Quoted(text); + std::string head = title; + head += '\n'; + head.append(head.size() - 1, '-'); + head += '\n'; + return head; } -static std::string QuotedCommand(const std::vector<std::string>& command) +static std::string QuotedCommand(std::vector<std::string> const& command) { std::string res; - for (std::vector<std::string>::const_iterator cit = command.begin(); - cit != command.end(); ++cit) { + for (std::string const& item : command) { if (!res.empty()) { res.push_back(' '); } - const std::string cesc = Quoted(*cit); - if (cit->empty() || (cesc.size() > (cit->size() + 2)) || + std::string const cesc = cmQtAutoGen::Quoted(item); + if (item.empty() || (cesc.size() > (item.size() + 2)) || (cesc.find(' ') != std::string::npos)) { res += cesc; } else { - res += *cit; + res += item; } } return res; } -static void InfoGet(cmMakefile* makefile, const char* key, std::string& value) +static std::string SubDirPrefix(std::string const& fileName) { - value = makefile->GetSafeDefinition(key); -} - -static void InfoGet(cmMakefile* makefile, const char* key, bool& value) -{ - value = makefile->IsOn(key); -} - -static void InfoGet(cmMakefile* makefile, const char* key, - std::vector<std::string>& list) -{ - cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition(key), list); -} - -static void InfoGetConfig(cmMakefile* makefile, const char* key, - const std::string& config, std::string& value) -{ - const char* valueConf = nullptr; - { - std::string keyConf = key; - if (!config.empty()) { - keyConf += "_"; - keyConf += config; - } - valueConf = makefile->GetDefinition(keyConf); - } - if (valueConf == nullptr) { - valueConf = makefile->GetSafeDefinition(key); - } - value = valueConf; -} - -static void InfoGetConfig(cmMakefile* makefile, const char* key, - const std::string& config, - std::vector<std::string>& list) -{ - std::string value; - InfoGetConfig(makefile, key, config, value); - cmSystemTools::ExpandListArgument(value, list); -} - -inline static bool SettingsMatch(cmMakefile* makefile, const char* key, - const std::string& value) -{ - return (value == makefile->GetSafeDefinition(key)); -} - -static void SettingAppend(std::string& str, const char* key, - const std::string& value) -{ - if (!value.empty()) { - str += "set("; - str += key; - str += " "; - str += cmOutputConverter::EscapeForCMake(value); - str += ")\n"; - } -} - -static std::string SubDirPrefix(const std::string& fileName) -{ - std::string res(cmsys::SystemTools::GetFilenamePath(fileName)); + std::string res(cmSystemTools::GetFilenamePath(fileName)); if (!res.empty()) { res += '/'; } return res; } -static bool FileNameIsUnique(const std::string& filePath, - const std::map<std::string, std::string>& fileMap) -{ - size_t count(0); - const std::string fileName = cmsys::SystemTools::GetFilenameName(filePath); - for (std::map<std::string, std::string>::const_iterator si = fileMap.begin(); - si != fileMap.end(); ++si) { - if (cmsys::SystemTools::GetFilenameName(si->first) == fileName) { - ++count; - if (count > 1) { - return false; - } - } - } - return true; -} - -static bool ReadAll(std::string& content, const std::string& filename) +static bool ReadFile(std::string& content, std::string const& filename, + std::string* error = nullptr) { bool success = false; - { - cmsys::ifstream ifs(filename.c_str()); + if (cmSystemTools::FileExists(filename)) { + std::size_t const length = cmSystemTools::FileLength(filename); + cmsys::ifstream ifs(filename.c_str(), (std::ios::in | std::ios::binary)); if (ifs) { - std::ostringstream osst; - osst << ifs.rdbuf(); - content = osst.str(); - success = true; + content.resize(length); + ifs.read(&content.front(), content.size()); + if (ifs) { + success = true; + } else { + content.clear(); + if (error != nullptr) { + error->append("Reading from the file failed."); + } + } + } else if (error != nullptr) { + error->append("Opening the file for reading failed."); } + } else if (error != nullptr) { + error->append("The file does not exist."); } return success; } /** - * @brief Tests if buildFile doesn't exist or is older than sourceFile - * @return True if buildFile doesn't exist or is older than sourceFile + * @brief Tests if buildFile is older than sourceFile + * @return True if buildFile is older than sourceFile. + * False may indicate an error. */ -static bool FileAbsentOrOlder(const std::string& buildFile, - const std::string& sourceFile) +static bool FileIsOlderThan(std::string const& buildFile, + std::string const& sourceFile, + std::string* error = nullptr) { int result = 0; - bool success = - cmsys::SystemTools::FileTimeCompare(buildFile, sourceFile, &result); - return (!success || (result <= 0)); -} - -static bool ListContains(const std::vector<std::string>& list, - const std::string& entry) -{ - return (std::find(list.begin(), list.end(), entry) != list.end()); -} - -static std::string JoinOptionsList(const std::vector<std::string>& opts) -{ - return cmOutputConverter::EscapeForCMake(cmJoin(opts, ";")); -} - -static std::string JoinOptionsMap( - const std::map<std::string, std::string>& opts) -{ - std::string result; - for (std::map<std::string, std::string>::const_iterator it = opts.begin(); - it != opts.end(); ++it) { - if (it != opts.begin()) { - result += cmQtAutoGeneratorCommon::listSep; - } - result += it->first; - result += "==="; - result += it->second; + if (cmSystemTools::FileTimeCompare(buildFile, sourceFile, &result)) { + return (result < 0); } - return result; -} - -static std::string JoinExts(const std::vector<std::string>& lst) -{ - std::string result; - if (!lst.empty()) { - const std::string separator = ","; - for (std::vector<std::string>::const_iterator it = lst.begin(); - it != lst.end(); ++it) { - if (it != lst.begin()) { - result += separator; - } - result += '.'; - result += *it; - } + if (error != nullptr) { + error->append( + "File modification time comparison failed for the files\n "); + error->append(cmQtAutoGen::Quoted(buildFile)); + error->append("\nand\n "); + error->append(cmQtAutoGen::Quoted(sourceFile)); } - return result; + return false; } -static void UicMergeOptions(std::vector<std::string>& opts, - const std::vector<std::string>& fileOpts, - bool isQt5) +static bool ListContains(std::vector<std::string> const& list, + std::string const& entry) { - static const char* valueOptions[] = { "tr", "translate", - "postfix", "generator", - "include", // Since Qt 5.3 - "g" }; - std::vector<std::string> extraOpts; - for (std::vector<std::string>::const_iterator it = fileOpts.begin(); - it != fileOpts.end(); ++it) { - std::vector<std::string>::iterator existingIt = - std::find(opts.begin(), opts.end(), *it); - if (existingIt != opts.end()) { - const char* o = it->c_str(); - if (*o == '-') { - ++o; - } - if (isQt5 && *o == '-') { - ++o; - } - if (std::find_if(cmArrayBegin(valueOptions), cmArrayEnd(valueOptions), - cmStrCmp(*it)) != cmArrayEnd(valueOptions)) { - assert(existingIt + 1 != opts.end()); - *(existingIt + 1) = *(it + 1); - ++it; - } - } else { - extraOpts.push_back(*it); - } - } - opts.insert(opts.end(), extraOpts.begin(), extraOpts.end()); + return (std::find(list.begin(), list.end(), entry) != list.end()); } // -- Class methods cmQtAutoGenerators::cmQtAutoGenerators() - : Verbose(cmsys::SystemTools::HasEnv("VERBOSE")) + : MultiConfig(cmQtAutoGen::WRAP) + , IncludeProjectDirsBefore(false) + , Verbose(cmSystemTools::HasEnv("VERBOSE")) , ColorOutput(true) , MocSettingsChanged(false) , MocPredefsChanged(false) - , MocRunFailed(false) + , MocRelaxedMode(false) , UicSettingsChanged(false) - , UicRunFailed(false) , RccSettingsChanged(false) - , RccRunFailed(false) { - - std::string colorEnv; - cmsys::SystemTools::GetEnv("COLOR", colorEnv); - if (!colorEnv.empty()) { - if (cmSystemTools::IsOn(colorEnv.c_str())) { - this->ColorOutput = true; - } else { - this->ColorOutput = false; + { + std::string colorEnv; + cmSystemTools::GetEnv("COLOR", colorEnv); + if (!colorEnv.empty()) { + this->ColorOutput = cmSystemTools::IsOn(colorEnv.c_str()); } } // Moc macro filters - this->MocMacroFilters.push_back( - MocMacroFilter("Q_OBJECT", "[\n][ \t]*{?[ \t]*Q_OBJECT[^a-zA-Z0-9_]")); - this->MocMacroFilters.push_back( - MocMacroFilter("Q_GADGET", "[\n][ \t]*{?[ \t]*Q_GADGET[^a-zA-Z0-9_]")); + this->MocMacroFilters.emplace_back( + "Q_OBJECT", "[\n][ \t]*{?[ \t]*Q_OBJECT[^a-zA-Z0-9_]"); + this->MocMacroFilters.emplace_back( + "Q_GADGET", "[\n][ \t]*{?[ \t]*Q_GADGET[^a-zA-Z0-9_]"); // Precompile regular expressions this->MocRegExpInclude.compile( @@ -292,8 +163,8 @@ cmQtAutoGenerators::cmQtAutoGenerators() "[\"<](([^ \">]+/)?ui_[^ \">/]+\\.h)[\">]"); } -bool cmQtAutoGenerators::Run(const std::string& targetDirectory, - const std::string& config) +bool cmQtAutoGenerators::Run(std::string const& targetDirectory, + std::string const& config) { cmake cm(cmake::RoleScript); cm.SetHomeOutputDirectory(targetDirectory); @@ -305,16 +176,14 @@ bool cmQtAutoGenerators::Run(const std::string& targetDirectory, snapshot.GetDirectory().SetCurrentBinary(targetDirectory); snapshot.GetDirectory().SetCurrentSource(targetDirectory); - CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, snapshot)); - gg.SetCurrentMakefile(mf.get()); + auto makefile = cm::make_unique<cmMakefile>(&gg, snapshot); + gg.SetCurrentMakefile(makefile.get()); bool success = false; - if (this->ReadAutogenInfoFile(mf.get(), targetDirectory, config)) { - // Read old settings - this->SettingsFileRead(mf.get()); - // Init and run - this->Init(mf.get()); - if (this->RunAutogen()) { + if (this->InitInfoFile(makefile.get(), targetDirectory, config)) { + // Read latest settings + this->SettingsFileRead(makefile.get()); + if (this->Process()) { // Write current settings if (this->SettingsFileWrite()) { success = true; @@ -324,117 +193,145 @@ bool cmQtAutoGenerators::Run(const std::string& targetDirectory, return success; } -bool cmQtAutoGenerators::MocDependFilterPush(const std::string& key, - const std::string& regExp) +bool cmQtAutoGenerators::InitInfoFile(cmMakefile* makefile, + std::string const& targetDirectory, + std::string const& config) { - bool success = false; - if (!key.empty()) { - if (!regExp.empty()) { - MocDependFilter filter; - filter.key = key; - if (filter.regExp.compile(regExp)) { - this->MocDependFilters.push_back(filter); - success = true; - } else { - this->LogError("AutoMoc: Error in AUTOMOC_DEPEND_FILTERS: Compiling " - "regular expression failed.\nKey: " + - Quoted(key) + "\nExp.: " + Quoted(regExp)); + // -- Meta + this->HeaderExtensions = makefile->GetCMakeInstance()->GetHeaderExtensions(); + + // Utility lambdas + auto InfoGet = [makefile](const char* key) { + return makefile->GetSafeDefinition(key); + }; + auto InfoGetBool = [makefile](const char* key) { + return makefile->IsOn(key); + }; + auto InfoGetList = [makefile](const char* key) -> std::vector<std::string> { + std::vector<std::string> list; + cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition(key), list); + return list; + }; + auto InfoGetLists = + [makefile](const char* key) -> std::vector<std::vector<std::string>> { + std::vector<std::vector<std::string>> lists; + { + std::string const value = makefile->GetSafeDefinition(key); + std::string::size_type pos = 0; + while (pos < value.size()) { + std::string::size_type next = value.find(cmQtAutoGen::listSep, pos); + std::string::size_type length = + (next != std::string::npos) ? next - pos : value.size() - pos; + // Remove enclosing braces + if (length >= 2) { + std::string::const_iterator itBeg = value.begin() + (pos + 1); + std::string::const_iterator itEnd = itBeg + (length - 2); + { + std::string subValue(itBeg, itEnd); + std::vector<std::string> list; + cmSystemTools::ExpandListArgument(subValue, list); + lists.push_back(std::move(list)); + } + } + pos += length; + pos += cmQtAutoGen::listSep.size(); } - } else { - this->LogError("AutoMoc: Error in AUTOMOC_DEPEND_FILTERS: Regular " - "expression is empty"); } - } else { - this->LogError("AutoMoc: Error in AUTOMOC_DEPEND_FILTERS: Key is empty"); - } - return success; -} - -bool cmQtAutoGenerators::ReadAutogenInfoFile( - cmMakefile* makefile, const std::string& targetDirectory, - const std::string& config) -{ - std::string filename(cmSystemTools::CollapseFullPath(targetDirectory)); - cmSystemTools::ConvertToUnixSlashes(filename); - filename += "/AutogenInfo.cmake"; + return lists; + }; + auto InfoGetConfig = [makefile, &config](const char* key) -> std::string { + const char* valueConf = nullptr; + { + std::string keyConf = key; + keyConf += '_'; + keyConf += config; + valueConf = makefile->GetDefinition(keyConf); + } + if (valueConf == nullptr) { + valueConf = makefile->GetSafeDefinition(key); + } + return std::string(valueConf); + }; + auto InfoGetConfigList = + [&InfoGetConfig](const char* key) -> std::vector<std::string> { + std::vector<std::string> list; + cmSystemTools::ExpandListArgument(InfoGetConfig(key), list); + return list; + }; - if (!makefile->ReadListFile(filename.c_str())) { - this->LogError("AutoGen: Error processing file: " + filename); + // -- Read info file + this->InfoFile = cmSystemTools::CollapseFullPath(targetDirectory); + cmSystemTools::ConvertToUnixSlashes(this->InfoFile); + this->InfoFile += "/AutogenInfo.cmake"; + if (!makefile->ReadListFile(this->InfoFile.c_str())) { + this->LogFileError(cmQtAutoGen::GEN, this->InfoFile, + "File processing failed"); return false; } // -- Meta - InfoGetConfig(makefile, "AM_CONFIG_SUFFIX", config, this->ConfigSuffix); - - // - Old settings file - { - this->SettingsFile = cmSystemTools::CollapseFullPath(targetDirectory); - cmSystemTools::ConvertToUnixSlashes(this->SettingsFile); - this->SettingsFile += "/AutogenOldSettings"; - this->SettingsFile += this->ConfigSuffix; - this->SettingsFile += ".cmake"; + this->MultiConfig = cmQtAutoGen::MultiConfigType(InfoGet("AM_MULTI_CONFIG")); + this->ConfigSuffix = InfoGetConfig("AM_CONFIG_SUFFIX"); + if (this->ConfigSuffix.empty()) { + this->ConfigSuffix = "_"; + this->ConfigSuffix += config; } // - Files and directories - InfoGet(makefile, "AM_CMAKE_SOURCE_DIR", this->ProjectSourceDir); - InfoGet(makefile, "AM_CMAKE_BINARY_DIR", this->ProjectBinaryDir); - InfoGet(makefile, "AM_CMAKE_CURRENT_SOURCE_DIR", this->CurrentSourceDir); - InfoGet(makefile, "AM_CMAKE_CURRENT_BINARY_DIR", this->CurrentBinaryDir); - InfoGet(makefile, "AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE", - this->IncludeProjectDirsBefore); - InfoGet(makefile, "AM_BUILD_DIR", this->AutogenBuildDir); + this->ProjectSourceDir = InfoGet("AM_CMAKE_SOURCE_DIR"); + this->ProjectBinaryDir = InfoGet("AM_CMAKE_BINARY_DIR"); + this->CurrentSourceDir = InfoGet("AM_CMAKE_CURRENT_SOURCE_DIR"); + this->CurrentBinaryDir = InfoGet("AM_CMAKE_CURRENT_BINARY_DIR"); + this->IncludeProjectDirsBefore = + InfoGetBool("AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE"); + this->AutogenBuildDir = InfoGet("AM_BUILD_DIR"); if (this->AutogenBuildDir.empty()) { - this->LogError("AutoGen: Error: Missing autogen build directory "); + this->LogFileError(cmQtAutoGen::GEN, this->InfoFile, + "Autogen build directory missing"); return false; } - InfoGet(makefile, "AM_SOURCES", this->Sources); - InfoGet(makefile, "AM_HEADERS", this->Headers); // - Qt environment - InfoGet(makefile, "AM_QT_VERSION_MAJOR", this->QtMajorVersion); - if (this->QtMajorVersion.empty()) { - InfoGet(makefile, "AM_Qt5Core_VERSION_MAJOR", this->QtMajorVersion); - } - InfoGet(makefile, "AM_QT_MOC_EXECUTABLE", this->MocExecutable); - InfoGet(makefile, "AM_QT_UIC_EXECUTABLE", this->UicExecutable); - InfoGet(makefile, "AM_QT_RCC_EXECUTABLE", this->RccExecutable); + this->QtMajorVersion = InfoGet("AM_QT_VERSION_MAJOR"); + this->QtMinorVersion = InfoGet("AM_QT_VERSION_MINOR"); + this->MocExecutable = InfoGet("AM_QT_MOC_EXECUTABLE"); + this->UicExecutable = InfoGet("AM_QT_UIC_EXECUTABLE"); + this->RccExecutable = InfoGet("AM_QT_RCC_EXECUTABLE"); // Check Qt version if ((this->QtMajorVersion != "4") && (this->QtMajorVersion != "5")) { - this->LogError("AutoGen: Error: Unsupported Qt version: " + - Quoted(this->QtMajorVersion)); + this->LogFileError(cmQtAutoGen::GEN, this->InfoFile, + "Unsupported Qt version: " + + cmQtAutoGen::Quoted(this->QtMajorVersion)); return false; } // - Moc if (this->MocEnabled()) { - InfoGet(makefile, "AM_MOC_SKIP", this->MocSkipList); - InfoGetConfig(makefile, "AM_MOC_DEFINITIONS", config, - this->MocDefinitions); + this->MocSkipList = InfoGetList("AM_MOC_SKIP"); + this->MocDefinitions = InfoGetConfigList("AM_MOC_DEFINITIONS"); #ifdef _WIN32 { - const std::string win32("WIN32"); + std::string const win32("WIN32"); if (!ListContains(this->MocDefinitions, win32)) { this->MocDefinitions.push_back(win32); } } #endif - InfoGetConfig(makefile, "AM_MOC_INCLUDES", config, this->MocIncludePaths); - InfoGet(makefile, "AM_MOC_OPTIONS", this->MocOptions); - InfoGet(makefile, "AM_MOC_RELAXED_MODE", this->MocRelaxedMode); + this->MocIncludePaths = InfoGetConfigList("AM_MOC_INCLUDES"); + this->MocOptions = InfoGetList("AM_MOC_OPTIONS"); + this->MocRelaxedMode = InfoGetBool("AM_MOC_RELAXED_MODE"); { - std::vector<std::string> MocMacroNames; - InfoGet(makefile, "AM_MOC_MACRO_NAMES", MocMacroNames); - for (std::vector<std::string>::const_iterator dit = - MocMacroNames.begin(); - dit != MocMacroNames.end(); ++dit) { - this->MocMacroFilters.push_back( - MocMacroFilter(*dit, "[^a-zA-Z0-9_]" + *dit + "[^a-zA-Z0-9_]")); + std::vector<std::string> const MocMacroNames = + InfoGetList("AM_MOC_MACRO_NAMES"); + for (std::string const& item : MocMacroNames) { + this->MocMacroFilters.emplace_back( + item, ("[^a-zA-Z0-9_]" + item).append("[^a-zA-Z0-9_]")); } } { - std::vector<std::string> mocDependFilters; - InfoGet(makefile, "AM_MOC_DEPEND_FILTERS", mocDependFilters); + std::vector<std::string> const mocDependFilters = + InfoGetList("AM_MOC_DEPEND_FILTERS"); // Insert Q_PLUGIN_METADATA dependency filter if (this->QtMajorVersion != "4") { this->MocDependFilterPush("Q_PLUGIN_METADATA", @@ -443,105 +340,266 @@ bool cmQtAutoGenerators::ReadAutogenInfoFile( } // Insert user defined dependency filters if ((mocDependFilters.size() % 2) == 0) { - for (std::vector<std::string>::const_iterator dit = - mocDependFilters.begin(); - dit != mocDependFilters.end(); dit += 2) { + for (std::vector<std::string>::const_iterator + dit = mocDependFilters.begin(), + ditEnd = mocDependFilters.end(); + dit != ditEnd; dit += 2) { if (!this->MocDependFilterPush(*dit, *(dit + 1))) { return false; } } } else { - this->LogError( - "AutoMoc: Error: AUTOMOC_DEPEND_FILTERS list size is not " - "a multiple of 2 in:\n" + - Quoted(filename)); + this->LogFileError( + cmQtAutoGen::MOC, this->InfoFile, + "AUTOMOC_DEPEND_FILTERS list size is not a multiple of 2"); return false; } } - InfoGet(makefile, "AM_MOC_PREDEFS_CMD", this->MocPredefsCmd); + this->MocPredefsCmd = InfoGetList("AM_MOC_PREDEFS_CMD"); } // - Uic if (this->UicEnabled()) { - InfoGet(makefile, "AM_UIC_SKIP", this->UicSkipList); - InfoGet(makefile, "AM_UIC_SEARCH_PATHS", this->UicSearchPaths); - InfoGetConfig(makefile, "AM_UIC_TARGET_OPTIONS", config, - this->UicTargetOptions); + this->UicSkipList = InfoGetList("AM_UIC_SKIP"); + this->UicSearchPaths = InfoGetList("AM_UIC_SEARCH_PATHS"); + this->UicTargetOptions = InfoGetConfigList("AM_UIC_TARGET_OPTIONS"); { - std::vector<std::string> uicFilesVec; - std::vector<std::string> uicOptionsVec; - InfoGet(makefile, "AM_UIC_OPTIONS_FILES", uicFilesVec); - InfoGet(makefile, "AM_UIC_OPTIONS_OPTIONS", uicOptionsVec); + auto sources = InfoGetList("AM_UIC_OPTIONS_FILES"); + auto options = InfoGetLists("AM_UIC_OPTIONS_OPTIONS"); // Compare list sizes - if (uicFilesVec.size() == uicOptionsVec.size()) { - for (std::vector<std::string>::iterator - fileIt = uicFilesVec.begin(), - optionIt = uicOptionsVec.begin(); - fileIt != uicFilesVec.end(); ++fileIt, ++optionIt) { - cmSystemTools::ReplaceString(*optionIt, - cmQtAutoGeneratorCommon::listSep, ";"); - this->UicOptions[*fileIt] = *optionIt; - } - } else { - this->LogError( - "AutoGen: Error: Uic files/options lists size missmatch in:\n" + - Quoted(filename)); + if (sources.size() != options.size()) { + std::ostringstream ost; + ost << "files/options lists sizes missmatch (" << sources.size() << "/" + << options.size() << ")"; + this->LogFileError(cmQtAutoGen::UIC, this->InfoFile, ost.str()); return false; } + auto fitEnd = sources.cend(); + auto fit = sources.begin(); + auto oit = options.begin(); + while (fit != fitEnd) { + this->UicOptions[*fit] = std::move(*oit); + ++fit; + ++oit; + } } } // - Rcc if (this->RccEnabled()) { - InfoGet(makefile, "AM_RCC_SOURCES", this->RccSources); - // File options + // File lists + auto sources = InfoGetList("AM_RCC_SOURCES"); + auto builds = InfoGetList("AM_RCC_BUILDS"); + auto options = InfoGetLists("AM_RCC_OPTIONS"); + auto inputs = InfoGetLists("AM_RCC_INPUTS"); + + if (sources.size() != builds.size()) { + std::ostringstream ost; + ost << "sources, builds lists sizes missmatch (" << sources.size() << "/" + << builds.size() << ")"; + this->LogFileError(cmQtAutoGen::RCC, this->InfoFile, ost.str()); + return false; + } + if (sources.size() != options.size()) { + std::ostringstream ost; + ost << "sources, options lists sizes missmatch (" << sources.size() + << "/" << options.size() << ")"; + this->LogFileError(cmQtAutoGen::RCC, this->InfoFile, ost.str()); + return false; + } + if (sources.size() != inputs.size()) { + std::ostringstream ost; + ost << "sources, inputs lists sizes missmatch (" << sources.size() << "/" + << inputs.size() << ")"; + this->LogFileError(cmQtAutoGen::RCC, this->InfoFile, ost.str()); + return false; + } + { + auto srcItEnd = sources.end(); + auto srcIt = sources.begin(); + auto bldIt = builds.begin(); + auto optIt = options.begin(); + auto inpIt = inputs.begin(); + while (srcIt != srcItEnd) { + this->RccJobs.push_back(RccJob{ std::move(*srcIt), std::move(*bldIt), + std::move(*optIt), + std::move(*inpIt) }); + ++srcIt; + ++bldIt; + ++optIt; + ++inpIt; + } + } + } + + // Initialize source file jobs + { + // Utility lambdas + auto AddJob = [this](std::map<std::string, SourceJob>& jobs, + std::string&& sourceFile) { + const bool moc = !this->MocSkip(sourceFile); + const bool uic = !this->UicSkip(sourceFile); + if (moc || uic) { + SourceJob& job = jobs[std::move(sourceFile)]; + job.Moc = moc; + job.Uic = uic; + } + }; + + // Add header jobs + for (std::string& hdr : InfoGetList("AM_HEADERS")) { + AddJob(this->HeaderJobs, std::move(hdr)); + } + // Add source jobs { - std::vector<std::string> rccFilesVec; - std::vector<std::string> rccOptionsVec; - InfoGet(makefile, "AM_RCC_OPTIONS_FILES", rccFilesVec); - InfoGet(makefile, "AM_RCC_OPTIONS_OPTIONS", rccOptionsVec); - if (rccFilesVec.size() == rccOptionsVec.size()) { - for (std::vector<std::string>::iterator - fileIt = rccFilesVec.begin(), - optionIt = rccOptionsVec.begin(); - fileIt != rccFilesVec.end(); ++fileIt, ++optionIt) { - // Replace item separator - cmSystemTools::ReplaceString(*optionIt, - cmQtAutoGeneratorCommon::listSep, ";"); - this->RccOptions[*fileIt] = *optionIt; + std::vector<std::string> sources = InfoGetList("AM_SOURCES"); + // Add header(s) for the source file + for (std::string const& src : sources) { + const bool srcMoc = !this->MocSkip(src); + const bool srcUic = !this->UicSkip(src); + if (!srcMoc && !srcUic) { + continue; + } + // Search for the default header file and a private header + std::array<std::string, 2> headerBases; + headerBases[0] = SubDirPrefix(src); + headerBases[0] += cmSystemTools::GetFilenameWithoutLastExtension(src); + headerBases[1] = headerBases[0]; + headerBases[1] += "_p"; + for (std::string const& headerBase : headerBases) { + std::string header; + if (this->FindHeader(header, headerBase)) { + const bool moc = srcMoc && !this->MocSkip(header); + const bool uic = srcUic && !this->UicSkip(header); + if (moc || uic) { + SourceJob& job = this->HeaderJobs[std::move(header)]; + job.Moc = moc; + job.Uic = uic; + } + } } - } else { - this->LogError( - "AutoGen: Error: RCC files/options lists size missmatch in:\n" + - Quoted(filename)); - return false; + } + // Add Source jobs + for (std::string& src : sources) { + AddJob(this->SourceJobs, std::move(src)); } } - // File lists + } + + // Init derived information + // ------------------------ + + // Init file path checksum generator + this->FilePathChecksum.setupParentDirs( + this->CurrentSourceDir, this->CurrentBinaryDir, this->ProjectSourceDir, + this->ProjectBinaryDir); + + // include directory + this->AutogenIncludeDir = "include"; + if (this->MultiConfig != cmQtAutoGen::SINGLE) { + this->AutogenIncludeDir += this->ConfigSuffix; + } + this->AutogenIncludeDir += "/"; + + // Moc variables + if (this->MocEnabled()) { + // Mocs compilation file + this->MocCompFileRel = "mocs_compilation"; + if (this->MultiConfig == cmQtAutoGen::FULL) { + this->MocCompFileRel += this->ConfigSuffix; + } + this->MocCompFileRel += ".cpp"; + this->MocCompFileAbs = cmSystemTools::CollapseCombinedPath( + this->AutogenBuildDir, this->MocCompFileRel); + + // Moc predefs file + if (!this->MocPredefsCmd.empty()) { + this->MocPredefsFileRel = "moc_predefs"; + if (this->MultiConfig != cmQtAutoGen::SINGLE) { + this->MocPredefsFileRel += this->ConfigSuffix; + } + this->MocPredefsFileRel += ".h"; + this->MocPredefsFileAbs = cmSystemTools::CollapseCombinedPath( + this->AutogenBuildDir, this->MocPredefsFileRel); + } + + // Sort include directories on demand + if (this->IncludeProjectDirsBefore) { + // Move strings to temporary list + std::list<std::string> includes; + includes.insert(includes.end(), this->MocIncludePaths.begin(), + this->MocIncludePaths.end()); + this->MocIncludePaths.clear(); + this->MocIncludePaths.reserve(includes.size()); + // Append project directories only + { + std::array<std::string const*, 2> const movePaths = { + { &this->ProjectBinaryDir, &this->ProjectSourceDir } + }; + for (std::string const* ppath : movePaths) { + std::list<std::string>::iterator it = includes.begin(); + while (it != includes.end()) { + std::string const& path = *it; + if (cmSystemTools::StringStartsWith(path, ppath->c_str())) { + this->MocIncludePaths.push_back(path); + it = includes.erase(it); + } else { + ++it; + } + } + } + } + // Append remaining directories + this->MocIncludePaths.insert(this->MocIncludePaths.end(), + includes.begin(), includes.end()); + } + // Compose moc includes list { - std::vector<std::string> rccInputLists; - InfoGet(makefile, "AM_RCC_INPUTS", rccInputLists); - if (this->RccSources.size() == rccInputLists.size()) { - for (std::vector<std::string>::iterator - fileIt = this->RccSources.begin(), - inputIt = rccInputLists.begin(); - fileIt != this->RccSources.end(); ++fileIt, ++inputIt) { - // Remove braces - *inputIt = inputIt->substr(1, inputIt->size() - 2); - // Replace item separator - cmSystemTools::ReplaceString(*inputIt, - cmQtAutoGeneratorCommon::listSep, ";"); - std::vector<std::string> rccInputFiles; - cmSystemTools::ExpandListArgument(*inputIt, rccInputFiles); - this->RccInputs[*fileIt] = rccInputFiles; + std::set<std::string> frameworkPaths; + for (std::string const& path : this->MocIncludePaths) { + this->MocIncludes.push_back("-I" + path); + // Extract framework path + if (cmHasLiteralSuffix(path, ".framework/Headers")) { + // Go up twice to get to the framework root + std::vector<std::string> pathComponents; + cmSystemTools::SplitPath(path, pathComponents); + std::string frameworkPath = cmSystemTools::JoinPath( + pathComponents.begin(), pathComponents.end() - 2); + frameworkPaths.insert(frameworkPath); } - } else { - this->LogError( - "AutoGen: Error: RCC sources/inputs lists size missmatch in:\n" + - Quoted(filename)); - return false; } + // Append framework includes + for (std::string const& path : frameworkPaths) { + this->MocIncludes.push_back("-F"); + this->MocIncludes.push_back(path); + } + } + // Setup single list with all options + { + // Add includes + this->MocAllOptions.insert(this->MocAllOptions.end(), + this->MocIncludes.begin(), + this->MocIncludes.end()); + // Add definitions + for (std::string const& def : this->MocDefinitions) { + this->MocAllOptions.push_back("-D" + def); + } + // Add options + this->MocAllOptions.insert(this->MocAllOptions.end(), + this->MocOptions.begin(), + this->MocOptions.end()); + } + } + + // - Old settings file + { + this->SettingsFile = cmSystemTools::CollapseFullPath(targetDirectory); + cmSystemTools::ConvertToUnixSlashes(this->SettingsFile); + this->SettingsFile += "/AutogenOldSettings"; + if (this->MultiConfig != cmQtAutoGen::SINGLE) { + this->SettingsFile += this->ConfigSuffix; } + this->SettingsFile += ".cmake"; } return true; @@ -552,20 +610,16 @@ void cmQtAutoGenerators::SettingsFileRead(cmMakefile* makefile) // Compose current settings strings { cmCryptoHash crypt(cmCryptoHash::AlgoSHA256); - const std::string sep(" ~~~ "); + std::string const sep(" ~~~ "); if (this->MocEnabled()) { std::string str; str += this->MocExecutable; str += sep; - str += JoinOptionsList(this->MocDefinitions); - str += sep; - str += JoinOptionsList(this->MocIncludePaths); - str += sep; - str += JoinOptionsList(this->MocOptions); + str += cmJoin(this->MocAllOptions, ";"); str += sep; str += this->IncludeProjectDirsBefore ? "TRUE" : "FALSE"; str += sep; - str += JoinOptionsList(this->MocPredefsCmd); + str += cmJoin(this->MocPredefsCmd, ";"); str += sep; this->SettingsStringMoc = crypt.HashString(str); } @@ -573,17 +627,27 @@ void cmQtAutoGenerators::SettingsFileRead(cmMakefile* makefile) std::string str; str += this->UicExecutable; str += sep; - str += JoinOptionsList(this->UicTargetOptions); - str += sep; - str += JoinOptionsMap(this->UicOptions); + str += cmJoin(this->UicTargetOptions, ";"); + for (const auto& item : this->UicOptions) { + str += sep; + str += item.first; + str += sep; + str += cmJoin(item.second, ";"); + } str += sep; this->SettingsStringUic = crypt.HashString(str); } if (this->RccEnabled()) { std::string str; str += this->RccExecutable; - str += sep; - str += JoinOptionsMap(this->RccOptions); + for (const RccJob& rccJob : this->RccJobs) { + str += sep; + str += rccJob.QrcFile; + str += sep; + str += rccJob.RccFile; + str += sep; + str += cmJoin(rccJob.Options, ";"); + } str += sep; this->SettingsStringRcc = crypt.HashString(str); } @@ -591,19 +655,24 @@ void cmQtAutoGenerators::SettingsFileRead(cmMakefile* makefile) // Read old settings if (makefile->ReadListFile(this->SettingsFile.c_str())) { - if (!SettingsMatch(makefile, SettingsKeyMoc, this->SettingsStringMoc)) { - this->MocSettingsChanged = true; - } - if (!SettingsMatch(makefile, SettingsKeyUic, this->SettingsStringUic)) { - this->UicSettingsChanged = true; - } - if (!SettingsMatch(makefile, SettingsKeyRcc, this->SettingsStringRcc)) { - this->RccSettingsChanged = true; + { + auto SMatch = [makefile](const char* key, std::string const& value) { + return (value == makefile->GetSafeDefinition(key)); + }; + if (!SMatch(SettingsKeyMoc, this->SettingsStringMoc)) { + this->MocSettingsChanged = true; + } + if (!SMatch(SettingsKeyUic, this->SettingsStringUic)) { + this->UicSettingsChanged = true; + } + if (!SMatch(SettingsKeyRcc, this->SettingsStringRcc)) { + this->RccSettingsChanged = true; + } } // In case any setting changed remove the old settings file. // This triggers a full rebuild on the next run if the current // build is aborted before writing the current settings in the end. - if (this->AnySettingsChanged()) { + if (this->SettingsChanged()) { cmSystemTools::RemoveFile(this->SettingsFile); } } else { @@ -618,20 +687,30 @@ bool cmQtAutoGenerators::SettingsFileWrite() { bool success = true; // Only write if any setting changed - if (this->AnySettingsChanged()) { + if (this->SettingsChanged()) { if (this->Verbose) { - this->LogInfo("AutoGen: Writing settings file " + - Quoted(this->SettingsFile)); + this->LogInfo(cmQtAutoGen::GEN, "Writing settings file " + + cmQtAutoGen::Quoted(this->SettingsFile)); } // Compose settings file content std::string settings; - SettingAppend(settings, SettingsKeyMoc, this->SettingsStringMoc); - SettingAppend(settings, SettingsKeyUic, this->SettingsStringUic); - SettingAppend(settings, SettingsKeyRcc, this->SettingsStringRcc); + { + auto SettingAppend = [&settings](const char* key, + std::string const& value) { + settings += "set("; + settings += key; + settings += " "; + settings += cmOutputConverter::EscapeForCMake(value); + settings += ")\n"; + }; + SettingAppend(SettingsKeyMoc, this->SettingsStringMoc); + SettingAppend(SettingsKeyUic, this->SettingsStringUic); + SettingAppend(SettingsKeyRcc, this->SettingsStringRcc); + } // Write settings file - if (!this->FileWrite("AutoGen", this->SettingsFile, settings)) { - this->LogError("AutoGen: Error: Could not write old settings file " + - Quoted(this->SettingsFile)); + if (!this->FileWrite(cmQtAutoGen::GEN, this->SettingsFile, settings)) { + this->LogFileError(cmQtAutoGen::GEN, this->SettingsFile, + "Settings file writing failed"); // Remove old settings file to trigger a full rebuild on the next run cmSystemTools::RemoveFile(this->SettingsFile); success = false; @@ -640,93 +719,7 @@ bool cmQtAutoGenerators::SettingsFileWrite() return success; } -void cmQtAutoGenerators::Init(cmMakefile* makefile) -{ - // Mocs compilation file - this->MocCompFileRel = "mocs_compilation.cpp"; - this->MocCompFileAbs = cmSystemTools::CollapseCombinedPath( - this->AutogenBuildDir, this->MocCompFileRel); - - // Mocs include directory - this->AutogenIncludeDir = "include"; - this->AutogenIncludeDir += this->ConfigSuffix; - this->AutogenIncludeDir += "/"; - - // Moc predefs file - if (!this->MocPredefsCmd.empty()) { - this->MocPredefsFileRel = "moc_predefs"; - this->MocPredefsFileRel += this->ConfigSuffix; - this->MocPredefsFileRel += ".h"; - this->MocPredefsFileAbs = cmSystemTools::CollapseCombinedPath( - this->AutogenBuildDir, this->MocPredefsFileRel); - } - - // Init file path checksum generator - FPathChecksum.setupParentDirs(this->CurrentSourceDir, this->CurrentBinaryDir, - this->ProjectSourceDir, - this->ProjectBinaryDir); - - // Acquire header extensions - this->HeaderExtensions = makefile->GetCMakeInstance()->GetHeaderExtensions(); - - // Sort include directories on demand - if (this->IncludeProjectDirsBefore) { - // Move strings to temporary list - std::list<std::string> includes; - includes.insert(includes.end(), this->MocIncludePaths.begin(), - this->MocIncludePaths.end()); - this->MocIncludePaths.clear(); - this->MocIncludePaths.reserve(includes.size()); - // Append project directories only - { - const char* movePaths[2] = { this->ProjectBinaryDir.c_str(), - this->ProjectSourceDir.c_str() }; - for (const char* const* mpit = cmArrayBegin(movePaths); - mpit != cmArrayEnd(movePaths); ++mpit) { - std::list<std::string>::iterator it = includes.begin(); - while (it != includes.end()) { - const std::string& path = *it; - if (cmsys::SystemTools::StringStartsWith(path, *mpit)) { - this->MocIncludePaths.push_back(path); - it = includes.erase(it); - } else { - ++it; - } - } - } - } - // Append remaining directories - this->MocIncludePaths.insert(this->MocIncludePaths.end(), includes.begin(), - includes.end()); - } - // Compose moc includes list - { - std::set<std::string> frameworkPaths; - for (std::vector<std::string>::const_iterator it = - this->MocIncludePaths.begin(); - it != this->MocIncludePaths.end(); ++it) { - const std::string& path = *it; - this->MocIncludes.push_back("-I" + path); - // Extract framework path - if (cmHasLiteralSuffix(path, ".framework/Headers")) { - // Go up twice to get to the framework root - std::vector<std::string> pathComponents; - cmsys::SystemTools::SplitPath(path, pathComponents); - std::string frameworkPath = cmsys::SystemTools::JoinPath( - pathComponents.begin(), pathComponents.end() - 2); - frameworkPaths.insert(frameworkPath); - } - } - // Append framework includes - for (std::set<std::string>::const_iterator it = frameworkPaths.begin(); - it != frameworkPaths.end(); ++it) { - this->MocIncludes.push_back("-F"); - this->MocIncludes.push_back(*it); - } - } -} - -bool cmQtAutoGenerators::RunAutogen() +bool cmQtAutoGenerators::Process() { // the program goes through all .cpp files to see which moc files are // included. It is not really interesting how the moc file is named, but @@ -738,59 +731,37 @@ bool cmQtAutoGenerators::RunAutogen() // Create AUTOGEN include directory { - const std::string incDirAbs = cmSystemTools::CollapseCombinedPath( + std::string const incDirAbs = cmSystemTools::CollapseCombinedPath( this->AutogenBuildDir, this->AutogenIncludeDir); - if (!cmsys::SystemTools::MakeDirectory(incDirAbs)) { - this->LogError("AutoGen: Error: Could not create include directory " + - Quoted(incDirAbs)); + if (!cmSystemTools::MakeDirectory(incDirAbs)) { + this->LogFileError(cmQtAutoGen::GEN, incDirAbs, + "Could not create directory"); return false; } } - // key = moc source filepath, value = moc output filepath - std::map<std::string, std::string> mocsIncluded; - std::map<std::string, std::string> mocsNotIncluded; - std::map<std::string, std::set<std::string> > mocDepends; - std::map<std::string, std::vector<std::string> > uisIncluded; - // collects all headers which may need to be mocced - std::set<std::string> mocHeaderFiles; - std::set<std::string> uicHeaderFiles; - - // Parse sources - for (std::vector<std::string>::const_iterator it = this->Sources.begin(); - it != this->Sources.end(); ++it) { - const std::string& absFilename = cmsys::SystemTools::GetRealPath(*it); - // Parse source file for MOC/UIC - if (!this->ParseSourceFile(absFilename, mocsIncluded, mocDepends, - uisIncluded, this->MocRelaxedMode)) { + // Parse source files + for (const auto& item : this->SourceJobs) { + if (!this->ParseSourceFile(item.first, item.second)) { return false; } - // Find additional headers - this->SearchHeadersForSourceFile(absFilename, mocHeaderFiles, - uicHeaderFiles); } - - // Parse headers - for (std::vector<std::string>::const_iterator it = this->Headers.begin(); - it != this->Headers.end(); ++it) { - const std::string& headerName = cmsys::SystemTools::GetRealPath(*it); - if (!this->MocSkip(headerName)) { - mocHeaderFiles.insert(headerName); - } - if (!this->UicSkip(headerName)) { - uicHeaderFiles.insert(headerName); + // Parse header files + for (const auto& item : this->HeaderJobs) { + if (!this->ParseHeaderFile(item.first, item.second)) { + return false; } } - if (!this->ParseHeaders(mocHeaderFiles, uicHeaderFiles, mocsIncluded, - mocsNotIncluded, mocDepends, uisIncluded)) { + // Read missing dependency information + if (!this->ParsePostprocess()) { return false; - }; + } // Generate files - if (!this->MocGenerateAll(mocsIncluded, mocsNotIncluded, mocDepends)) { + if (!this->MocGenerateAll()) { return false; } - if (!this->UicGenerateAll(uisIncluded)) { + if (!this->UicGenerateAll()) { return false; } if (!this->RccGenerateAll()) { @@ -801,74 +772,96 @@ bool cmQtAutoGenerators::RunAutogen() } /** - * @brief Tests if the C++ content requires moc processing - * @return True if moc is required + * @return True on success */ -bool cmQtAutoGenerators::MocRequired(const std::string& contentText, - std::string* macroName) +bool cmQtAutoGenerators::ParseSourceFile(std::string const& absFilename, + const SourceJob& job) { - for (std::vector<MocMacroFilter>::iterator fit = - this->MocMacroFilters.begin(); - fit != this->MocMacroFilters.end(); ++fit) { - MocMacroFilter& filter = *fit; - // Run a simple find string operation before the expensive - // regular expression check - if (contentText.find(filter.first) != std::string::npos) { - if (filter.second.find(contentText)) { - // Return macro name on demand - if (macroName != nullptr) { - *macroName = filter.first; - } - return true; + std::string contentText; + std::string error; + bool success = ReadFile(contentText, absFilename, &error); + if (success) { + if (!contentText.empty()) { + if (job.Moc) { + success = this->MocParseSourceContent(absFilename, contentText); + } + if (success && job.Uic) { + success = this->UicParseContent(absFilename, contentText); } + } else { + this->LogFileWarning(cmQtAutoGen::GEN, absFilename, + "The source file is empty"); } + } else { + this->LogFileError(cmQtAutoGen::GEN, absFilename, + "Could not read the source file: " + error); } - return false; + return success; } -void cmQtAutoGenerators::MocFindDepends( - const std::string& absFilename, const std::string& contentText, - std::map<std::string, std::set<std::string> >& mocDepends) +/** + * @return True on success + */ +bool cmQtAutoGenerators::ParseHeaderFile(std::string const& absFilename, + const SourceJob& job) { - for (std::vector<MocDependFilter>::iterator fit = - this->MocDependFilters.begin(); - fit != this->MocDependFilters.end(); ++fit) { - MocDependFilter& filter = *fit; - // Run a simple find string operation before the expensive - // regular expression check - if (contentText.find(filter.key) != std::string::npos) { - // Run regular expression check loop - const std::string sourcePath = SubDirPrefix(absFilename); - const char* contentChars = contentText.c_str(); - while (filter.regExp.find(contentChars)) { - // Evaluate match - const std::string match = filter.regExp.match(1); - if (!match.empty()) { - // Find the dependency file - std::string incFile; - if (this->MocFindIncludedFile(incFile, sourcePath, match)) { - mocDepends[absFilename].insert(incFile); - if (this->Verbose) { - this->LogInfo("AutoMoc: Found dependency:\n " + - Quoted(absFilename) + "\n " + Quoted(incFile)); - } - } else { - this->LogWarning("AutoMoc: Warning: " + Quoted(absFilename) + - "\n" + "Could not find dependency file " + - Quoted(match)); - } - } - contentChars += filter.regExp.end(); + std::string contentText; + std::string error; + bool success = ReadFile(contentText, absFilename, &error); + if (success) { + if (!contentText.empty()) { + if (job.Moc) { + this->MocParseHeaderContent(absFilename, contentText); + } + if (job.Uic) { + success = this->UicParseContent(absFilename, contentText); + } + } else { + this->LogFileWarning(cmQtAutoGen::GEN, absFilename, + "The header file is empty"); + } + } else { + this->LogFileError(cmQtAutoGen::GEN, absFilename, + "Could not read the header file: " + error); + } + return success; +} + +/** + * @return True on success + */ +bool cmQtAutoGenerators::ParsePostprocess() +{ + bool success = true; + // Read missin dependecies + for (auto& item : this->MocJobsIncluded) { + if (!item->DependsValid) { + std::string content; + std::string error; + if (ReadFile(content, item->SourceFile, &error)) { + this->MocFindDepends(item->SourceFile, content, item->Depends); + item->DependsValid = true; + } else { + std::string emsg = "Could not read file\n "; + emsg += item->SourceFile; + emsg += "\nrequired by moc include \""; + emsg += item->IncludeString; + emsg += "\".\n"; + emsg += error; + this->LogFileError(cmQtAutoGen::MOC, item->Includer, emsg); + success = false; + break; } } } + return success; } /** * @brief Tests if the file should be ignored for moc scanning * @return True if the file should be ignored */ -bool cmQtAutoGenerators::MocSkip(const std::string& absFilename) const +bool cmQtAutoGenerators::MocSkip(std::string const& absFilename) const { if (this->MocEnabled()) { // Test if the file name is on the skip list @@ -880,68 +873,189 @@ bool cmQtAutoGenerators::MocSkip(const std::string& absFilename) const } /** - * @brief Tests if the file name is in the skip list + * @brief Tests if the C++ content requires moc processing + * @return True if moc is required */ -bool cmQtAutoGenerators::UicSkip(const std::string& absFilename) const +bool cmQtAutoGenerators::MocRequired(std::string const& contentText, + std::string* macroName) { - if (this->UicEnabled()) { - // Test if the file name is on the skip list - if (!ListContains(this->UicSkipList, absFilename)) { - return false; + for (KeyRegExp& filter : this->MocMacroFilters) { + // Run a simple find string operation before the expensive + // regular expression check + if (contentText.find(filter.Key) != std::string::npos) { + if (filter.RegExp.find(contentText)) { + // Return macro name on demand + if (macroName != nullptr) { + *macroName = filter.Key; + } + return true; + } } } - return true; + return false; } -/** - * @return True on success - */ -bool cmQtAutoGenerators::ParseSourceFile( - const std::string& absFilename, - std::map<std::string, std::string>& mocsIncluded, - std::map<std::string, std::set<std::string> >& mocDepends, - std::map<std::string, std::vector<std::string> >& uisIncluded, bool relaxed) +std::string cmQtAutoGenerators::MocStringMacros() const { - std::string contentText; - bool success = ReadAll(contentText, absFilename); - if (success) { - if (!contentText.empty()) { - // Parse source contents for MOC - if (success && !this->MocSkip(absFilename)) { - success = this->MocParseSourceContent( - absFilename, contentText, mocsIncluded, mocDepends, relaxed); + std::string res; + const auto itB = this->MocMacroFilters.cbegin(); + const auto itE = this->MocMacroFilters.cend(); + const auto itL = itE - 1; + auto itC = itB; + for (; itC != itE; ++itC) { + // Separator + if (itC != itB) { + if (itC != itL) { + res += ", "; + } else { + res += " or "; + } + } + // Key + res += itC->Key; + } + return res; +} + +std::string cmQtAutoGenerators::MocStringHeaders( + std::string const& fileBase) const +{ + std::string res = fileBase; + res += ".{"; + res += cmJoin(this->HeaderExtensions, ","); + res += "}"; + return res; +} + +std::string cmQtAutoGenerators::MocFindIncludedHeader( + std::string const& sourcePath, std::string const& includeBase) const +{ + std::string header; + // Search in vicinity of the source + if (!this->FindHeader(header, sourcePath + includeBase)) { + // Search in include directories + for (std::string const& path : this->MocIncludePaths) { + std::string fullPath = path; + fullPath.push_back('/'); + fullPath += includeBase; + if (this->FindHeader(header, fullPath)) { + break; } - // Parse source contents for UIC - if (success && !this->UicSkip(absFilename)) { - this->UicParseContent(absFilename, contentText, uisIncluded); + } + } + // Sanitize + if (!header.empty()) { + header = cmSystemTools::GetRealPath(header); + } + return header; +} + +bool cmQtAutoGenerators::MocFindIncludedFile( + std::string& absFile, std::string const& sourcePath, + std::string const& includeString) const +{ + bool success = false; + // Search in vicinity of the source + { + std::string testPath = sourcePath; + testPath += includeString; + if (cmSystemTools::FileExists(testPath.c_str())) { + absFile = cmSystemTools::GetRealPath(testPath); + success = true; + } + } + // Search in include directories + if (!success) { + for (std::string const& path : this->MocIncludePaths) { + std::string fullPath = path; + fullPath.push_back('/'); + fullPath += includeString; + if (cmSystemTools::FileExists(fullPath.c_str())) { + absFile = cmSystemTools::GetRealPath(fullPath); + success = true; + break; + } + } + } + return success; +} + +bool cmQtAutoGenerators::MocDependFilterPush(std::string const& key, + std::string const& regExp) +{ + std::string error; + if (!key.empty()) { + if (!regExp.empty()) { + KeyRegExp filter; + filter.Key = key; + if (filter.RegExp.compile(regExp)) { + this->MocDependFilters.push_back(std::move(filter)); + } else { + error = "Regular expression compiling failed"; } } else { - std::ostringstream ost; - ost << "AutoGen: Warning: The file is empty:\n" - << Quoted(absFilename) << "\n"; - this->LogWarning(ost.str()); + error = "Regular expression is empty"; } } else { - std::ostringstream ost; - ost << "AutoGen: Error: Could not read file:\n" << Quoted(absFilename); - this->LogError(ost.str()); + error = "Key is empty"; } - return success; + if (!error.empty()) { + std::string emsg = "AUTOMOC_DEPEND_FILTERS: "; + emsg += error; + emsg += "\n"; + emsg += " Key: "; + emsg += cmQtAutoGen::Quoted(key); + emsg += "\n"; + emsg += " RegExp: "; + emsg += cmQtAutoGen::Quoted(regExp); + emsg += "\n"; + this->LogError(cmQtAutoGen::MOC, emsg); + return false; + } + return true; } -void cmQtAutoGenerators::UicParseContent( - const std::string& absFilename, const std::string& contentText, - std::map<std::string, std::vector<std::string> >& uisIncluded) +void cmQtAutoGenerators::MocFindDepends(std::string const& absFilename, + std::string const& contentText, + std::set<std::string>& depends) { - if (this->Verbose) { - this->LogInfo("AutoUic: Checking " + absFilename); + if (this->MocDependFilters.empty() && contentText.empty()) { + return; } - const char* contentChars = contentText.c_str(); - if (strstr(contentChars, "ui_") != nullptr) { - while (this->UicRegExpInclude.find(contentChars)) { - uisIncluded[absFilename].push_back(this->UicRegExpInclude.match(1)); - contentChars += this->UicRegExpInclude.end(); + std::vector<std::string> matches; + for (KeyRegExp& filter : this->MocDependFilters) { + // Run a simple find string check + if (contentText.find(filter.Key) != std::string::npos) { + // Run the expensive regular expression check loop + const char* contentChars = contentText.c_str(); + while (filter.RegExp.find(contentChars)) { + std::string match = filter.RegExp.match(1); + if (!match.empty()) { + matches.emplace_back(std::move(match)); + } + contentChars += filter.RegExp.end(); + } + } + } + + if (!matches.empty()) { + std::string const sourcePath = SubDirPrefix(absFilename); + for (std::string const& match : matches) { + // Find the dependency file + std::string incFile; + if (this->MocFindIncludedFile(incFile, sourcePath, match)) { + depends.insert(incFile); + if (this->Verbose) { + this->LogInfo(cmQtAutoGen::MOC, "Found dependency:\n " + + cmQtAutoGen::Quoted(absFilename) + "\n " + + cmQtAutoGen::Quoted(incFile)); + } + } else { + this->LogFileWarning(cmQtAutoGen::MOC, absFilename, + "Could not find dependency file " + + cmQtAutoGen::Quoted(match)); + } } } } @@ -949,321 +1063,333 @@ void cmQtAutoGenerators::UicParseContent( /** * @return True on success */ -bool cmQtAutoGenerators::MocParseSourceContent( - const std::string& absFilename, const std::string& contentText, - std::map<std::string, std::string>& mocsIncluded, - std::map<std::string, std::set<std::string> >& mocDepends, bool relaxed) +bool cmQtAutoGenerators::MocParseSourceContent(std::string const& absFilename, + std::string const& contentText) { if (this->Verbose) { - this->LogInfo("AutoMoc: Checking " + absFilename); - } + this->LogInfo(cmQtAutoGen::MOC, "Checking: " + absFilename); + } + + auto AddJob = [this, &absFilename](std::string const& sourceFile, + std::string const& includeString, + std::string const* content) { + auto job = cm::make_unique<MocJobIncluded>(); + job->SourceFile = sourceFile; + job->BuildFileRel = this->AutogenIncludeDir; + job->BuildFileRel += includeString; + job->Includer = absFilename; + job->IncludeString = includeString; + job->DependsValid = (content != nullptr); + if (job->DependsValid) { + this->MocFindDepends(sourceFile, *content, job->Depends); + } + this->MocJobsIncluded.push_back(std::move(job)); + }; - const std::string scannedFileAbsPath = SubDirPrefix(absFilename); - const std::string scannedFileBasename = - cmsys::SystemTools::GetFilenameWithoutLastExtension(absFilename); + struct MocInc + { + std::string Inc; // full include string + std::string Dir; // include string directory + std::string Base; // include string file base + }; - std::string macroName; - const bool requiresMoc = this->MocRequired(contentText, ¯oName); - bool ownDotMocIncluded = false; - std::string ownMocUnderscoreInclude; - std::string ownMocUnderscoreHeader; - - // first a simple string check for "moc" is *much* faster than the regexp, - // and if the string search already fails, we don't have to try the - // expensive regexp - const char* contentChars = contentText.c_str(); - if (strstr(contentChars, "moc") != nullptr) { - // Iterate over all included moc files - while (this->MocRegExpInclude.find(contentChars)) { - const std::string incString = this->MocRegExpInclude.match(1); - // Basename of the moc include - const std::string incSubDir(SubDirPrefix(incString)); - const std::string incBasename = - cmsys::SystemTools::GetFilenameWithoutLastExtension(incString); - - // If the moc include is of the moc_foo.cpp style we expect - // the Q_OBJECT class declaration in a header file. - // If the moc include is of the foo.moc style we need to look for - // a Q_OBJECT macro in the current source file, if it contains the - // macro we generate the moc file from the source file. - if (cmHasLiteralPrefix(incBasename, "moc_")) { - // Include: moc_FOO.cxx - // Remove the moc_ part - const std::string incRealBasename = incBasename.substr(4); - const std::string headerToMoc = - this->MocFindHeader(scannedFileAbsPath, incSubDir + incRealBasename); - if (!headerToMoc.empty()) { - if (!this->MocSkip(headerToMoc)) { - // Register moc job - mocsIncluded[headerToMoc] = incString; - this->MocFindDepends(headerToMoc, contentText, mocDepends); - // Store meta information for relaxed mode - if (relaxed && (incRealBasename == scannedFileBasename)) { - ownMocUnderscoreInclude = incString; - ownMocUnderscoreHeader = headerToMoc; - } - } + // Extract moc includes from file + std::vector<MocInc> mocIncsUsc; + std::vector<MocInc> mocIncsDot; + { + const char* contentChars = contentText.c_str(); + if (strstr(contentChars, "moc") != nullptr) { + while (this->MocRegExpInclude.find(contentChars)) { + std::string incString = this->MocRegExpInclude.match(1); + std::string incDir(SubDirPrefix(incString)); + std::string incBase = + cmSystemTools::GetFilenameWithoutLastExtension(incString); + if (cmHasLiteralPrefix(incBase, "moc_")) { + // moc_<BASE>.cxx + // Remove the moc_ part from the base name + mocIncsUsc.push_back(MocInc{ std::move(incString), std::move(incDir), + incBase.substr(4) }); } else { - std::ostringstream ost; - ost << "AutoMoc: Error: " << Quoted(absFilename) << "\n" - << "The file includes the moc file " << Quoted(incString) - << ", but could not find header " - << Quoted(incRealBasename + "{" + - JoinExts(this->HeaderExtensions) + "}"); - ; - this->LogError(ost.str()); - return false; + // <BASE>.moc + mocIncsDot.push_back(MocInc{ std::move(incString), std::move(incDir), + std::move(incBase) }); } + // Forward content pointer + contentChars += this->MocRegExpInclude.end(); + } + } + } + + std::string selfMacroName; + const bool selfRequiresMoc = this->MocRequired(contentText, &selfMacroName); + + // Check if there is anything to do + if (!selfRequiresMoc && mocIncsUsc.empty() && mocIncsDot.empty()) { + return true; + } + + // Scan file variables + std::string const scanFileDir = SubDirPrefix(absFilename); + std::string const scanFileBase = + cmSystemTools::GetFilenameWithoutLastExtension(absFilename); + // Relaxed mode variables + bool ownDotMocIncluded = false; + std::string ownMocUscInclude; + std::string ownMocUscHeader; + + // Process moc_<BASE>.cxx includes + for (const MocInc& mocInc : mocIncsUsc) { + std::string const header = + this->MocFindIncludedHeader(scanFileDir, mocInc.Dir + mocInc.Base); + if (!header.empty()) { + // Check if header is skipped + if (this->MocSkip(header)) { + continue; + } + // Register moc job + AddJob(header, mocInc.Inc, nullptr); + // Store meta information for relaxed mode + if (this->MocRelaxedMode && (mocInc.Base == scanFileBase)) { + ownMocUscInclude = mocInc.Inc; + ownMocUscHeader = header; + } + } else { + std::string emsg = "The file includes the moc file "; + emsg += cmQtAutoGen::Quoted(mocInc.Inc); + emsg += ", but could not find the header "; + emsg += cmQtAutoGen::Quoted(this->MocStringHeaders(mocInc.Base)); + this->LogFileError(cmQtAutoGen::MOC, absFilename, emsg); + return false; + } + } + + // Process <BASE>.moc includes + for (const MocInc& mocInc : mocIncsDot) { + const bool ownMoc = (mocInc.Base == scanFileBase); + if (this->MocRelaxedMode) { + // Relaxed mode + if (selfRequiresMoc && ownMoc) { + // Add self + AddJob(absFilename, mocInc.Inc, &contentText); + ownDotMocIncluded = true; } else { - // Include: FOO.moc - std::string fileToMoc; - if (relaxed) { - // Mode: Relaxed - if (requiresMoc && (incBasename == scannedFileBasename)) { - // Include self - fileToMoc = absFilename; - ownDotMocIncluded = true; - } else { - // In relaxed mode try to find a header instead but issue a warning - const std::string headerToMoc = - this->MocFindHeader(scannedFileAbsPath, incSubDir + incBasename); - if (!headerToMoc.empty()) { - if (!this->MocSkip(headerToMoc)) { - // This is for KDE4 compatibility: - fileToMoc = headerToMoc; - if (!requiresMoc && (incBasename == scannedFileBasename)) { - std::ostringstream ost; - ost - << "AutoMoc: Warning: " << Quoted(absFilename) << "\n" - << "The file includes the moc file " << Quoted(incString) - << ", but does not contain a Q_OBJECT or Q_GADGET macro.\n" - << "Running moc on " << Quoted(headerToMoc) << "!\n" - << "Include " << Quoted("moc_" + incBasename + ".cpp") - << " for a compatibility with strict mode (see " - "CMAKE_AUTOMOC_RELAXED_MODE).\n"; - this->LogWarning(ost.str()); - } else { - std::ostringstream ost; - ost << "AutoMoc: Warning: " << Quoted(absFilename) << "\n" - << "The file includes the moc file " << Quoted(incString) - << " instead of " - << Quoted("moc_" + incBasename + ".cpp") << ".\n" - << "Running moc on " << Quoted(headerToMoc) << "!\n" - << "Include " << Quoted("moc_" + incBasename + ".cpp") - << " for compatibility with strict mode (see " - "CMAKE_AUTOMOC_RELAXED_MODE).\n"; - this->LogWarning(ost.str()); - } - } + // In relaxed mode try to find a header instead but issue a warning. + // This is for KDE4 compatibility + std::string const header = + this->MocFindIncludedHeader(scanFileDir, mocInc.Dir + mocInc.Base); + if (!header.empty()) { + // Check if header is skipped + if (this->MocSkip(header)) { + continue; + } + // Register moc job + AddJob(header, mocInc.Inc, nullptr); + if (!selfRequiresMoc) { + if (ownMoc) { + std::string emsg = "The file includes the moc file "; + emsg += cmQtAutoGen::Quoted(mocInc.Inc); + emsg += ", but does not contain a "; + emsg += this->MocStringMacros(); + emsg += " macro.\nRunning moc on\n "; + emsg += cmQtAutoGen::Quoted(header); + emsg += "!\nBetter include "; + emsg += cmQtAutoGen::Quoted("moc_" + mocInc.Base + ".cpp"); + emsg += " for a compatibility with strict mode.\n" + "(CMAKE_AUTOMOC_RELAXED_MODE warning)\n"; + this->LogFileWarning(cmQtAutoGen::MOC, absFilename, emsg); } else { - std::ostringstream ost; - ost << "AutoMoc: Error: " << Quoted(absFilename) << "\n" - << "The file includes the moc file " << Quoted(incString) - << ", which seems to be the moc file from a different " - "source file. CMake also could not find a matching " - "header."; - this->LogError(ost.str()); - return false; + std::string emsg = "The file includes the moc file "; + emsg += cmQtAutoGen::Quoted(mocInc.Inc); + emsg += " instead of "; + emsg += cmQtAutoGen::Quoted("moc_" + mocInc.Base + ".cpp"); + emsg += ".\nRunning moc on\n "; + emsg += cmQtAutoGen::Quoted(header); + emsg += "!\nBetter include "; + emsg += cmQtAutoGen::Quoted("moc_" + mocInc.Base + ".cpp"); + emsg += " for compatibility with strict mode.\n" + "(CMAKE_AUTOMOC_RELAXED_MODE warning)\n"; + this->LogFileWarning(cmQtAutoGen::MOC, absFilename, emsg); } } } else { - // Mode: Strict - if (incBasename == scannedFileBasename) { - // Include self - fileToMoc = absFilename; - ownDotMocIncluded = true; - // Accept but issue a warning if moc isn't required - if (!requiresMoc) { - std::ostringstream ost; - ost << "AutoMoc: Warning: " << Quoted(absFilename) << "\n" - << "The file includes the moc file " << Quoted(incString) - << ", but does not contain a Q_OBJECT or Q_GADGET " - "macro."; - this->LogWarning(ost.str()); - } - } else { - // Don't allow FOO.moc include other than self in strict mode - std::ostringstream ost; - ost << "AutoMoc: Error: " << Quoted(absFilename) << "\n" - << "The file includes the moc file " << Quoted(incString) - << ", which seems to be the moc file from a different " - "source file. This is not supported. Include " - << Quoted(scannedFileBasename + ".moc") - << " to run moc on this source file."; - this->LogError(ost.str()); - return false; - } + std::string emsg = "The file includes the moc file "; + emsg += cmQtAutoGen::Quoted(mocInc.Inc); + emsg += ", which seems to be the moc file from a different " + "source file. CMake also could not find a matching " + "header."; + this->LogFileError(cmQtAutoGen::MOC, absFilename, emsg); + return false; } - if (!fileToMoc.empty()) { - mocsIncluded[fileToMoc] = incString; - this->MocFindDepends(fileToMoc, contentText, mocDepends); + } + } else { + // Strict mode + if (ownMoc) { + // Include self + AddJob(absFilename, mocInc.Inc, &contentText); + ownDotMocIncluded = true; + // Accept but issue a warning if moc isn't required + if (!selfRequiresMoc) { + std::string emsg = "The file includes the moc file "; + emsg += cmQtAutoGen::Quoted(mocInc.Inc); + emsg += ", but does not contain a "; + emsg += this->MocStringMacros(); + emsg += " macro."; + this->LogFileWarning(cmQtAutoGen::MOC, absFilename, emsg); } + } else { + // Don't allow <BASE>.moc include other than self in strict mode + std::string emsg = "The file includes the moc file "; + emsg += cmQtAutoGen::Quoted(mocInc.Inc); + emsg += ", which seems to be the moc file from a different " + "source file.\nThis is not supported. Include "; + emsg += cmQtAutoGen::Quoted(scanFileBase + ".moc"); + emsg += " to run moc on this source file."; + this->LogFileError(cmQtAutoGen::MOC, absFilename, emsg); + return false; } - // Forward content pointer - contentChars += this->MocRegExpInclude.end(); } } - if (requiresMoc && !ownDotMocIncluded) { + if (selfRequiresMoc && !ownDotMocIncluded) { // In this case, check whether the scanned file itself contains a Q_OBJECT. // If this is the case, the moc_foo.cpp should probably be generated from // foo.cpp instead of foo.h, because otherwise it won't build. // But warn, since this is not how it is supposed to be used. - if (relaxed && !ownMocUnderscoreInclude.empty()) { + if (this->MocRelaxedMode && !ownMocUscInclude.empty()) { // This is for KDE4 compatibility: - std::ostringstream ost; - ost << "AutoMoc: Warning: " << Quoted(absFilename) << "\n" - << "The file contains a " << macroName - << " macro, but does not include " - << Quoted(scannedFileBasename + ".moc") << ", but instead includes " - << Quoted(ownMocUnderscoreInclude) << ".\n" - << "Running moc on " << Quoted(absFilename) << "!\n" - << "Better include " << Quoted(scannedFileBasename + ".moc") - << " for compatibility with strict mode (see " - "CMAKE_AUTOMOC_RELAXED_MODE)."; - this->LogWarning(ost.str()); - - // Use scanned source file instead of scanned header file as moc source - mocsIncluded[absFilename] = ownMocUnderscoreInclude; - this->MocFindDepends(absFilename, contentText, mocDepends); - // Remove - mocsIncluded.erase(ownMocUnderscoreHeader); + std::string emsg = "The file contains a "; + emsg += selfMacroName; + emsg += " macro, but does not include "; + emsg += cmQtAutoGen::Quoted(scanFileBase + ".moc"); + emsg += ". Instead it includes "; + emsg += cmQtAutoGen::Quoted(ownMocUscInclude); + emsg += ".\nRunning moc on\n "; + emsg += cmQtAutoGen::Quoted(absFilename); + emsg += "!\nBetter include "; + emsg += cmQtAutoGen::Quoted(scanFileBase + ".moc"); + emsg += " for compatibility with strict mode.\n" + "(CMAKE_AUTOMOC_RELAXED_MODE warning)"; + this->LogFileWarning(cmQtAutoGen::MOC, absFilename, emsg); + + // Remove own header job + { + auto itC = this->MocJobsIncluded.begin(); + auto itE = this->MocJobsIncluded.end(); + for (; itC != itE; ++itC) { + if ((*itC)->SourceFile == ownMocUscHeader) { + if ((*itC)->IncludeString == ownMocUscInclude) { + this->MocJobsIncluded.erase(itC); + break; + } + } + } + } + // Add own source job + AddJob(absFilename, ownMocUscInclude, &contentText); } else { // Otherwise always error out since it will not compile: - std::ostringstream ost; - ost << "AutoMoc: Error: " << Quoted(absFilename) << "\n" - << "The file contains a " << macroName - << " macro, but does not include " - << Quoted(scannedFileBasename + ".moc") << "!\n" - << "Consider adding the include or enabling SKIP_AUTOMOC for this " - "file."; - this->LogError(ost.str()); + std::string emsg = "The file contains a "; + emsg += selfMacroName; + emsg += " macro, but does not include "; + emsg += cmQtAutoGen::Quoted(scanFileBase + ".moc"); + emsg += "!\nConsider to\n - add #include \""; + emsg += scanFileBase; + emsg += ".moc\"\n - enable SKIP_AUTOMOC for this file"; + this->LogFileError(cmQtAutoGen::MOC, absFilename, emsg); return false; } } - return true; } -void cmQtAutoGenerators::MocParseHeaderContent( - const std::string& absFilename, const std::string& contentText, - std::map<std::string, std::string>& mocsNotIncluded, - std::map<std::string, std::set<std::string> >& mocDepends) +void cmQtAutoGenerators::MocParseHeaderContent(std::string const& absFilename, + std::string const& contentText) { - // Log if (this->Verbose) { - this->LogInfo("AutoMoc: Checking " + absFilename); - } - if (this->MocRequired(contentText)) { - // Register moc job - mocsNotIncluded[absFilename] = - this->ChecksumedPath(absFilename, "moc_", this->ConfigSuffix + ".cpp"); - this->MocFindDepends(absFilename, contentText, mocDepends); - } -} - -void cmQtAutoGenerators::SearchHeadersForSourceFile( - const std::string& absFilename, std::set<std::string>& mocHeaderFiles, - std::set<std::string>& uicHeaderFiles) const -{ - std::string basepaths[2]; - { - std::string bpath = SubDirPrefix(absFilename); - bpath += cmsys::SystemTools::GetFilenameWithoutLastExtension(absFilename); - // search for default header files and private header files - basepaths[0] = bpath; - basepaths[1] = bpath + "_p"; - } - - for (const std::string* bpit = cmArrayBegin(basepaths); - bpit != cmArrayEnd(basepaths); ++bpit) { - std::string headerName; - if (this->FindHeader(headerName, *bpit)) { - // Moc headers - if (!this->MocSkip(absFilename) && !this->MocSkip(headerName)) { - mocHeaderFiles.insert(headerName); - } - // Uic headers - if (!this->UicSkip(absFilename) && !this->UicSkip(headerName)) { - uicHeaderFiles.insert(headerName); - } - } - } -} - -bool cmQtAutoGenerators::ParseHeaders( - const std::set<std::string>& mocHeaderFiles, - const std::set<std::string>& uicHeaderFiles, - const std::map<std::string, std::string>& mocsIncluded, - std::map<std::string, std::string>& mocsNotIncluded, - std::map<std::string, std::set<std::string> >& mocDepends, - std::map<std::string, std::vector<std::string> >& uisIncluded) -{ - bool success = true; - // Merged header files list to read files only once - std::set<std::string> headerFiles; - headerFiles.insert(mocHeaderFiles.begin(), mocHeaderFiles.end()); - headerFiles.insert(uicHeaderFiles.begin(), uicHeaderFiles.end()); - - for (std::set<std::string>::const_iterator hIt = headerFiles.begin(); - hIt != headerFiles.end(); ++hIt) { - const std::string& headerName = *hIt; - std::string contentText; - if (ReadAll(contentText, headerName)) { - // Parse header content for MOC - if ((mocHeaderFiles.find(headerName) != mocHeaderFiles.end()) && - (mocsIncluded.find(headerName) == mocsIncluded.end())) { - this->MocParseHeaderContent(headerName, contentText, mocsNotIncluded, - mocDepends); - } - // Parse header content for UIC - if (uicHeaderFiles.find(headerName) != uicHeaderFiles.end()) { - this->UicParseContent(headerName, contentText, uisIncluded); + this->LogInfo(cmQtAutoGen::MOC, "Checking: " + absFilename); + } + + auto const fit = + std::find_if(this->MocJobsIncluded.cbegin(), this->MocJobsIncluded.cend(), + [&absFilename](std::unique_ptr<MocJobIncluded> const& job) { + return job->SourceFile == absFilename; + }); + if (fit == this->MocJobsIncluded.cend()) { + if (this->MocRequired(contentText)) { + auto job = cm::make_unique<MocJobAuto>(); + job->SourceFile = absFilename; + { + std::string& bld = job->BuildFileRel; + bld = this->FilePathChecksum.getPart(absFilename); + bld += '/'; + bld += "moc_"; + bld += cmSystemTools::GetFilenameWithoutLastExtension(absFilename); + if (this->MultiConfig != cmQtAutoGen::SINGLE) { + bld += this->ConfigSuffix; + } + bld += ".cpp"; } - } else { - std::ostringstream ost; - ost << "AutoGen: Error: Could not read header file:\n" - << Quoted(headerName); - this->LogError(ost.str()); - success = false; - break; + this->MocFindDepends(absFilename, contentText, job->Depends); + this->MocJobsAuto.push_back(std::move(job)); } } - return success; } -bool cmQtAutoGenerators::MocGenerateAll( - const std::map<std::string, std::string>& mocsIncluded, - const std::map<std::string, std::string>& mocsNotIncluded, - const std::map<std::string, std::set<std::string> >& mocDepends) +bool cmQtAutoGenerators::MocGenerateAll() { if (!this->MocEnabled()) { return true; } - // Look for name collisions + // Look for name collisions in included moc files { - std::multimap<std::string, std::string> collisions; - // Test merged map of included and notIncluded - std::map<std::string, std::string> mergedMocs(mocsIncluded); - mergedMocs.insert(mocsNotIncluded.begin(), mocsNotIncluded.end()); - if (this->NameCollisionTest(mergedMocs, collisions)) { - std::ostringstream ost; - ost << "AutoMoc: Error: " - "The same moc file will be generated " - "from different sources.\n" - "To avoid this error either\n" - "- rename the source files or\n" - "- do not include the (moc_NAME.cpp|NAME.moc) file"; - this->LogErrorNameCollision(ost.str(), collisions); + bool collision = false; + std::map<std::string, std::vector<MocJobIncluded const*>> collisions; + for (auto const& job : this->MocJobsIncluded) { + auto& list = collisions[job->IncludeString]; + if (!list.empty()) { + collision = true; + } + list.push_back(job.get()); + } + if (collision) { + std::string emsg = + "Included moc files with the same name will be " + "generated from different sources.\n" + "Consider to\n" + " - not include the \"moc_<NAME>.cpp\" file\n" + " - add a directory prefix to a \"<NAME>.moc\" include " + "(e.g \"sub/<NAME>.moc\")\n" + " - rename the source file(s)\n" + "Include conflicts\n" + "-----------------\n"; + const auto& colls = collisions; + for (auto const& coll : colls) { + if (coll.second.size() > 1) { + emsg += cmQtAutoGen::Quoted(coll.first); + emsg += " included in\n"; + for (const MocJobIncluded* job : coll.second) { + emsg += " - "; + emsg += cmQtAutoGen::Quoted(job->Includer); + emsg += "\n"; + } + emsg += "would be generated from\n"; + for (const MocJobIncluded* job : coll.second) { + emsg += " - "; + emsg += cmQtAutoGen::Quoted(job->SourceFile); + emsg += "\n"; + } + } + } + this->LogError(cmQtAutoGen::MOC, emsg); return false; } } - // Generate moc_predefs + // (Re)generate moc_predefs.h on demand if (!this->MocPredefsCmd.empty()) { if (this->MocSettingsChanged || - FileAbsentOrOlder(this->MocPredefsFileAbs, this->SettingsFile)) { + !cmSystemTools::FileExists(this->MocPredefsFileAbs)) { if (this->Verbose) { this->LogBold("Generating MOC predefs " + this->MocPredefsFileRel); } @@ -1272,160 +1398,200 @@ bool cmQtAutoGenerators::MocGenerateAll( { // Compose command std::vector<std::string> cmd = this->MocPredefsCmd; - // Add includes - cmd.insert(cmd.end(), this->MocIncludes.begin(), - this->MocIncludes.end()); - // Add definitions - for (std::vector<std::string>::const_iterator it = - this->MocDefinitions.begin(); - it != this->MocDefinitions.end(); ++it) { - cmd.push_back("-D" + (*it)); - } // Add options - cmd.insert(cmd.end(), this->MocOptions.begin(), - this->MocOptions.end()); + cmd.insert(cmd.end(), this->MocAllOptions.begin(), + this->MocAllOptions.end()); // Execute command - if (!this->RunCommand(cmd, output, false)) { - { - std::ostringstream ost; - ost << "AutoMoc: Error: moc predefs generation command failed\n"; - ost << "AutoMoc: Command:\n" << QuotedCommand(cmd) << "\n"; - ost << "AutoMoc: Command output:\n" << output << "\n"; - this->LogError(ost.str()); - } + if (!this->RunCommand(cmd, output)) { + this->LogCommandError(cmQtAutoGen::MOC, + "moc_predefs generation failed", cmd, output); return false; } } + // (Re)write predefs file only on demand if (this->FileDiffers(this->MocPredefsFileAbs, output)) { - if (this->FileWrite("AutoMoc", this->MocPredefsFileAbs, output)) { + if (this->FileWrite(cmQtAutoGen::MOC, this->MocPredefsFileAbs, + output)) { this->MocPredefsChanged = true; } else { + this->LogFileError(cmQtAutoGen::MOC, this->MocPredefsFileAbs, + "moc_predefs file writing failed"); return false; } + } else { + // Touch to update the time stamp + if (this->Verbose) { + this->LogInfo(cmQtAutoGen::MOC, + "Touching moc_predefs " + this->MocPredefsFileRel); + } + cmSystemTools::Touch(this->MocPredefsFileAbs, false); } } + + // Add moc_predefs.h to moc file dependecies + for (auto const& item : this->MocJobsIncluded) { + item->Depends.insert(this->MocPredefsFileAbs); + } + for (auto const& item : this->MocJobsAuto) { + item->Depends.insert(this->MocPredefsFileAbs); + } } // Generate moc files that are included by source files. - for (std::map<std::string, std::string>::const_iterator it = - mocsIncluded.begin(); - it != mocsIncluded.end(); ++it) { - if (!this->MocGenerateFile(it->first, it->second, mocDepends, true)) { - if (this->MocRunFailed) { - return false; - } + for (auto const& item : this->MocJobsIncluded) { + if (!this->MocGenerateFile(*item)) { + return false; } } - // Generate moc files that are _not_ included by source files. - bool mocCompFileGenerated = false; - for (std::map<std::string, std::string>::const_iterator it = - mocsNotIncluded.begin(); - it != mocsNotIncluded.end(); ++it) { - if (this->MocGenerateFile(it->first, it->second, mocDepends, false)) { - mocCompFileGenerated = true; - } else { - if (this->MocRunFailed) { - return false; - } + bool autoNameGenerated = false; + for (auto const& item : this->MocJobsAuto) { + if (!this->MocGenerateFile(*item, &autoNameGenerated)) { + return false; } } // Compose mocs compilation file content - std::string automocSource; { - std::ostringstream ost; - ost << "/* This file is autogenerated, do not edit*/\n"; - if (mocsNotIncluded.empty()) { - // Dummy content - ost << "enum some_compilers { need_more_than_nothing };\n"; + std::string mocs = + "// This file is autogenerated. Changes will be overwritten.\n"; + if (this->MocJobsAuto.empty()) { + // Placeholder content + mocs += + "// No files found that require moc or the moc files are included\n"; + mocs += "enum some_compilers { need_more_than_nothing };\n"; } else { // Valid content - for (std::map<std::string, std::string>::const_iterator it = - mocsNotIncluded.begin(); - it != mocsNotIncluded.end(); ++it) { - ost << "#include \"" << it->second << "\"\n"; + for (const auto& item : this->MocJobsAuto) { + mocs += "#include \""; + mocs += item->BuildFileRel; + mocs += "\"\n"; } } - automocSource = ost.str(); - } - if (this->FileDiffers(this->MocCompFileAbs, automocSource)) { - // Actually write mocs compilation file - if (this->Verbose) { - this->LogBold("Generating MOC compilation " + this->MocCompFileRel); - } - if (!this->FileWrite("AutoMoc", this->MocCompFileAbs, automocSource)) { - return false; - } - } else if (mocCompFileGenerated) { - // Only touch mocs compilation file - if (this->Verbose) { - this->LogInfo("Touching MOC compilation " + this->MocCompFileRel); + if (this->FileDiffers(this->MocCompFileAbs, mocs)) { + // Actually write mocs compilation file + if (this->Verbose) { + this->LogBold("Generating MOC compilation " + this->MocCompFileRel); + } + if (!this->FileWrite(cmQtAutoGen::MOC, this->MocCompFileAbs, mocs)) { + this->LogFileError(cmQtAutoGen::MOC, this->MocCompFileAbs, + "mocs compilation file writing failed"); + return false; + } + } else if (autoNameGenerated) { + // Only touch mocs compilation file + if (this->Verbose) { + this->LogInfo(cmQtAutoGen::MOC, + "Touching mocs compilation " + this->MocCompFileRel); + } + cmSystemTools::Touch(this->MocCompFileAbs, false); } - cmSystemTools::Touch(this->MocCompFileAbs, false); } return true; } /** - * @return True if a moc file was created. False may indicate an error. + * @return True on success */ -bool cmQtAutoGenerators::MocGenerateFile( - const std::string& sourceFile, const std::string& mocFileName, - const std::map<std::string, std::set<std::string> >& mocDepends, - bool included) +bool cmQtAutoGenerators::MocGenerateFile(const MocJobAuto& mocJob, + bool* generated) { - bool mocGenerated = false; - bool generateMoc = this->MocSettingsChanged || this->MocPredefsChanged; - - const std::string mocFileRel = - included ? (this->AutogenIncludeDir + mocFileName) : mocFileName; - const std::string mocFileAbs = - cmSystemTools::CollapseCombinedPath(this->AutogenBuildDir, mocFileRel); - - if (!generateMoc) { - // Test if the source file is newer that the build file - generateMoc = FileAbsentOrOlder(mocFileAbs, sourceFile); - if (!generateMoc) { - // Test if a dependency file changed - std::map<std::string, std::set<std::string> >::const_iterator dit = - mocDepends.find(sourceFile); - if (dit != mocDepends.end()) { - for (std::set<std::string>::const_iterator fit = dit->second.begin(); - fit != dit->second.end(); ++fit) { - if (FileAbsentOrOlder(mocFileAbs, *fit)) { - generateMoc = true; - break; - } + bool success = true; + + std::string const mocFileAbs = cmSystemTools::CollapseCombinedPath( + this->AutogenBuildDir, mocJob.BuildFileRel); + + bool generate = false; + std::string generateReason; + if (!generate && !cmSystemTools::FileExists(mocFileAbs.c_str())) { + if (this->Verbose) { + generateReason = "Generating "; + generateReason += cmQtAutoGen::Quoted(mocFileAbs); + generateReason += " from its source file "; + generateReason += cmQtAutoGen::Quoted(mocJob.SourceFile); + generateReason += " because it doesn't exist"; + } + generate = true; + } + if (!generate && this->MocSettingsChanged) { + if (this->Verbose) { + generateReason = "Generating "; + generateReason += cmQtAutoGen::Quoted(mocFileAbs); + generateReason += " from "; + generateReason += cmQtAutoGen::Quoted(mocJob.SourceFile); + generateReason += " because the MOC settings changed"; + } + generate = true; + } + if (!generate && this->MocPredefsChanged) { + if (this->Verbose) { + generateReason = "Generating "; + generateReason += cmQtAutoGen::Quoted(mocFileAbs); + generateReason += " from "; + generateReason += cmQtAutoGen::Quoted(mocJob.SourceFile); + generateReason += " because moc_predefs.h changed"; + } + generate = true; + } + if (!generate) { + std::string error; + if (FileIsOlderThan(mocFileAbs, mocJob.SourceFile, &error)) { + if (this->Verbose) { + generateReason = "Generating "; + generateReason += cmQtAutoGen::Quoted(mocFileAbs); + generateReason += " because it's older than its source file "; + generateReason += cmQtAutoGen::Quoted(mocJob.SourceFile); + } + generate = true; + } else { + if (!error.empty()) { + this->LogError(cmQtAutoGen::MOC, error); + success = false; + } + } + } + if (success && !generate) { + // Test if a dependency file is newer + std::string error; + for (std::string const& depFile : mocJob.Depends) { + if (FileIsOlderThan(mocFileAbs, depFile, &error)) { + if (this->Verbose) { + generateReason = "Generating "; + generateReason += cmQtAutoGen::Quoted(mocFileAbs); + generateReason += " from "; + generateReason += cmQtAutoGen::Quoted(mocJob.SourceFile); + generateReason += " because it is older than "; + generateReason += cmQtAutoGen::Quoted(depFile); } + generate = true; + break; + } + if (!error.empty()) { + this->LogError(cmQtAutoGen::MOC, error); + success = false; + break; } } } - if (generateMoc) { + + if (generate) { // Log if (this->Verbose) { - this->LogBold("Generating MOC source " + mocFileRel); + this->LogBold("Generating MOC source " + mocJob.BuildFileRel); + this->LogInfo(cmQtAutoGen::MOC, generateReason); } // Make sure the parent directory exists - if (this->MakeParentDirectory("AutoMoc", mocFileAbs)) { + if (this->MakeParentDirectory(cmQtAutoGen::MOC, mocFileAbs)) { // Compose moc command std::vector<std::string> cmd; cmd.push_back(this->MocExecutable); - // Add includes - cmd.insert(cmd.end(), this->MocIncludes.begin(), - this->MocIncludes.end()); - // Add definitions - for (std::vector<std::string>::const_iterator it = - this->MocDefinitions.begin(); - it != this->MocDefinitions.end(); ++it) { - cmd.push_back("-D" + (*it)); - } // Add options - cmd.insert(cmd.end(), this->MocOptions.begin(), this->MocOptions.end()); + cmd.insert(cmd.end(), this->MocAllOptions.begin(), + this->MocAllOptions.end()); // Add predefs include if (!this->MocPredefsFileAbs.empty()) { cmd.push_back("--include"); @@ -1433,47 +1599,119 @@ bool cmQtAutoGenerators::MocGenerateFile( } cmd.push_back("-o"); cmd.push_back(mocFileAbs); - cmd.push_back(sourceFile); + cmd.push_back(mocJob.SourceFile); // Execute moc command std::string output; if (this->RunCommand(cmd, output)) { // Success - mocGenerated = true; + if (generated != nullptr) { + *generated = true; + } } else { - // Command failed + // Moc command failed { - std::ostringstream ost; - ost << "AutoMoc: Error: moc process failed for\n"; - ost << Quoted(mocFileRel) << "\n"; - ost << "AutoMoc: Command:\n" << QuotedCommand(cmd) << "\n"; - ost << "AutoMoc: Command output:\n" << output << "\n"; - this->LogError(ost.str()); + std::string emsg = "moc failed for\n "; + emsg += cmQtAutoGen::Quoted(mocJob.SourceFile); + this->LogCommandError(cmQtAutoGen::MOC, emsg, cmd, output); } cmSystemTools::RemoveFile(mocFileAbs); - this->MocRunFailed = true; + success = false; } } else { // Parent directory creation failed - this->MocRunFailed = true; + success = false; } } - return mocGenerated; + return success; +} + +/** + * @brief Tests if the file name is in the skip list + */ +bool cmQtAutoGenerators::UicSkip(std::string const& absFilename) const +{ + if (this->UicEnabled()) { + // Test if the file name is on the skip list + if (!ListContains(this->UicSkipList, absFilename)) { + return false; + } + } + return true; +} + +bool cmQtAutoGenerators::UicParseContent(std::string const& absFilename, + std::string const& contentText) +{ + if (this->Verbose) { + this->LogInfo(cmQtAutoGen::UIC, "Checking: " + absFilename); + } + + std::vector<std::string> includes; + // Extracte includes + { + const char* contentChars = contentText.c_str(); + if (strstr(contentChars, "ui_") != nullptr) { + while (this->UicRegExpInclude.find(contentChars)) { + includes.push_back(this->UicRegExpInclude.match(1)); + contentChars += this->UicRegExpInclude.end(); + } + } + } + + for (std::string const& includeString : includes) { + std::string uiInputFile; + if (!UicFindIncludedFile(uiInputFile, absFilename, includeString)) { + return false; + } + // Check if this file should be skipped + if (this->UicSkip(uiInputFile)) { + continue; + } + // Check if the job already exists + bool jobExists = false; + for (const auto& job : this->UicJobs) { + if ((job->SourceFile == uiInputFile) && + (job->IncludeString == includeString)) { + jobExists = true; + break; + } + } + if (!jobExists) { + auto job = cm::make_unique<UicJob>(); + job->SourceFile = uiInputFile; + job->BuildFileRel = this->AutogenIncludeDir; + job->BuildFileRel += includeString; + job->Includer = absFilename; + job->IncludeString = includeString; + this->UicJobs.push_back(std::move(job)); + } + } + + return true; } bool cmQtAutoGenerators::UicFindIncludedFile(std::string& absFile, - const std::string& sourceFile, - const std::string& searchPath, - const std::string& searchFile) + std::string const& sourceFile, + std::string const& includeString) { bool success = false; - std::vector<std::string> testFiles; + std::string searchFile = + cmSystemTools::GetFilenameWithoutLastExtension(includeString).substr(3); + searchFile += ".ui"; // Collect search paths list + std::vector<std::string> testFiles; { - const std::string searchFileFull = searchPath + searchFile; + std::string const searchPath = SubDirPrefix(includeString); + + std::string searchFileFull; + if (!searchPath.empty()) { + searchFileFull = searchPath; + searchFileFull += searchFile; + } // Vicinity of the source { - const std::string sourcePath = SubDirPrefix(sourceFile); + std::string const sourcePath = SubDirPrefix(sourceFile); testFiles.push_back(sourcePath + searchFile); if (!searchPath.empty()) { testFiles.push_back(sourcePath + searchFileFull); @@ -1481,27 +1719,21 @@ bool cmQtAutoGenerators::UicFindIncludedFile(std::string& absFile, } // AUTOUIC search paths if (!this->UicSearchPaths.empty()) { - for (std::vector<std::string>::const_iterator iit = - this->UicSearchPaths.begin(); - iit != this->UicSearchPaths.end(); ++iit) { - testFiles.push_back(*iit + "/" + searchFile); + for (std::string const& sPath : this->UicSearchPaths) { + testFiles.push_back((sPath + "/").append(searchFile)); } if (!searchPath.empty()) { - for (std::vector<std::string>::const_iterator iit = - this->UicSearchPaths.begin(); - iit != this->UicSearchPaths.end(); ++iit) { - testFiles.push_back(*iit + "/" + searchFileFull); + for (std::string const& sPath : this->UicSearchPaths) { + testFiles.push_back((sPath + "/").append(searchFileFull)); } } } } // Search for the .ui file! - for (std::vector<std::string>::const_iterator iit = testFiles.begin(); - iit != testFiles.end(); ++iit) { - const std::string& testFile = *iit; - if (cmsys::SystemTools::FileExists(testFile.c_str())) { - absFile = cmsys::SystemTools::GetRealPath(testFile); + for (std::string const& testFile : testFiles) { + if (cmSystemTools::FileExists(testFile.c_str())) { + absFile = cmSystemTools::GetRealPath(testFile); success = true; break; } @@ -1509,84 +1741,75 @@ bool cmQtAutoGenerators::UicFindIncludedFile(std::string& absFile, // Log error if (!success) { - std::ostringstream ost; - ost << "AutoUic: Error: " << Quoted(sourceFile) << "\n"; - ost << "Could not find " << Quoted(searchFile) << " in\n"; - for (std::vector<std::string>::const_iterator iit = testFiles.begin(); - iit != testFiles.end(); ++iit) { - ost << " " << Quoted(*iit) << "\n"; + std::string emsg = "Could not find "; + emsg += cmQtAutoGen::Quoted(searchFile); + emsg += " in\n"; + for (std::string const& testFile : testFiles) { + emsg += " "; + emsg += cmQtAutoGen::Quoted(testFile); + emsg += "\n"; } - this->LogError(ost.str()); + this->LogFileError(cmQtAutoGen::UIC, sourceFile, emsg); } return success; } -bool cmQtAutoGenerators::UicGenerateAll( - const std::map<std::string, std::vector<std::string> >& uisIncluded) +bool cmQtAutoGenerators::UicGenerateAll() { if (!this->UicEnabled()) { return true; } - // single map with input / output names - std::map<std::string, std::map<std::string, std::string> > sourceGenMap; + // Look for name collisions in included uic files { - // Collision lookup map - std::map<std::string, std::string> testMap; - // Compile maps - for (std::map<std::string, std::vector<std::string> >::const_iterator sit = - uisIncluded.begin(); - sit != uisIncluded.end(); ++sit) { - const std::string& source(sit->first); - const std::vector<std::string>& sourceIncs(sit->second); - // insert new source/destination map - std::map<std::string, std::string>& uiGenMap = sourceGenMap[source]; - for (std::vector<std::string>::const_iterator uit = sourceIncs.begin(); - uit != sourceIncs.end(); ++uit) { - // Remove ui_ from the begin filename by substr() - const std::string uiBasePath = SubDirPrefix(*uit); - const std::string uiBaseName = - cmsys::SystemTools::GetFilenameWithoutLastExtension(*uit).substr(3); - const std::string uiFileName = uiBaseName + ".ui"; - std::string uiInputFile; - if (UicFindIncludedFile(uiInputFile, source, uiBasePath, uiFileName)) { - std::string uiOutputFile = uiBasePath + "ui_" + uiBaseName + ".h"; - cmSystemTools::ReplaceString(uiOutputFile, "..", "__"); - uiGenMap[uiInputFile] = uiOutputFile; - testMap[uiInputFile] = uiOutputFile; - } else { - return false; - } + bool collision = false; + std::map<std::string, std::vector<UicJob const*>> collisions; + for (auto const& job : this->UicJobs) { + auto& list = collisions[job->IncludeString]; + if (!list.empty()) { + collision = true; } - } - // look for name collisions - { - std::multimap<std::string, std::string> collisions; - if (this->NameCollisionTest(testMap, collisions)) { - std::ostringstream ost; - ost << "AutoUic: Error: The same ui_NAME.h file will be generated " - "from different sources.\n" - "To avoid this error rename the source files.\n"; - this->LogErrorNameCollision(ost.str(), collisions); - return false; + list.push_back(job.get()); + } + if (collision) { + std::string emsg = + "Included uic files with the same name will be " + "generated from different sources.\n" + "Consider to\n" + " - add a directory prefix to a \"ui_<NAME>.h\" include " + "(e.g \"sub/ui_<NAME>.h\")\n" + " - rename the <NAME>.ui file(s) and adjust the \"ui_<NAME>.h\" " + "include(s)\n" + "Include conflicts\n" + "-----------------\n"; + const auto& colls = collisions; + for (auto const& coll : colls) { + if (coll.second.size() > 1) { + emsg += cmQtAutoGen::Quoted(coll.first); + emsg += " included in\n"; + for (const UicJob* job : coll.second) { + emsg += " - "; + emsg += cmQtAutoGen::Quoted(job->Includer); + emsg += "\n"; + } + emsg += "would be generated from\n"; + for (const UicJob* job : coll.second) { + emsg += " - "; + emsg += cmQtAutoGen::Quoted(job->SourceFile); + emsg += "\n"; + } + } } + this->LogError(cmQtAutoGen::UIC, emsg); + return false; } } - // generate ui files - for (std::map<std::string, - std::map<std::string, std::string> >::const_iterator it = - sourceGenMap.begin(); - it != sourceGenMap.end(); ++it) { - for (std::map<std::string, std::string>::const_iterator sit = - it->second.begin(); - sit != it->second.end(); ++sit) { - if (!this->UicGenerateFile(it->first, sit->first, sit->second)) { - if (this->UicRunFailed) { - return false; - } - } + // Generate ui header files + for (const auto& item : this->UicJobs) { + if (!this->UicGenerateFile(*item)) { + return false; } } @@ -1594,73 +1817,100 @@ bool cmQtAutoGenerators::UicGenerateAll( } /** - * @return True if a uic file was created. False may indicate an error. + * @return True on success */ -bool cmQtAutoGenerators::UicGenerateFile(const std::string& realName, - const std::string& uiInputFile, - const std::string& uiOutputFile) +bool cmQtAutoGenerators::UicGenerateFile(const UicJob& uicJob) { - bool uicGenerated = false; - bool generateUic = this->UicSettingsChanged; + bool success = true; - const std::string uicFileRel = this->AutogenIncludeDir + uiOutputFile; - const std::string uicFileAbs = - cmSystemTools::CollapseCombinedPath(this->AutogenBuildDir, uicFileRel); + std::string const uicFileAbs = cmSystemTools::CollapseCombinedPath( + this->AutogenBuildDir, uicJob.BuildFileRel); - if (!generateUic) { - // Test if the source file is newer that the build file - generateUic = FileAbsentOrOlder(uicFileAbs, uiInputFile); + bool generate = false; + std::string generateReason; + if (!generate && !cmSystemTools::FileExists(uicFileAbs.c_str())) { + if (this->Verbose) { + generateReason = "Generating "; + generateReason += cmQtAutoGen::Quoted(uicFileAbs); + generateReason += " from its source file "; + generateReason += cmQtAutoGen::Quoted(uicJob.SourceFile); + generateReason += " because it doesn't exist"; + } + generate = true; + } + if (!generate && this->UicSettingsChanged) { + if (this->Verbose) { + generateReason = "Generating "; + generateReason += cmQtAutoGen::Quoted(uicFileAbs); + generateReason += " from "; + generateReason += cmQtAutoGen::Quoted(uicJob.SourceFile); + generateReason += " because the UIC settings changed"; + } + generate = true; + } + if (!generate) { + std::string error; + if (FileIsOlderThan(uicFileAbs, uicJob.SourceFile, &error)) { + if (this->Verbose) { + generateReason = "Generating "; + generateReason += cmQtAutoGen::Quoted(uicFileAbs); + generateReason += " because it's older than its source file "; + generateReason += cmQtAutoGen::Quoted(uicJob.SourceFile); + } + generate = true; + } else { + if (!error.empty()) { + this->LogError(cmQtAutoGen::UIC, error); + success = false; + } + } } - if (generateUic) { + if (generate) { // Log if (this->Verbose) { - this->LogBold("Generating UIC header " + uicFileRel); + this->LogBold("Generating UIC header " + uicJob.BuildFileRel); + this->LogInfo(cmQtAutoGen::UIC, generateReason); } // Make sure the parent directory exists - if (this->MakeParentDirectory("AutoUic", uicFileAbs)) { + if (this->MakeParentDirectory(cmQtAutoGen::UIC, uicFileAbs)) { // Compose uic command std::vector<std::string> cmd; cmd.push_back(this->UicExecutable); { std::vector<std::string> allOpts = this->UicTargetOptions; - std::map<std::string, std::string>::const_iterator optionIt = - this->UicOptions.find(uiInputFile); + auto optionIt = this->UicOptions.find(uicJob.SourceFile); if (optionIt != this->UicOptions.end()) { - std::vector<std::string> fileOpts; - cmSystemTools::ExpandListArgument(optionIt->second, fileOpts); - UicMergeOptions(allOpts, fileOpts, (this->QtMajorVersion == "5")); + cmQtAutoGen::UicMergeOptions(allOpts, optionIt->second, + (this->QtMajorVersion == "5")); } cmd.insert(cmd.end(), allOpts.begin(), allOpts.end()); } cmd.push_back("-o"); cmd.push_back(uicFileAbs); - cmd.push_back(uiInputFile); + cmd.push_back(uicJob.SourceFile); std::string output; if (this->RunCommand(cmd, output)) { // Success - uicGenerated = true; } else { // Command failed { - std::ostringstream ost; - ost << "AutoUic: Error: uic process failed for\n"; - ost << Quoted(uicFileRel) << " needed by\n"; - ost << Quoted(realName) << "\n"; - ost << "AutoUic: Command:\n" << QuotedCommand(cmd) << "\n"; - ost << "AutoUic: Command output:\n" << output << "\n"; - this->LogError(ost.str()); + std::string emsg = "uic failed for\n "; + emsg += cmQtAutoGen::Quoted(uicJob.SourceFile); + emsg += "\nincluded by\n "; + emsg += cmQtAutoGen::Quoted(uicJob.Includer); + this->LogCommandError(cmQtAutoGen::UIC, emsg, cmd, output); } cmSystemTools::RemoveFile(uicFileAbs); - this->UicRunFailed = true; + success = false; } } else { // Parent directory creation failed - this->UicRunFailed = true; + success = false; } } - return uicGenerated; + return success; } bool cmQtAutoGenerators::RccGenerateAll() @@ -1669,360 +1919,365 @@ bool cmQtAutoGenerators::RccGenerateAll() return true; } - // generate single map with input / output names - std::map<std::string, std::string> qrcGenMap; - { - const std::string qrcPrefix = "qrc_"; - const std::string qrcSuffix = this->ConfigSuffix + ".cpp"; - for (std::vector<std::string>::const_iterator si = - this->RccSources.begin(); - si != this->RccSources.end(); ++si) { - const std::string ext = - cmsys::SystemTools::GetFilenameLastExtension(*si); - if (ext == ".qrc") { - qrcGenMap[*si] = this->ChecksumedPath(*si, qrcPrefix, qrcSuffix); - } - } - } - - // look for name collisions - { - std::multimap<std::string, std::string> collisions; - if (this->NameCollisionTest(qrcGenMap, collisions)) { - std::ostringstream ost; - ost << "AutoRcc: Error: The same qrc_NAME.cpp file" - " will be generated from different sources.\n" - "To avoid this error rename the source .qrc files.\n"; - this->LogErrorNameCollision(ost.str(), collisions); + // Generate rcc files + for (const RccJob& rccJob : this->RccJobs) { + if (!this->RccGenerateFile(rccJob)) { return false; } } - - // generate qrc files - for (std::map<std::string, std::string>::const_iterator si = - qrcGenMap.begin(); - si != qrcGenMap.end(); ++si) { - bool unique = FileNameIsUnique(si->first, qrcGenMap); - if (!this->RccGenerateFile(si->first, si->second, unique)) { - if (this->RccRunFailed) { - return false; - } - } - } return true; } /** - * @return True if a rcc file was created. False may indicate an error. + * @return True on success */ -bool cmQtAutoGenerators::RccGenerateFile(const std::string& rccInputFile, - const std::string& rccOutputFile, - bool unique_n) +bool cmQtAutoGenerators::RccGenerateFile(const RccJob& rccJob) { + bool success = true; bool rccGenerated = false; - bool generateRcc = this->RccSettingsChanged; - const std::string rccBuildFile = - cmSystemTools::CollapseCombinedPath(this->AutogenBuildDir, rccOutputFile); + + std::string rccFileAbs; + if (this->MultiConfig == cmQtAutoGen::SINGLE) { + rccFileAbs = rccJob.RccFile; + } else { + rccFileAbs = + cmQtAutoGen::AppendFilenameSuffix(rccJob.RccFile, this->ConfigSuffix); + } + std::string const rccFileRel = cmSystemTools::RelativePath( + this->AutogenBuildDir.c_str(), rccFileAbs.c_str()); // Check if regeneration is required - if (!generateRcc) { - // Test if the resources list file is newer than build file - generateRcc = FileAbsentOrOlder(rccBuildFile, rccInputFile); - if (!generateRcc) { - // Acquire input file list - std::vector<std::string> readFiles; - const std::vector<std::string>* files = &this->RccInputs[rccInputFile]; - if (files->empty()) { - // Read input file list from qrc file - std::string error; - if (cmQtAutoGeneratorCommon::RccListInputs( - this->QtMajorVersion, this->RccExecutable, rccInputFile, - readFiles, &error)) { - files = &readFiles; - } else { - files = nullptr; - this->LogError(error); - this->RccRunFailed = true; - } + bool generate = false; + std::string generateReason; + if (!cmSystemTools::FileExists(rccJob.QrcFile)) { + { + std::string error = "Could not find the file\n "; + error += cmQtAutoGen::Quoted(rccJob.QrcFile); + this->LogError(cmQtAutoGen::RCC, error); + } + success = false; + } + if (success && !generate && !cmSystemTools::FileExists(rccFileAbs.c_str())) { + if (this->Verbose) { + generateReason = "Generating "; + generateReason += cmQtAutoGen::Quoted(rccFileAbs); + generateReason += " from its source file "; + generateReason += cmQtAutoGen::Quoted(rccJob.QrcFile); + generateReason += " because it doesn't exist"; + } + generate = true; + } + if (success && !generate && this->RccSettingsChanged) { + if (this->Verbose) { + generateReason = "Generating "; + generateReason += cmQtAutoGen::Quoted(rccFileAbs); + generateReason += " from "; + generateReason += cmQtAutoGen::Quoted(rccJob.QrcFile); + generateReason += " because the RCC settings changed"; + } + generate = true; + } + if (success && !generate) { + std::string error; + if (FileIsOlderThan(rccFileAbs, rccJob.QrcFile, &error)) { + if (this->Verbose) { + generateReason = "Generating "; + generateReason += cmQtAutoGen::Quoted(rccFileAbs); + generateReason += " because it is older than "; + generateReason += cmQtAutoGen::Quoted(rccJob.QrcFile); + } + generate = true; + } else { + if (!error.empty()) { + this->LogError(cmQtAutoGen::RCC, error); + success = false; } - // Test if any input file is newer than the build file - if (files != nullptr) { - for (std::vector<std::string>::const_iterator it = files->begin(); - it != files->end(); ++it) { - if (FileAbsentOrOlder(rccBuildFile, *it)) { - generateRcc = true; - break; + } + } + if (success && !generate) { + // Acquire input file list + std::vector<std::string> readFiles; + std::vector<std::string> const* files = nullptr; + if (!rccJob.Inputs.empty()) { + files = &rccJob.Inputs; + } else { + // Read input file list from qrc file + std::string error; + if (cmQtAutoGen::RccListInputs(this->QtMajorVersion, this->RccExecutable, + rccJob.QrcFile, readFiles, &error)) { + files = &readFiles; + } else { + this->LogFileError(cmQtAutoGen::RCC, rccJob.QrcFile, error); + success = false; + } + } + // Test if any input file is newer than the build file + if (files != nullptr) { + std::string error; + for (std::string const& resFile : *files) { + if (!cmSystemTools::FileExists(resFile.c_str())) { + error = "Could not find the file\n "; + error += cmQtAutoGen::Quoted(resFile); + error += "\nwhich is listed in\n "; + error += cmQtAutoGen::Quoted(rccJob.QrcFile); + break; + } + if (FileIsOlderThan(rccFileAbs, resFile, &error)) { + if (this->Verbose) { + generateReason = "Generating "; + generateReason += cmQtAutoGen::Quoted(rccFileAbs); + generateReason += " from "; + generateReason += cmQtAutoGen::Quoted(rccJob.QrcFile); + generateReason += " because it is older than "; + generateReason += cmQtAutoGen::Quoted(resFile); } + generate = true; + break; } + if (!error.empty()) { + break; + } + } + // Print error + if (!error.empty()) { + this->LogError(cmQtAutoGen::RCC, error); + success = false; } } } // Regenerate on demand - if (generateRcc) { + if (generate) { // Log if (this->Verbose) { - this->LogBold("Generating RCC source " + rccOutputFile); + this->LogBold("Generating RCC source " + rccFileRel); + this->LogInfo(cmQtAutoGen::RCC, generateReason); } // Make sure the parent directory exists - if (this->MakeParentDirectory("AutoRcc", rccBuildFile)) { - // Compose symbol name - std::string symbolName = - cmsys::SystemTools::GetFilenameWithoutLastExtension(rccInputFile); - if (!unique_n) { - symbolName += "_"; - symbolName += FPathChecksum.getPart(rccInputFile); - } - // Replace '-' with '_'. The former is valid for - // file names but not for symbol names. - std::replace(symbolName.begin(), symbolName.end(), '-', '_'); - + if (this->MakeParentDirectory(cmQtAutoGen::RCC, rccFileAbs)) { // Compose rcc command std::vector<std::string> cmd; cmd.push_back(this->RccExecutable); - { - std::map<std::string, std::string>::const_iterator optionIt = - this->RccOptions.find(rccInputFile); - if (optionIt != this->RccOptions.end()) { - cmSystemTools::ExpandListArgument(optionIt->second, cmd); - } - } - cmd.push_back("-name"); - cmd.push_back(symbolName); + cmd.insert(cmd.end(), rccJob.Options.begin(), rccJob.Options.end()); cmd.push_back("-o"); - cmd.push_back(rccBuildFile); - cmd.push_back(rccInputFile); + cmd.push_back(rccFileAbs); + cmd.push_back(rccJob.QrcFile); std::string output; if (this->RunCommand(cmd, output)) { // Success rccGenerated = true; } else { - // Command failed { - std::ostringstream ost; - ost << "AutoRcc: Error: rcc process failed for\n"; - ost << Quoted(rccOutputFile) << "\n"; - ost << "AutoRcc: Command:\n" << QuotedCommand(cmd) << "\n"; - ost << "AutoRcc: Command output:\n" << output << "\n"; - this->LogError(ost.str()); + std::string emsg = "rcc failed for\n "; + emsg += cmQtAutoGen::Quoted(rccJob.QrcFile); + this->LogCommandError(cmQtAutoGen::RCC, emsg, cmd, output); } - cmSystemTools::RemoveFile(rccBuildFile); - this->RccRunFailed = true; + cmSystemTools::RemoveFile(rccFileAbs); + success = false; } } else { // Parent directory creation failed - this->RccRunFailed = true; + success = false; } } - // For a multi configuration generator generate a wrapper file - if (!this->ConfigSuffix.empty() && !this->RccRunFailed) { + + // Generate a wrapper source file on demand + if (success && (this->MultiConfig == cmQtAutoGen::WRAP)) { // Wrapper file name - const std::string cppSuffix = ".cpp"; - const size_t suffixLength = this->ConfigSuffix.size() + cppSuffix.size(); - const std::string wrapperFileRel = - rccOutputFile.substr(0, rccOutputFile.size() - suffixLength) + cppSuffix; - const std::string wrapperFileAbs = cmSystemTools::CollapseCombinedPath( - this->AutogenBuildDir, wrapperFileRel); + std::string const& wrapperFileAbs = rccJob.RccFile; + std::string const wrapperFileRel = cmSystemTools::RelativePath( + this->AutogenBuildDir.c_str(), wrapperFileAbs.c_str()); // Wrapper file content - std::string content = - "// This is an autogenerated configuration wrapper file. Do not edit.\n" - "#include \""; - content += cmsys::SystemTools::GetFilenameName(rccBuildFile); + std::string content = "// This is an autogenerated configuration " + "wrapper file. Changes will be overwritten.\n" + "#include \""; + content += cmSystemTools::GetFilenameName(rccFileRel); content += "\"\n"; // Write content to file if (this->FileDiffers(wrapperFileAbs, content)) { - // Write new wrapper file if the content differs + // Write new wrapper file if (this->Verbose) { this->LogBold("Generating RCC wrapper " + wrapperFileRel); } - if (!this->FileWrite("AutoRcc", wrapperFileAbs, content)) { - // Error - rccGenerated = false; - this->RccRunFailed = true; + if (!this->FileWrite(cmQtAutoGen::RCC, wrapperFileAbs, content)) { + this->LogFileError(cmQtAutoGen::RCC, wrapperFileAbs, + "rcc wrapper file writing failed"); + success = false; } } else if (rccGenerated) { - // Only touch wrapper file if the content matches + // Just touch the wrapper file if (this->Verbose) { - this->LogInfo("Touching RCC wrapper " + wrapperFileRel); + this->LogInfo(cmQtAutoGen::RCC, + "Touching RCC wrapper " + wrapperFileRel); } cmSystemTools::Touch(wrapperFileAbs, false); } } - return rccGenerated; -} - -void cmQtAutoGenerators::LogErrorNameCollision( - const std::string& message, - const std::multimap<std::string, std::string>& collisions) const -{ - typedef std::multimap<std::string, std::string>::const_iterator Iter; - - std::ostringstream ost; - // Add message - if (!message.empty()) { - ost << message; - if (message[message.size() - 1] != '\n') { - ost << '\n'; - } - } - // Append collision list - for (Iter it = collisions.begin(); it != collisions.end(); ++it) { - ost << it->first << " : " << it->second << '\n'; - } - this->LogError(ost.str()); + return success; } -void cmQtAutoGenerators::LogBold(const std::string& message) const +void cmQtAutoGenerators::LogBold(std::string const& message) const { cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundBlue | cmsysTerminal_Color_ForegroundBold, message.c_str(), true, this->ColorOutput); } -void cmQtAutoGenerators::LogInfo(const std::string& message) const +void cmQtAutoGenerators::LogInfo(cmQtAutoGen::Generator genType, + std::string const& message) const { - std::string msg(message); - if (!msg.empty()) { - if (msg[msg.size() - 1] != '\n') { - msg.push_back('\n'); - } - cmSystemTools::Stdout(msg.c_str(), msg.size()); + std::string msg = cmQtAutoGen::GeneratorName(genType); + msg += ": "; + msg += message; + if (msg.back() != '\n') { + msg.push_back('\n'); } + cmSystemTools::Stdout(msg.c_str(), msg.size()); } -void cmQtAutoGenerators::LogWarning(const std::string& message) const +void cmQtAutoGenerators::LogWarning(cmQtAutoGen::Generator genType, + std::string const& message) const { - std::string msg(message); - if (!msg.empty()) { - if (msg[msg.size() - 1] != '\n') { - msg.push_back('\n'); - } - // Append empty line + std::string msg = cmQtAutoGen::GeneratorName(genType); + msg += " warning:"; + if (message.find('\n') == std::string::npos) { + // Single line message + msg.push_back(' '); + } else { + // Multi line message msg.push_back('\n'); - cmSystemTools::Stdout(msg.c_str(), msg.size()); } + // Message + msg += message; + if (msg.back() != '\n') { + msg.push_back('\n'); + } + msg.push_back('\n'); + cmSystemTools::Stdout(msg.c_str(), msg.size()); } -void cmQtAutoGenerators::LogError(const std::string& message) const +void cmQtAutoGenerators::LogFileWarning(cmQtAutoGen::Generator genType, + std::string const& filename, + std::string const& message) const { - std::string msg(message); - if (!msg.empty()) { - if (msg[msg.size() - 1] != '\n') { - msg.push_back('\n'); - } - // Append empty line - msg.push_back('\n'); - cmSystemTools::Stderr(msg.c_str(), msg.size()); - } + std::string msg = " "; + msg += cmQtAutoGen::Quoted(filename); + msg.push_back('\n'); + // Message + msg += message; + this->LogWarning(genType, msg); } -/** - * @brief Collects name collisions as output/input pairs - * @return True if there were collisions - */ -bool cmQtAutoGenerators::NameCollisionTest( - const std::map<std::string, std::string>& genFiles, - std::multimap<std::string, std::string>& collisions) const +void cmQtAutoGenerators::LogError(cmQtAutoGen::Generator genType, + std::string const& message) const { - typedef std::map<std::string, std::string>::const_iterator Iter; - typedef std::map<std::string, std::string>::value_type VType; - for (Iter ait = genFiles.begin(); ait != genFiles.end(); ++ait) { - bool first_match(true); - for (Iter bit = (++Iter(ait)); bit != genFiles.end(); ++bit) { - if (ait->second == bit->second) { - if (first_match) { - if (collisions.find(ait->second) != collisions.end()) { - // We already know of this collision from before - break; - } - collisions.insert(VType(ait->second, ait->first)); - first_match = false; - } - collisions.insert(VType(bit->second, bit->first)); - } - } + std::string msg; + msg.push_back('\n'); + msg += HeadLine(cmQtAutoGen::GeneratorName(genType) + " error"); + // Message + msg += message; + if (msg.back() != '\n') { + msg.push_back('\n'); } + msg.push_back('\n'); + cmSystemTools::Stderr(msg.c_str(), msg.size()); +} - return !collisions.empty(); +void cmQtAutoGenerators::LogFileError(cmQtAutoGen::Generator genType, + std::string const& filename, + std::string const& message) const +{ + std::string emsg = " "; + emsg += cmQtAutoGen::Quoted(filename); + emsg += '\n'; + // Message + emsg += message; + this->LogError(genType, emsg); } -/** - * @brief Generates a file path based on the checksum of the source file path - * @return The path - */ -std::string cmQtAutoGenerators::ChecksumedPath( - const std::string& sourceFile, const std::string& basePrefix, - const std::string& baseSuffix) const +void cmQtAutoGenerators::LogCommandError( + cmQtAutoGen::Generator genType, std::string const& message, + std::vector<std::string> const& command, std::string const& output) const { - std::string res = FPathChecksum.getPart(sourceFile); - res += "/"; - res += basePrefix; - res += cmsys::SystemTools::GetFilenameWithoutLastExtension(sourceFile); - res += baseSuffix; - return res; + std::string msg; + msg.push_back('\n'); + msg += HeadLine(cmQtAutoGen::GeneratorName(genType) + " subprocess error"); + msg += message; + if (msg.back() != '\n') { + msg.push_back('\n'); + } + msg.push_back('\n'); + msg += HeadLine("Command"); + msg += QuotedCommand(command); + if (msg.back() != '\n') { + msg.push_back('\n'); + } + msg.push_back('\n'); + msg += HeadLine("Output"); + msg += output; + if (msg.back() != '\n') { + msg.push_back('\n'); + } + msg.push_back('\n'); + cmSystemTools::Stderr(msg.c_str(), msg.size()); } /** * @brief Generates the parent directory of the given file on demand * @return True on success */ -bool cmQtAutoGenerators::MakeParentDirectory(const char* logPrefix, - const std::string& filename) const +bool cmQtAutoGenerators::MakeParentDirectory(cmQtAutoGen::Generator genType, + std::string const& filename) const { bool success = true; - const std::string dirName = cmSystemTools::GetFilenamePath(filename); + std::string const dirName = cmSystemTools::GetFilenamePath(filename); if (!dirName.empty()) { - success = cmsys::SystemTools::MakeDirectory(dirName); - if (!success) { - std::string error = logPrefix; - error += ": Error: Parent directory creation failed for "; - error += Quoted(filename); - this->LogError(error); + if (!cmSystemTools::MakeDirectory(dirName)) { + this->LogFileError(genType, filename, + "Could not create parent directory"); + success = false; } } return success; } -bool cmQtAutoGenerators::FileDiffers(const std::string& filename, - const std::string& content) +bool cmQtAutoGenerators::FileDiffers(std::string const& filename, + std::string const& content) { bool differs = true; { std::string oldContents; - if (ReadAll(oldContents, filename)) { + if (ReadFile(oldContents, filename)) { differs = (oldContents != content); } } return differs; } -bool cmQtAutoGenerators::FileWrite(const char* logPrefix, - const std::string& filename, - const std::string& content) +bool cmQtAutoGenerators::FileWrite(cmQtAutoGen::Generator genType, + std::string const& filename, + std::string const& content) { std::string error; // Make sure the parent directory exists - if (this->MakeParentDirectory(logPrefix, filename)) { + if (this->MakeParentDirectory(genType, filename)) { cmsys::ofstream outfile; - outfile.open(filename.c_str(), std::ios::trunc); + outfile.open(filename.c_str(), + (std::ios::out | std::ios::binary | std::ios::trunc)); if (outfile) { outfile << content; // Check for write errors if (!outfile.good()) { - error = logPrefix; - error += ": Error writing "; - error += Quoted(filename); + error = "File writing failed"; } } else { - error = logPrefix; - error = ": Error opening "; - error += Quoted(filename); + error = "Opening file for writing failed"; } } if (!error.empty()) { - this->LogError(error); + this->LogFileError(genType, filename, error); return false; } return true; @@ -2032,18 +2287,19 @@ bool cmQtAutoGenerators::FileWrite(const char* logPrefix, * @brief Runs a command and returns true on success * @return True on success */ -bool cmQtAutoGenerators::RunCommand(const std::vector<std::string>& command, - std::string& output, bool verbose) const +bool cmQtAutoGenerators::RunCommand(std::vector<std::string> const& command, + std::string& output) const { // Log command if (this->Verbose) { - this->LogInfo(QuotedCommand(command)); + std::string qcmd = QuotedCommand(command); + qcmd.push_back('\n'); + cmSystemTools::Stdout(qcmd.c_str(), qcmd.size()); } // Execute command int retVal = 0; bool res = cmSystemTools::RunSingleCommand( - command, &output, &output, &retVal, nullptr, - verbose ? cmSystemTools::OUTPUT_MERGE : cmSystemTools::OUTPUT_NONE); + command, &output, &output, &retVal, nullptr, cmSystemTools::OUTPUT_NONE); return (res && (retVal == 0)); } @@ -2053,71 +2309,16 @@ bool cmQtAutoGenerators::RunCommand(const std::vector<std::string>& command, * @return True on success */ bool cmQtAutoGenerators::FindHeader(std::string& header, - const std::string& testBasePath) const + std::string const& testBasePath) const { - for (std::vector<std::string>::const_iterator ext = - this->HeaderExtensions.begin(); - ext != this->HeaderExtensions.end(); ++ext) { + for (std::string const& ext : this->HeaderExtensions) { std::string testFilePath(testBasePath); - testFilePath += '.'; - testFilePath += (*ext); - if (cmsys::SystemTools::FileExists(testFilePath.c_str())) { + testFilePath.push_back('.'); + testFilePath += ext; + if (cmSystemTools::FileExists(testFilePath.c_str())) { header = testFilePath; return true; } } return false; } - -std::string cmQtAutoGenerators::MocFindHeader( - const std::string& sourcePath, const std::string& includeBase) const -{ - std::string header; - // Search in vicinity of the source - if (!this->FindHeader(header, sourcePath + includeBase)) { - // Search in include directories - for (std::vector<std::string>::const_iterator iit = - this->MocIncludePaths.begin(); - iit != this->MocIncludePaths.end(); ++iit) { - const std::string fullPath = ((*iit) + '/' + includeBase); - if (FindHeader(header, fullPath)) { - break; - } - } - } - // Sanitize - if (!header.empty()) { - header = cmsys::SystemTools::GetRealPath(header); - } - return header; -} - -bool cmQtAutoGenerators::MocFindIncludedFile( - std::string& absFile, const std::string& sourcePath, - const std::string& includeString) const -{ - bool success = false; - // Search in vicinity of the source - { - std::string testPath = sourcePath; - testPath += includeString; - if (cmsys::SystemTools::FileExists(testPath.c_str())) { - absFile = cmsys::SystemTools::GetRealPath(testPath); - success = true; - } - } - // Search in include directories - if (!success) { - for (std::vector<std::string>::const_iterator iit = - this->MocIncludePaths.begin(); - iit != this->MocIncludePaths.end(); ++iit) { - const std::string fullPath = ((*iit) + '/' + includeString); - if (cmsys::SystemTools::FileExists(fullPath.c_str())) { - absFile = cmsys::SystemTools::GetRealPath(fullPath); - success = true; - break; - } - } - } - return success; -} diff --git a/Source/cmQtAutoGenerators.h b/Source/cmQtAutoGenerators.h index a8eb961..a7bb538 100644 --- a/Source/cmQtAutoGenerators.h +++ b/Source/cmQtAutoGenerators.h @@ -6,160 +6,194 @@ #include "cmConfigure.h" // IWYU pragma: keep #include "cmFilePathChecksum.h" +#include "cmQtAutoGen.h" #include "cmsys/RegularExpression.hxx" #include <map> +#include <memory> // IWYU pragma: keep #include <set> #include <string> -#include <utility> #include <vector> class cmMakefile; class cmQtAutoGenerators { + CM_DISABLE_COPY(cmQtAutoGenerators) public: cmQtAutoGenerators(); - bool Run(const std::string& targetDirectory, const std::string& config); + bool Run(std::string const& targetDirectory, std::string const& config); private: // -- Types - /// @brief Used to extract additional dependencies from content text - struct MocDependFilter + /// @brief Search key plus regular expression pair + struct KeyRegExp { - std::string key; - cmsys::RegularExpression regExp; + KeyRegExp() = default; + + KeyRegExp(const char* key, const char* regExp) + : Key(key) + , RegExp(regExp) + { + } + + KeyRegExp(std::string const& key, std::string const& regExp) + : Key(key) + , RegExp(regExp) + { + } + + std::string Key; + cmsys::RegularExpression RegExp; }; - typedef std::pair<std::string, cmsys::RegularExpression> MocMacroFilter; - // -- Configuration - bool MocDependFilterPush(const std::string& key, const std::string& regExp); - bool ReadAutogenInfoFile(cmMakefile* makefile, - const std::string& targetDirectory, - const std::string& config); + /// @brief Source file job + struct SourceJob + { + bool Moc = false; + bool Uic = false; + }; - bool MocEnabled() const { return !this->MocExecutable.empty(); } - bool UicEnabled() const { return !this->UicExecutable.empty(); } - bool RccEnabled() const { return !this->RccExecutable.empty(); } + /// @brief MOC job + struct MocJobAuto + { + std::string SourceFile; + std::string BuildFileRel; + std::set<std::string> Depends; + }; + + /// @brief MOC job + struct MocJobIncluded : MocJobAuto + { + bool DependsValid = false; + std::string Includer; + std::string IncludeString; + }; + + /// @brief UIC job + struct UicJob + { + std::string SourceFile; + std::string BuildFileRel; + std::string Includer; + std::string IncludeString; + }; + + /// @brief RCC job + struct RccJob + { + std::string QrcFile; + std::string RccFile; + std::vector<std::string> Options; + std::vector<std::string> Inputs; + }; + + // -- Initialization + bool InitInfoFile(cmMakefile* makefile, std::string const& targetDirectory, + std::string const& config); // -- Settings file void SettingsFileRead(cmMakefile* makefile); bool SettingsFileWrite(); - - bool AnySettingsChanged() const + bool SettingsChanged() const { return (this->MocSettingsChanged || this->RccSettingsChanged || this->UicSettingsChanged); } - // -- Init and run - void Init(cmMakefile* makefile); - bool RunAutogen(); + // -- Central processing + bool Process(); + + // -- Source parsing + bool ParseSourceFile(std::string const& absFilename, const SourceJob& job); + bool ParseHeaderFile(std::string const& absFilename, const SourceJob& job); + bool ParsePostprocess(); - // -- Content analysis - bool MocRequired(const std::string& contentText, + // -- Moc + bool MocEnabled() const { return !this->MocExecutable.empty(); } + bool MocSkip(std::string const& absFilename) const; + bool MocRequired(std::string const& contentText, std::string* macroName = nullptr); - void MocFindDepends( - const std::string& absFilename, const std::string& contentText, - std::map<std::string, std::set<std::string> >& mocDepends); - - bool MocSkip(const std::string& absFilename) const; - bool UicSkip(const std::string& absFilename) const; - - bool ParseSourceFile( - const std::string& absFilename, - std::map<std::string, std::string>& mocsIncluded, - std::map<std::string, std::set<std::string> >& mocDepends, - std::map<std::string, std::vector<std::string> >& includedUis, - bool relaxed); - - void SearchHeadersForSourceFile(const std::string& absFilename, - std::set<std::string>& mocHeaderFiles, - std::set<std::string>& uicHeaderFiles) const; - - bool ParseHeaders( - const std::set<std::string>& mocHeaderFiles, - const std::set<std::string>& uicHeaderFiles, - const std::map<std::string, std::string>& mocsIncluded, - std::map<std::string, std::string>& mocsNotIncluded, - std::map<std::string, std::set<std::string> >& mocDepends, - std::map<std::string, std::vector<std::string> >& includedUis); - - void UicParseContent( - const std::string& fileName, const std::string& contentText, - std::map<std::string, std::vector<std::string> >& includedUis); - - bool MocParseSourceContent( - const std::string& absFilename, const std::string& contentText, - std::map<std::string, std::string>& mocsIncluded, - std::map<std::string, std::set<std::string> >& mocDepends, bool relaxed); - - void MocParseHeaderContent( - const std::string& absFilename, const std::string& contentText, - std::map<std::string, std::string>& mocsNotIncluded, - std::map<std::string, std::set<std::string> >& mocDepends); - - // -- Moc file generation - bool MocGenerateAll( - const std::map<std::string, std::string>& mocsIncluded, - const std::map<std::string, std::string>& mocsNotIncluded, - const std::map<std::string, std::set<std::string> >& mocDepends); - bool MocGenerateFile( - const std::string& sourceFile, const std::string& mocFileName, - const std::map<std::string, std::set<std::string> >& mocDepends, - bool included); - - // -- Uic file generation - bool UicFindIncludedFile(std::string& absFile, const std::string& sourceFile, - const std::string& searchPath, - const std::string& searchFile); - bool UicGenerateAll( - const std::map<std::string, std::vector<std::string> >& includedUis); - bool UicGenerateFile(const std::string& realName, - const std::string& uiInputFile, - const std::string& uiOutputFile); - - // -- Rcc file generation + // Moc strings + std::string MocStringMacros() const; + std::string MocStringHeaders(std::string const& fileBase) const; + std::string MocFindIncludedHeader(std::string const& sourcePath, + std::string const& includeBase) const; + bool MocFindIncludedFile(std::string& absFile, std::string const& sourceFile, + std::string const& includeString) const; + // Moc depends + bool MocDependFilterPush(std::string const& key, std::string const& regExp); + void MocFindDepends(std::string const& absFilename, + std::string const& contentText, + std::set<std::string>& depends); + // Moc + bool MocParseSourceContent(std::string const& absFilename, + std::string const& contentText); + void MocParseHeaderContent(std::string const& absFilename, + std::string const& contentText); + + bool MocGenerateAll(); + bool MocGenerateFile(const MocJobAuto& mocJob, bool* generated = nullptr); + + // -- Uic + bool UicEnabled() const { return !this->UicExecutable.empty(); } + bool UicSkip(std::string const& absFilename) const; + bool UicParseContent(std::string const& fileName, + std::string const& contentText); + bool UicFindIncludedFile(std::string& absFile, std::string const& sourceFile, + std::string const& includeString); + bool UicGenerateAll(); + bool UicGenerateFile(const UicJob& uicJob); + + // -- Rcc + bool RccEnabled() const { return !this->RccExecutable.empty(); } bool RccGenerateAll(); - bool RccGenerateFile(const std::string& qrcInputFile, - const std::string& qrcOutputFile, bool unique_n); - - // -- Logging - void LogErrorNameCollision( - const std::string& message, - const std::multimap<std::string, std::string>& collisions) const; - void LogBold(const std::string& message) const; - void LogInfo(const std::string& message) const; - void LogWarning(const std::string& message) const; - void LogError(const std::string& message) const; - void LogCommand(const std::vector<std::string>& command) const; + bool RccGenerateFile(const RccJob& rccJob); + + // -- Log info + void LogBold(std::string const& message) const; + void LogInfo(cmQtAutoGen::Generator genType, + std::string const& message) const; + // -- Log warning + void LogWarning(cmQtAutoGen::Generator genType, + std::string const& message) const; + void LogFileWarning(cmQtAutoGen::Generator genType, + std::string const& filename, + std::string const& message) const; + // -- Log error + void LogError(cmQtAutoGen::Generator genType, + std::string const& message) const; + void LogFileError(cmQtAutoGen::Generator genType, + std::string const& filename, + std::string const& message) const; + void LogCommandError(cmQtAutoGen::Generator genType, + std::string const& message, + std::vector<std::string> const& command, + std::string const& output) const; // -- Utility - bool NameCollisionTest( - const std::map<std::string, std::string>& genFiles, - std::multimap<std::string, std::string>& collisions) const; - std::string ChecksumedPath(const std::string& sourceFile, - const std::string& basePrefix, - const std::string& baseSuffix) const; - bool MakeParentDirectory(const char* logPrefix, - const std::string& filename) const; - bool FileDiffers(const std::string& filename, const std::string& content); - bool FileWrite(const char* logPrefix, const std::string& filename, - const std::string& content); - - bool RunCommand(const std::vector<std::string>& command, std::string& output, - bool verbose = true) const; - - bool FindHeader(std::string& header, const std::string& testBasePath) const; - - std::string MocFindHeader(const std::string& sourcePath, - const std::string& includeBase) const; - bool MocFindIncludedFile(std::string& absFile, const std::string& sourceFile, - const std::string& includeString) const; + bool MakeParentDirectory(cmQtAutoGen::Generator genType, + std::string const& filename) const; + bool FileDiffers(std::string const& filename, std::string const& content); + bool FileWrite(cmQtAutoGen::Generator genType, std::string const& filename, + std::string const& content); + bool FindHeader(std::string& header, std::string const& testBasePath) const; + bool RunCommand(std::vector<std::string> const& command, + std::string& output) const; // -- Meta + std::string InfoFile; std::string ConfigSuffix; + cmQtAutoGen::MultiConfig MultiConfig; + // -- Settings + bool IncludeProjectDirsBefore; + bool Verbose; + bool ColorOutput; + std::string SettingsFile; + std::string SettingsStringMoc; + std::string SettingsStringUic; + std::string SettingsStringRcc; // -- Directories std::string ProjectSourceDir; std::string ProjectBinaryDir; @@ -169,27 +203,19 @@ private: std::string AutogenIncludeDir; // -- Qt environment std::string QtMajorVersion; + std::string QtMinorVersion; std::string MocExecutable; std::string UicExecutable; std::string RccExecutable; // -- File lists - std::vector<std::string> Sources; - std::vector<std::string> Headers; + std::map<std::string, SourceJob> HeaderJobs; + std::map<std::string, SourceJob> SourceJobs; std::vector<std::string> HeaderExtensions; - cmFilePathChecksum FPathChecksum; - // -- Settings - bool IncludeProjectDirsBefore; - bool Verbose; - bool ColorOutput; - std::string SettingsFile; - std::string SettingsStringMoc; - std::string SettingsStringUic; - std::string SettingsStringRcc; + cmFilePathChecksum FilePathChecksum; // -- Moc bool MocSettingsChanged; bool MocPredefsChanged; bool MocRelaxedMode; - bool MocRunFailed; std::string MocCompFileRel; std::string MocCompFileAbs; std::string MocPredefsFileRel; @@ -199,24 +225,24 @@ private: std::vector<std::string> MocIncludes; std::vector<std::string> MocDefinitions; std::vector<std::string> MocOptions; + std::vector<std::string> MocAllOptions; std::vector<std::string> MocPredefsCmd; - std::vector<MocDependFilter> MocDependFilters; - std::vector<MocMacroFilter> MocMacroFilters; + std::vector<KeyRegExp> MocDependFilters; + std::vector<KeyRegExp> MocMacroFilters; cmsys::RegularExpression MocRegExpInclude; + std::vector<std::unique_ptr<MocJobIncluded>> MocJobsIncluded; + std::vector<std::unique_ptr<MocJobAuto>> MocJobsAuto; // -- Uic bool UicSettingsChanged; - bool UicRunFailed; std::vector<std::string> UicSkipList; std::vector<std::string> UicTargetOptions; - std::map<std::string, std::string> UicOptions; + std::map<std::string, std::vector<std::string>> UicOptions; std::vector<std::string> UicSearchPaths; cmsys::RegularExpression UicRegExpInclude; + std::vector<std::unique_ptr<UicJob>> UicJobs; // -- Rcc bool RccSettingsChanged; - bool RccRunFailed; - std::vector<std::string> RccSources; - std::map<std::string, std::string> RccOptions; - std::map<std::string, std::vector<std::string> > RccInputs; + std::vector<RccJob> RccJobs; }; #endif diff --git a/Source/cmRST.cxx b/Source/cmRST.cxx index 5364f76..112be4d 100644 --- a/Source/cmRST.cxx +++ b/Source/cmRST.cxx @@ -86,7 +86,7 @@ void cmRST::ProcessModule(std::istream& is) if (line[0] != '#') { this->ProcessLine(line.substr(0, pos)); } - rst = ""; + rst.clear(); this->Reset(); this->OutputLinePending = true; } @@ -101,7 +101,7 @@ void cmRST::ProcessModule(std::istream& is) this->ProcessLine(line.substr(2)); continue; } - rst = ""; + rst.clear(); this->Reset(); this->OutputLinePending = true; } @@ -292,9 +292,7 @@ std::string cmRST::ReplaceSubstitutions(std::string const& line) void cmRST::OutputMarkupLines(bool inlineMarkup) { - for (std::vector<std::string>::iterator i = this->MarkupLines.begin(); - i != this->MarkupLines.end(); ++i) { - std::string line = *i; + for (auto line : this->MarkupLines) { if (!line.empty()) { line = " " + line; } @@ -347,15 +345,13 @@ void cmRST::ProcessDirectiveReplace() // Record markup lines as replacement text. std::string& replacement = this->Replace[this->ReplaceName]; replacement += cmJoin(this->MarkupLines, " "); - this->ReplaceName = ""; + this->ReplaceName.clear(); } void cmRST::ProcessDirectiveTocTree() { // Process documents referenced by toctree directive. - for (std::vector<std::string>::iterator i = this->MarkupLines.begin(); - i != this->MarkupLines.end(); ++i) { - std::string const& line = *i; + for (std::string const& line : this->MarkupLines) { if (!line.empty() && line[0] != ':') { if (this->TocTreeLink.find(line)) { std::string const& link = this->TocTreeLink.match(1); diff --git a/Source/cmRemoveCommand.cxx b/Source/cmRemoveCommand.cxx index 1db8441..bb14e68 100644 --- a/Source/cmRemoveCommand.cxx +++ b/Source/cmRemoveCommand.cxx @@ -37,10 +37,10 @@ bool cmRemoveCommand::InitialPass(std::vector<std::string> const& args, // now create the new value std::string value; - for (unsigned int j = 0; j < varArgsExpanded.size(); ++j) { + for (std::string const& varArgExpanded : varArgsExpanded) { int found = 0; - for (unsigned int k = 0; k < argsExpanded.size(); ++k) { - if (varArgsExpanded[j] == argsExpanded[k]) { + for (std::string const& argExpanded : argsExpanded) { + if (varArgExpanded == argExpanded) { found = 1; break; } @@ -49,7 +49,7 @@ bool cmRemoveCommand::InitialPass(std::vector<std::string> const& args, if (!value.empty()) { value += ";"; } - value += varArgsExpanded[j]; + value += varArgExpanded; } } diff --git a/Source/cmRemoveCommand.h b/Source/cmRemoveCommand.h index 9e035d7..7b11849 100644 --- a/Source/cmRemoveCommand.h +++ b/Source/cmRemoveCommand.h @@ -23,14 +23,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmRemoveCommand; } + cmCommand* Clone() override { return new cmRemoveCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmRemoveDefinitionsCommand.cxx b/Source/cmRemoveDefinitionsCommand.cxx index f5fe2df..8311b4b 100644 --- a/Source/cmRemoveDefinitionsCommand.cxx +++ b/Source/cmRemoveDefinitionsCommand.cxx @@ -15,9 +15,8 @@ bool cmRemoveDefinitionsCommand::InitialPass( return true; } - for (std::vector<std::string>::const_iterator i = args.begin(); - i != args.end(); ++i) { - this->Makefile->RemoveDefineFlag(i->c_str()); + for (std::string const& i : args) { + this->Makefile->RemoveDefineFlag(i.c_str()); } return true; } diff --git a/Source/cmRemoveDefinitionsCommand.h b/Source/cmRemoveDefinitionsCommand.h index c2c6b0e..a5cb204 100644 --- a/Source/cmRemoveDefinitionsCommand.h +++ b/Source/cmRemoveDefinitionsCommand.h @@ -25,14 +25,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmRemoveDefinitionsCommand; } + cmCommand* Clone() override { return new cmRemoveDefinitionsCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmReturnCommand.h b/Source/cmReturnCommand.h index 53c91cd..ef39614 100644 --- a/Source/cmReturnCommand.h +++ b/Source/cmReturnCommand.h @@ -23,14 +23,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmReturnCommand; } + cmCommand* Clone() override { return new cmReturnCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmScriptGenerator.cxx b/Source/cmScriptGenerator.cxx index 768e15a..2cae714 100644 --- a/Source/cmScriptGenerator.cxx +++ b/Source/cmScriptGenerator.cxx @@ -26,7 +26,7 @@ void cmScriptGenerator::Generate( this->ConfigurationName = config; this->ConfigurationTypes = &configurationTypes; this->GenerateScript(os); - this->ConfigurationName = ""; + this->ConfigurationName.clear(); this->ConfigurationTypes = nullptr; } @@ -69,11 +69,10 @@ std::string cmScriptGenerator::CreateConfigTest( result += this->RuntimeConfigVariable; result += "}\" MATCHES \"^("; const char* sep = ""; - for (std::vector<std::string>::const_iterator ci = configs.begin(); - ci != configs.end(); ++ci) { + for (std::string const& config : configs) { result += sep; sep = "|"; - cmScriptGeneratorEncodeConfig(*ci, result); + cmScriptGeneratorEncodeConfig(config, result); } result += ")$\""; return result; @@ -123,10 +122,8 @@ bool cmScriptGenerator::GeneratesForConfig(const std::string& config) // This is a configuration-specific rule. Check if the config // matches this rule. std::string config_upper = cmSystemTools::UpperCase(config); - for (std::vector<std::string>::const_iterator i = - this->Configurations.begin(); - i != this->Configurations.end(); ++i) { - if (cmSystemTools::UpperCase(*i) == config_upper) { + for (std::string const& cfg : this->Configurations) { + if (cmSystemTools::UpperCase(cfg) == config_upper) { return true; } } @@ -163,15 +160,12 @@ void cmScriptGenerator::GenerateScriptActionsPerConfig(std::ostream& os, // in a block for each configuration that is built. We restrict // the list of configurations to those to which this rule applies. bool first = true; - for (std::vector<std::string>::const_iterator i = - this->ConfigurationTypes->begin(); - i != this->ConfigurationTypes->end(); ++i) { - const char* config = i->c_str(); - if (this->GeneratesForConfig(config)) { + for (std::string const& cfgType : *this->ConfigurationTypes) { + if (this->GeneratesForConfig(cfgType)) { // Generate a per-configuration block. - std::string config_test = this->CreateConfigTest(config); + std::string config_test = this->CreateConfigTest(cfgType); os << indent << (first ? "if(" : "elseif(") << config_test << ")\n"; - this->GenerateScriptForConfig(os, config, indent.Next()); + this->GenerateScriptForConfig(os, cfgType, indent.Next()); first = false; } } diff --git a/Source/cmSearchPath.cxx b/Source/cmSearchPath.cxx index 0f2ef6e..a40c987 100644 --- a/Source/cmSearchPath.cxx +++ b/Source/cmSearchPath.cxx @@ -27,10 +27,9 @@ void cmSearchPath::ExtractWithout(const std::set<std::string>& ignore, if (clear) { outPaths.clear(); } - for (std::vector<std::string>::const_iterator p = this->Paths.begin(); - p != this->Paths.end(); ++p) { - if (ignore.count(*p) == 0) { - outPaths.push_back(*p); + for (std::string const& path : this->Paths) { + if (ignore.count(path) == 0) { + outPaths.push_back(path); } } } @@ -69,9 +68,8 @@ void cmSearchPath::AddUserPath(const std::string& path) } // Process them all from the current directory - for (std::vector<std::string>::const_iterator p = outPaths.begin(); - p != outPaths.end(); ++p) { - this->AddPathInternal(*p, this->FC->Makefile->GetCurrentSourceDirectory()); + for (std::string const& p : outPaths) { + this->AddPathInternal(p, this->FC->Makefile->GetCurrentSourceDirectory()); } } @@ -84,9 +82,8 @@ void cmSearchPath::AddCMakePath(const std::string& variable) std::vector<std::string> expanded; cmSystemTools::ExpandListArgument(value, expanded); - for (std::vector<std::string>::const_iterator p = expanded.begin(); - p != expanded.end(); ++p) { - this->AddPathInternal(*p, + for (std::string const& p : expanded) { + this->AddPathInternal(p, this->FC->Makefile->GetCurrentSourceDirectory()); } } @@ -96,9 +93,8 @@ void cmSearchPath::AddEnvPath(const std::string& variable) { std::vector<std::string> expanded; cmSystemTools::GetPath(expanded, variable.c_str()); - for (std::vector<std::string>::const_iterator p = expanded.begin(); - p != expanded.end(); ++p) { - this->AddPathInternal(*p); + for (std::string const& p : expanded) { + this->AddPathInternal(p); } } @@ -142,26 +138,24 @@ void cmSearchPath::AddSuffixes(const std::vector<std::string>& suffixes) inPaths.swap(this->Paths); this->Paths.reserve(inPaths.size() * (suffixes.size() + 1)); - for (std::vector<std::string>::iterator ip = inPaths.begin(); - ip != inPaths.end(); ++ip) { - cmSystemTools::ConvertToUnixSlashes(*ip); + for (std::string& inPath : inPaths) { + cmSystemTools::ConvertToUnixSlashes(inPath); // if *i is only / then do not add a // // this will get incorrectly considered a network // path on windows and cause huge delays. - std::string p = *ip; + std::string p = inPath; if (!p.empty() && *p.rbegin() != '/') { p += "/"; } // Combine with all the suffixes - for (std::vector<std::string>::const_iterator s = suffixes.begin(); - s != suffixes.end(); ++s) { - this->Paths.push_back(p + *s); + for (std::string const& suffix : suffixes) { + this->Paths.push_back(p + suffix); } // And now the original w/o any suffix - this->Paths.push_back(*ip); + this->Paths.push_back(inPath); } } @@ -178,12 +172,11 @@ void cmSearchPath::AddPrefixPaths(const std::vector<std::string>& paths, } else if (this->FC->CMakePathName == "LIBRARY") { subdir = "lib"; } else if (this->FC->CMakePathName == "FRAMEWORK") { - subdir = ""; // ? what to do for frameworks ? + subdir.clear(); // ? what to do for frameworks ? } - for (std::vector<std::string>::const_iterator p = paths.begin(); - p != paths.end(); ++p) { - std::string dir = *p; + for (std::string const& path : paths) { + std::string dir = path; if (!subdir.empty() && !dir.empty() && *dir.rbegin() != '/') { dir += "/"; } @@ -201,8 +194,8 @@ void cmSearchPath::AddPrefixPaths(const std::vector<std::string>& paths, if (subdir == "bin") { this->AddPathInternal(dir + "sbin", base); } - if (!subdir.empty() && *p != "/") { - this->AddPathInternal(*p, base); + if (!subdir.empty() && path != "/") { + this->AddPathInternal(path, base); } } } diff --git a/Source/cmSeparateArgumentsCommand.cxx b/Source/cmSeparateArgumentsCommand.cxx index 7b222a0..28cbdc0 100644 --- a/Source/cmSeparateArgumentsCommand.cxx +++ b/Source/cmSeparateArgumentsCommand.cxx @@ -36,29 +36,29 @@ bool cmSeparateArgumentsCommand::InitialPass( DoingCommand }; Doing doing = DoingVariable; - for (unsigned int i = 0; i < args.size(); ++i) { + for (std::string const& arg : args) { if (doing == DoingVariable) { - var = args[i]; + var = arg; doing = DoingMode; - } else if (doing == DoingMode && args[i] == "NATIVE_COMMAND") { + } else if (doing == DoingMode && arg == "NATIVE_COMMAND") { #ifdef _WIN32 mode = ModeWindows; #else mode = ModeUnix; #endif doing = DoingCommand; - } else if (doing == DoingMode && args[i] == "UNIX_COMMAND") { + } else if (doing == DoingMode && arg == "UNIX_COMMAND") { mode = ModeUnix; doing = DoingCommand; - } else if (doing == DoingMode && args[i] == "WINDOWS_COMMAND") { + } else if (doing == DoingMode && arg == "WINDOWS_COMMAND") { mode = ModeWindows; doing = DoingCommand; } else if (doing == DoingCommand) { - command = args[i]; + command = arg; doing = DoingNone; } else { std::ostringstream e; - e << "given unknown argument " << args[i]; + e << "given unknown argument " << arg; this->SetError(e.str()); return false; } @@ -84,19 +84,17 @@ bool cmSeparateArgumentsCommand::InitialPass( // Construct the result list value. std::string value; const char* sep = ""; - for (std::vector<std::string>::const_iterator vi = vec.begin(); - vi != vec.end(); ++vi) { + for (std::string const& vi : vec) { // Separate from the previous argument. value += sep; sep = ";"; // Preserve semicolons. - for (std::string::const_iterator si = vi->begin(); si != vi->end(); - ++si) { - if (*si == ';') { + for (char si : vi) { + if (si == ';') { value += '\\'; } - value += *si; + value += si; } } this->Makefile->AddDefinition(var, value.c_str()); diff --git a/Source/cmSeparateArgumentsCommand.h b/Source/cmSeparateArgumentsCommand.h index 2d4c7cd..988ad23 100644 --- a/Source/cmSeparateArgumentsCommand.h +++ b/Source/cmSeparateArgumentsCommand.h @@ -23,14 +23,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmSeparateArgumentsCommand; } + cmCommand* Clone() override { return new cmSeparateArgumentsCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmServer.cxx b/Source/cmServer.cxx index c3e6811..e923c22 100644 --- a/Source/cmServer.cxx +++ b/Source/cmServer.cxx @@ -16,6 +16,7 @@ #include <algorithm> #include <cassert> #include <cstdint> +#include <iostream> #include <memory> #include <utility> @@ -57,10 +58,6 @@ cmServer::cmServer(cmConnection* conn, bool supportExperimental) cmServer::~cmServer() { - if (!this->Protocol) { // Server was never fully started! - return; - } - for (cmServerProtocol* p : this->SupportedProtocols) { delete p; } @@ -87,7 +84,7 @@ void cmServer::ProcessRequest(cmConnection* connection, const cmServerRequest request(this, connection, value[kTYPE_KEY].asString(), value[kCOOKIE_KEY].asString(), value); - if (request.Type == "") { + if (request.Type.empty()) { cmServerResponse response(request); response.SetError("No type given in request."); this->WriteResponse(connection, response, nullptr); @@ -110,6 +107,7 @@ void cmServer::ProcessRequest(cmConnection* connection, void cmServer::RegisterProtocol(cmServerProtocol* protocol) { if (protocol->IsExperimental() && !this->SupportExperimental) { + delete protocol; return; } auto version = protocol->ProtocolVersion(); @@ -247,9 +245,11 @@ cmFileMonitor* cmServer::FileMonitor() const void cmServer::WriteJsonObject(const Json::Value& jsonValue, const DebugInfo* debug) const { + uv_rwlock_rdlock(&ConnectionsMutex); for (auto& connection : this->Connections) { WriteJsonObject(connection.get(), jsonValue, debug); } + uv_rwlock_rdunlock(&ConnectionsMutex); } void cmServer::WriteJsonObject(cmConnection* connection, @@ -285,8 +285,7 @@ void cmServer::WriteJsonObject(cmConnection* connection, } } - connection->WriteData(std::string("\n") + kSTART_MAGIC + std::string("\n") + - result + kEND_MAGIC + std::string("\n")); + connection->WriteData(result); } cmServerProtocol* cmServer::FindMatchingProtocol( @@ -413,18 +412,36 @@ static void __start_thread(void* arg) { auto server = reinterpret_cast<cmServerBase*>(arg); std::string error; - server->Serve(&error); + bool success = server->Serve(&error); + if (!success || error.empty() == false) { + std::cerr << "Error during serve: " << error << std::endl; + } +} + +static void __shutdownThread(uv_async_t* arg) +{ + auto server = reinterpret_cast<cmServerBase*>(arg->data); + on_walk_to_shutdown(reinterpret_cast<uv_handle_t*>(arg), nullptr); + server->StartShutDown(); } bool cmServerBase::StartServeThread() { ServeThreadRunning = true; + uv_async_init(&Loop, &this->ShutdownSignal, __shutdownThread); + this->ShutdownSignal.data = this; uv_thread_create(&ServeThread, __start_thread, this); return true; } bool cmServerBase::Serve(std::string* errorMessage) { +#ifndef NDEBUG + uv_thread_t blank_thread_t = {}; + assert(uv_thread_equal(&blank_thread_t, &ServeThreadId)); + ServeThreadId = uv_thread_self(); +#endif + errorMessage->clear(); uv_signal_init(&Loop, &this->SIGINTHandler); @@ -438,15 +455,24 @@ bool cmServerBase::Serve(std::string* errorMessage) OnServeStart(); - for (auto& connection : Connections) { - if (!connection->OnServeStart(errorMessage)) { - return false; + { + uv_rwlock_rdlock(&ConnectionsMutex); + for (auto& connection : Connections) { + if (!connection->OnServeStart(errorMessage)) { + uv_rwlock_rdunlock(&ConnectionsMutex); + return false; + } } + uv_rwlock_rdunlock(&ConnectionsMutex); } if (uv_run(&Loop, UV_RUN_DEFAULT) != 0) { + // It is important we don't ever let the event loop exit with open handles + // at best this is a memory leak, but it can also introduce race conditions + // which can hang the program. + assert(false && "Event loop stopped in unclean state."); + *errorMessage = "Internal Error: Event loop stopped in unclean state."; - StartShutDown(); return false; } @@ -458,14 +484,8 @@ void cmServerBase::OnConnected(cmConnection*) { } -void cmServerBase::OnDisconnect() -{ -} - void cmServerBase::OnServeStart() { - uv_signal_start(&this->SIGINTHandler, &on_signal, SIGINT); - uv_signal_start(&this->SIGHUPHandler, &on_signal, SIGHUP); } void cmServerBase::StartShutDown() @@ -480,16 +500,16 @@ void cmServerBase::StartShutDown() uv_signal_stop(&this->SIGHUPHandler); } - for (auto& connection : Connections) { - connection->OnConnectionShuttingDown(); + { + uv_rwlock_wrlock(&ConnectionsMutex); + for (auto& connection : Connections) { + connection->OnConnectionShuttingDown(); + } + Connections.clear(); + uv_rwlock_wrunlock(&ConnectionsMutex); } - Connections.clear(); - - uv_stop(&Loop); uv_walk(&Loop, on_walk_to_shutdown, nullptr); - - uv_run(&Loop, UV_RUN_DEFAULT); } bool cmServerBase::OnSignal(int signum) @@ -501,13 +521,12 @@ bool cmServerBase::OnSignal(int signum) cmServerBase::cmServerBase(cmConnection* connection) { - uv_loop_init(&Loop); + auto err = uv_loop_init(&Loop); + (void)err; + assert(err == 0); - uv_signal_init(&Loop, &this->SIGINTHandler); - uv_signal_init(&Loop, &this->SIGHUPHandler); - - this->SIGINTHandler.data = this; - this->SIGHUPHandler.data = this; + err = uv_rwlock_init(&ConnectionsMutex); + assert(err == 0); AddNewConnection(connection); } @@ -516,16 +535,19 @@ cmServerBase::~cmServerBase() { if (ServeThreadRunning) { - StartShutDown(); + uv_async_send(&this->ShutdownSignal); uv_thread_join(&ServeThread); } uv_loop_close(&Loop); + uv_rwlock_destroy(&ConnectionsMutex); } void cmServerBase::AddNewConnection(cmConnection* ownedConnection) { + uv_rwlock_wrlock(&ConnectionsMutex); Connections.emplace_back(ownedConnection); + uv_rwlock_wrunlock(&ConnectionsMutex); ownedConnection->SetServer(this); } @@ -539,9 +561,11 @@ void cmServerBase::OnDisconnect(cmConnection* pConnection) auto pred = [pConnection](const std::unique_ptr<cmConnection>& m) { return m.get() == pConnection; }; + uv_rwlock_wrlock(&ConnectionsMutex); Connections.erase( std::remove_if(Connections.begin(), Connections.end(), pred), Connections.end()); + uv_rwlock_wrunlock(&ConnectionsMutex); if (Connections.empty()) { StartShutDown(); } diff --git a/Source/cmServer.h b/Source/cmServer.h index eafd860..15fd2ba 100644 --- a/Source/cmServer.h +++ b/Source/cmServer.h @@ -37,13 +37,12 @@ public: * This should almost always be called by the given connections * directly. * - * @param connection The connectiont the request was received on + * @param connection The connection the request was received on * @param request The actual request */ virtual void ProcessRequest(cmConnection* connection, const std::string& request) = 0; virtual void OnConnected(cmConnection* connection); - virtual void OnDisconnect(); /*** * Start a dedicated thread. If this is used to start the server, it will @@ -62,10 +61,21 @@ public: void OnDisconnect(cmConnection* pConnection); protected: - std::vector<std::unique_ptr<cmConnection> > Connections; + mutable uv_rwlock_t ConnectionsMutex; + std::vector<std::unique_ptr<cmConnection>> Connections; bool ServeThreadRunning = false; uv_thread_t ServeThread; + uv_async_t ShutdownSignal; +#ifndef NDEBUG +public: + // When the server starts it will mark down it's current thread ID, + // which is useful in other contexts to just assert that operations + // are performed on that same thread. + uv_thread_t ServeThreadId = {}; + +protected: +#endif uv_loop_t Loop; @@ -140,22 +150,6 @@ private: cmServerProtocol* Protocol = nullptr; std::vector<cmServerProtocol*> SupportedProtocols; - std::string DataBuffer; - std::string JsonData; - - typedef union - { - uv_tty_t tty; - uv_pipe_t pipe; - } InOutUnion; - - InOutUnion Input; - InOutUnion Output; - uv_stream_t* InputStream = nullptr; - uv_stream_t* OutputStream = nullptr; - - mutable bool Writing = false; - friend class cmServerProtocol; friend class cmServerRequest; }; diff --git a/Source/cmServerConnection.cxx b/Source/cmServerConnection.cxx index 4891131..44af75f 100644 --- a/Source/cmServerConnection.cxx +++ b/Source/cmServerConnection.cxx @@ -2,76 +2,139 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmServerConnection.h" +#include "cmConfigure.h" #include "cmServer.h" #include "cmServerDictionary.h" +#ifdef _WIN32 +#include "io.h" +#else +#include <unistd.h> +#endif +#include <cassert> cmStdIoConnection::cmStdIoConnection( cmConnectionBufferStrategy* bufferStrategy) : cmEventBasedConnection(bufferStrategy) - , Input() - , Output() { } +void cmStdIoConnection::SetupStream(uv_stream_t*& stream, int file_id) +{ + assert(stream == nullptr); + switch (uv_guess_handle(file_id)) { + case UV_TTY: { + auto tty = new uv_tty_t(); + uv_tty_init(this->Server->GetLoop(), tty, file_id, file_id == 0); + uv_tty_set_mode(tty, UV_TTY_MODE_NORMAL); + stream = reinterpret_cast<uv_stream_t*>(tty); + break; + } + case UV_FILE: + if (file_id == 0) { + return; + } + // Intentional fallthrough; stdin can _not_ be treated as a named + // pipe, however stdout can be. + CM_FALLTHROUGH; + case UV_NAMED_PIPE: { + auto pipe = new uv_pipe_t(); + uv_pipe_init(this->Server->GetLoop(), pipe, 0); + uv_pipe_open(pipe, file_id); + stream = reinterpret_cast<uv_stream_t*>(pipe); + break; + } + default: + assert(false && "Unable to determine stream type"); + return; + } + stream->data = static_cast<cmEventBasedConnection*>(this); +} + void cmStdIoConnection::SetServer(cmServerBase* s) { cmConnection::SetServer(s); + if (!s) { + return; + } - if (uv_guess_handle(1) == UV_TTY) { - usesTty = true; - - this->Input.tty = new uv_tty_t(); - uv_tty_init(this->Server->GetLoop(), this->Input.tty, 0, 1); - uv_tty_set_mode(this->Input.tty, UV_TTY_MODE_NORMAL); - this->Input.tty->data = static_cast<cmEventBasedConnection*>(this); - this->ReadStream = reinterpret_cast<uv_stream_t*>(this->Input.tty); - - this->Output.tty = new uv_tty_t(); - uv_tty_init(this->Server->GetLoop(), this->Output.tty, 1, 0); - uv_tty_set_mode(this->Output.tty, UV_TTY_MODE_NORMAL); - this->Output.tty->data = static_cast<cmEventBasedConnection*>(this); - this->WriteStream = reinterpret_cast<uv_stream_t*>(this->Output.tty); - } else { - usesTty = false; - - this->Input.pipe = new uv_pipe_t(); - uv_pipe_init(this->Server->GetLoop(), this->Input.pipe, 0); - uv_pipe_open(this->Input.pipe, 0); - this->Input.pipe->data = static_cast<cmEventBasedConnection*>(this); - this->ReadStream = reinterpret_cast<uv_stream_t*>(this->Input.pipe); - - this->Output.pipe = new uv_pipe_t(); - uv_pipe_init(this->Server->GetLoop(), this->Output.pipe, 0); - uv_pipe_open(this->Output.pipe, 1); - this->Output.pipe->data = static_cast<cmEventBasedConnection*>(this); - this->WriteStream = reinterpret_cast<uv_stream_t*>(this->Output.pipe); + SetupStream(this->ReadStream, 0); + SetupStream(this->WriteStream, 1); +} + +void shutdown_connection(uv_prepare_t* prepare) +{ + cmStdIoConnection* connection = + reinterpret_cast<cmStdIoConnection*>(prepare->data); + + if (!uv_is_closing(reinterpret_cast<uv_handle_t*>(prepare))) { + uv_close(reinterpret_cast<uv_handle_t*>(prepare), + &cmEventBasedConnection::on_close_delete<uv_prepare_t>); } + connection->OnDisconnect(0); } bool cmStdIoConnection::OnServeStart(std::string* pString) { - uv_read_start(this->ReadStream, on_alloc_buffer, on_read); Server->OnConnected(this); + if (this->ReadStream) { + uv_read_start(this->ReadStream, on_alloc_buffer, on_read); + } else if (uv_guess_handle(0) == UV_FILE) { + char buffer[1024]; + while (auto len = read(0, buffer, sizeof(buffer))) { + ReadData(std::string(buffer, buffer + len)); + } + + // We can't start the disconnect from here, add a prepare hook to do that + // for us + auto prepare = new uv_prepare_t(); + prepare->data = this; + uv_prepare_init(Server->GetLoop(), prepare); + uv_prepare_start(prepare, shutdown_connection); + } return cmConnection::OnServeStart(pString); } -bool cmStdIoConnection::OnConnectionShuttingDown() +void cmStdIoConnection::ShutdownStream(uv_stream_t*& stream) { - cmEventBasedConnection::OnConnectionShuttingDown(); + if (!stream) { + return; + } + switch (stream->type) { + case UV_TTY: { + assert(!uv_is_closing(reinterpret_cast<uv_handle_t*>(stream))); + if (!uv_is_closing(reinterpret_cast<uv_handle_t*>(stream))) { + uv_close(reinterpret_cast<uv_handle_t*>(stream), + &on_close_delete<uv_tty_t>); + } + break; + } + case UV_FILE: + case UV_NAMED_PIPE: { + assert(!uv_is_closing(reinterpret_cast<uv_handle_t*>(stream))); + if (!uv_is_closing(reinterpret_cast<uv_handle_t*>(stream))) { + uv_close(reinterpret_cast<uv_handle_t*>(stream), + &on_close_delete<uv_pipe_t>); + } + break; + } + default: + assert(false && "Unable to determine stream type"); + } + + stream = nullptr; +} - if (usesTty) { - uv_read_stop(reinterpret_cast<uv_stream_t*>(this->Input.tty)); - uv_close(reinterpret_cast<uv_handle_t*>(this->Input.tty), - &on_close_delete); - uv_close(reinterpret_cast<uv_handle_t*>(this->Output.tty), - &on_close_delete); - } else { - uv_close(reinterpret_cast<uv_handle_t*>(this->Input.pipe), - &on_close_delete); - uv_close(reinterpret_cast<uv_handle_t*>(this->Output.pipe), - &on_close_delete); +bool cmStdIoConnection::OnConnectionShuttingDown() +{ + if (ReadStream) { + uv_read_stop(ReadStream); } + ShutdownStream(ReadStream); + ShutdownStream(WriteStream); + + cmEventBasedConnection::OnConnectionShuttingDown(); + return true; } @@ -93,6 +156,13 @@ void cmConnectionBufferStrategy::clear() { } +std::string cmServerBufferStrategy::BufferOutMessage( + const std::string& rawBuffer) const +{ + return std::string("\n") + kSTART_MAGIC + std::string("\n") + rawBuffer + + kEND_MAGIC + std::string("\n"); +} + std::string cmServerBufferStrategy::BufferMessage(std::string& RawReadBuffer) { for (;;) { diff --git a/Source/cmServerConnection.h b/Source/cmServerConnection.h index df404ce..4ca908d 100644 --- a/Source/cmServerConnection.h +++ b/Source/cmServerConnection.h @@ -25,6 +25,7 @@ class cmServerBufferStrategy : public cmConnectionBufferStrategy { public: std::string BufferMessage(std::string& rawBuffer) override; + std::string BufferOutMessage(const std::string& rawBuffer) const override; private: std::string RequestBuffer; @@ -45,16 +46,8 @@ public: bool OnServeStart(std::string* pString) override; private: - typedef union - { - uv_tty_t* tty; - uv_pipe_t* pipe; - } InOutUnion; - - bool usesTty = false; - - InOutUnion Input; - InOutUnion Output; + void SetupStream(uv_stream_t*& stream, int file_id); + void ShutdownStream(uv_stream_t*& stream); }; /*** diff --git a/Source/cmServerProtocol.cxx b/Source/cmServerProtocol.cxx index 2bcfefd..1b47608 100644 --- a/Source/cmServerProtocol.cxx +++ b/Source/cmServerProtocol.cxx @@ -66,7 +66,7 @@ template <class T> Json::Value fromStringList(const T& in) { Json::Value result = Json::arrayValue; - for (const std::string& i : in) { + for (std::string const& i : in) { result.append(i); } return result; @@ -75,7 +75,7 @@ Json::Value fromStringList(const T& in) std::vector<std::string> toStringList(const Json::Value& in) { std::vector<std::string> result; - for (const auto& it : in) { + for (auto const& it : in) { result.push_back(it.asString()); } return result; @@ -89,19 +89,17 @@ void getCMakeInputs(const cmGlobalGenerator* gg, const std::string& sourceDir, { const std::string cmakeRootDir = cmSystemTools::GetCMakeRoot() + '/'; std::vector<cmMakefile*> const& makefiles = gg->GetMakefiles(); - for (auto it = makefiles.begin(); it != makefiles.end(); ++it) { - const std::vector<std::string> listFiles = (*it)->GetListFiles(); + for (cmMakefile const* mf : makefiles) { + for (std::string const& lf : mf->GetListFiles()) { - for (auto jt = listFiles.begin(); jt != listFiles.end(); ++jt) { - - const std::string startOfFile = jt->substr(0, cmakeRootDir.size()); + const std::string startOfFile = lf.substr(0, cmakeRootDir.size()); const bool isInternal = (startOfFile == cmakeRootDir); - const bool isTemporary = !isInternal && (jt->find(buildDir + '/') == 0); + const bool isTemporary = !isInternal && (lf.find(buildDir + '/') == 0); - std::string toAdd = *jt; + std::string toAdd = lf; if (!sourceDir.empty()) { const std::string& relative = - cmSystemTools::RelativePath(sourceDir.c_str(), jt->c_str()); + cmSystemTools::RelativePath(sourceDir.c_str(), lf.c_str()); if (toAdd.size() > relative.size()) { toAdd = relative; } @@ -501,14 +499,14 @@ cmServerResponse cmServerProtocol1::ProcessCache( if (keys.empty()) { keys = allKeys; } else { - for (const auto& i : keys) { + for (auto const& i : keys) { if (std::find(allKeys.begin(), allKeys.end(), i) == allKeys.end()) { return request.ReportError("Key \"" + i + "\" not found in cache."); } } } std::sort(keys.begin(), keys.end()); - for (const auto& key : keys) { + for (auto const& key : keys) { Json::Value entry = Json::objectValue; entry[kKEY_KEY] = key; entry[kTYPE_KEY] = @@ -517,7 +515,7 @@ cmServerResponse cmServerProtocol1::ProcessCache( Json::Value props = Json::objectValue; bool haveProperties = false; - for (const auto& prop : state->GetCacheEntryPropertyList(key)) { + for (auto const& prop : state->GetCacheEntryPropertyList(key)) { haveProperties = true; props[prop] = state->GetCacheEntryProperty(key, prop); } @@ -591,7 +589,7 @@ public: std::string Language; std::string Flags; std::vector<std::string> Defines; - std::vector<std::pair<std::string, bool> > IncludePathList; + std::vector<std::pair<std::string, bool>> IncludePathList; }; bool LanguageData::operator==(const LanguageData& other) const @@ -604,7 +602,7 @@ bool LanguageData::operator==(const LanguageData& other) const void LanguageData::SetDefines(const std::set<std::string>& defines) { std::vector<std::string> result; - for (const auto& i : defines) { + for (std::string const& i : defines) { result.push_back(i); } std::sort(result.begin(), result.end()); @@ -621,11 +619,11 @@ struct hash<LanguageData> using std::hash; size_t result = hash<std::string>()(in.Language) ^ hash<std::string>()(in.Flags); - for (const auto& i : in.IncludePathList) { + for (auto const& i : in.IncludePathList) { result = result ^ (hash<std::string>()(i.first) ^ (i.second ? std::numeric_limits<size_t>::max() : 0)); } - for (const auto& i : in.Defines) { + for (auto const& i : in.Defines) { result = result ^ hash<std::string>()(i); } result = @@ -649,7 +647,7 @@ static Json::Value DumpSourceFileGroup(const LanguageData& data, } if (!data.IncludePathList.empty()) { Json::Value includes = Json::arrayValue; - for (const auto& i : data.IncludePathList) { + for (auto const& i : data.IncludePathList) { Json::Value tmp = Json::objectValue; tmp[kPATH_KEY] = i.first; if (i.second) { @@ -667,7 +665,7 @@ static Json::Value DumpSourceFileGroup(const LanguageData& data, result[kIS_GENERATED_KEY] = data.IsGenerated; Json::Value sourcesValue = Json::arrayValue; - for (const auto& i : files) { + for (auto const& i : files) { const std::string relPath = cmSystemTools::RelativePath(baseDir.c_str(), i.c_str()); sourcesValue.append(relPath.size() < i.size() ? relPath : i); @@ -686,7 +684,7 @@ static Json::Value DumpSourceFilesList( std::vector<cmSourceFile*> files; target->GetSourceFiles(files, config); - std::unordered_map<LanguageData, std::vector<std::string> > fileGroups; + std::unordered_map<LanguageData, std::vector<std::string>> fileGroups; for (cmSourceFile* file : files) { LanguageData fileData; fileData.Language = file->GetLanguage(); @@ -723,8 +721,8 @@ static Json::Value DumpSourceFilesList( const std::string baseDir = target->Makefile->GetCurrentSourceDirectory(); Json::Value result = Json::arrayValue; - for (auto it = fileGroups.begin(); it != fileGroups.end(); ++it) { - Json::Value group = DumpSourceFileGroup(it->first, it->second, baseDir); + for (auto const& it : fileGroups) { + Json::Value group = DumpSourceFileGroup(it.first, it.second, baseDir); if (!group.isNull()) { result.append(group); } @@ -756,7 +754,7 @@ static Json::Value DumpBacktrace(const cmListFileBacktrace& backtrace) static void DumpBacktraceRange(Json::Value& result, const std::string& type, cmBacktraceRange range) { - for (const auto& bt : range) { + for (auto const& bt : range) { Json::Value obj = Json::objectValue; obj[kTYPE_KEY] = type; obj[kBACKTRACE_KEY] = DumpBacktrace(bt); @@ -872,7 +870,7 @@ static Json::Value DumpTarget(cmGeneratorTarget* target, std::set<std::string> languages; target->GetLanguages(languages, config); std::map<std::string, LanguageData> languageDataMap; - for (const auto& lang : languages) { + for (std::string const& lang : languages) { LanguageData& ld = languageDataMap[lang]; ld.Language = lang; lg->GetTargetCompileFlags(target, config, lang, ld.Flags); @@ -881,7 +879,7 @@ static Json::Value DumpTarget(cmGeneratorTarget* target, ld.SetDefines(defines); std::vector<std::string> includePathList; lg->GetIncludeDirectories(includePathList, target, lang, config, true); - for (auto i : includePathList) { + for (std::string const& i : includePathList) { ld.IncludePathList.push_back( std::make_pair(i, target->IsSystemIncludeDirectory(i, config))); } @@ -902,7 +900,7 @@ static Json::Value DumpTargetsList( Json::Value result = Json::arrayValue; std::vector<cmGeneratorTarget*> targetList; - for (const auto& lgIt : generators) { + for (auto const& lgIt : generators) { const auto& list = lgIt->GetGeneratorTargets(); targetList.insert(targetList.end(), list.begin(), list.end()); } @@ -924,7 +922,7 @@ static Json::Value DumpProjectList(const cmake* cm, std::string const& config) auto globalGen = cm->GetGlobalGenerator(); - for (const auto& projectIt : globalGen->GetProjectMap()) { + for (auto const& projectIt : globalGen->GetProjectMap()) { Json::Value pObj = Json::objectValue; pObj[kNAME_KEY] = projectIt.first; @@ -959,7 +957,7 @@ static Json::Value DumpConfigurationsList(const cmake* cm) { Json::Value result = Json::arrayValue; - for (const std::string& c : getConfigurations(cm)) { + for (std::string const& c : getConfigurations(cm)) { result.append(DumpConfiguration(cm, c)); } @@ -1022,12 +1020,12 @@ cmServerResponse cmServerProtocol1::ProcessConfigure( if (passedArgs.isString()) { cacheArgs.push_back(passedArgs.asString()); } else if (passedArgs.isArray()) { - for (auto i = passedArgs.begin(); i != passedArgs.end(); ++i) { - if (!i->isString()) { + for (auto const& arg : passedArgs) { + if (!arg.isString()) { cacheArgumentsError = true; break; } - cacheArgs.push_back(i->asString()); + cacheArgs.push_back(arg.asString()); } } else { cacheArgumentsError = true; @@ -1148,7 +1146,7 @@ cmServerResponse cmServerProtocol1::ProcessSetGlobalSettings( kWARN_UNINITIALIZED_KEY, kWARN_UNUSED_KEY, kWARN_UNUSED_CLI_KEY, kCHECK_SYSTEM_VARS_KEY }; - for (const auto& i : boolValues) { + for (std::string const& i : boolValues) { if (!request.Data[i].isNull() && !request.Data[i].isBool()) { return request.ReportError("\"" + i + "\" must be unset or a bool value."); @@ -1178,11 +1176,11 @@ cmServerResponse cmServerProtocol1::ProcessFileSystemWatchers( const cmFileMonitor* const fm = FileMonitor(); Json::Value result = Json::objectValue; Json::Value files = Json::arrayValue; - for (const auto& f : fm->WatchedFiles()) { + for (auto const& f : fm->WatchedFiles()) { files.append(f); } Json::Value directories = Json::arrayValue; - for (const auto& d : fm->WatchedDirectories()) { + for (auto const& d : fm->WatchedDirectories()) { directories.append(d); } result[kWATCHED_FILES_KEY] = files; diff --git a/Source/cmSetCommand.h b/Source/cmSetCommand.h index 3faec6f..76e3eae 100644 --- a/Source/cmSetCommand.h +++ b/Source/cmSetCommand.h @@ -23,14 +23,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmSetCommand; } + cmCommand* Clone() override { return new cmSetCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmSetDirectoryPropertiesCommand.h b/Source/cmSetDirectoryPropertiesCommand.h index 16a07da..473347c 100644 --- a/Source/cmSetDirectoryPropertiesCommand.h +++ b/Source/cmSetDirectoryPropertiesCommand.h @@ -16,17 +16,14 @@ class cmMakefile; class cmSetDirectoryPropertiesCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE - { - return new cmSetDirectoryPropertiesCommand; - } + cmCommand* Clone() override { return new cmSetDirectoryPropertiesCommand; } /** * This is called when the command is first encountered in * the input file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; /** * Static entry point for use by other commands diff --git a/Source/cmSetPropertyCommand.cxx b/Source/cmSetPropertyCommand.cxx index 338fcea..7efcc04 100644 --- a/Source/cmSetPropertyCommand.cxx +++ b/Source/cmSetPropertyCommand.cxx @@ -204,20 +204,19 @@ bool cmSetPropertyCommand::HandleDirectoryMode() bool cmSetPropertyCommand::HandleTargetMode() { - for (std::set<std::string>::const_iterator ni = this->Names.begin(); - ni != this->Names.end(); ++ni) { - if (this->Makefile->IsAlias(*ni)) { + for (std::string const& name : this->Names) { + if (this->Makefile->IsAlias(name)) { this->SetError("can not be used on an ALIAS target."); return false; } - if (cmTarget* target = this->Makefile->FindTargetToUse(*ni)) { + if (cmTarget* target = this->Makefile->FindTargetToUse(name)) { // Handle the current target. if (!this->HandleTarget(target)) { return false; } } else { std::ostringstream e; - e << "could not find TARGET " << *ni + e << "could not find TARGET " << name << ". Perhaps it has not yet been created."; this->SetError(e.str()); return false; @@ -248,16 +247,15 @@ bool cmSetPropertyCommand::HandleTarget(cmTarget* target) bool cmSetPropertyCommand::HandleSourceMode() { - for (std::set<std::string>::const_iterator ni = this->Names.begin(); - ni != this->Names.end(); ++ni) { + for (std::string const& name : this->Names) { // Get the source file. - if (cmSourceFile* sf = this->Makefile->GetOrCreateSource(*ni)) { + if (cmSourceFile* sf = this->Makefile->GetOrCreateSource(name)) { if (!this->HandleSource(sf)) { return false; } } else { std::ostringstream e; - e << "given SOURCE name that could not be found or created: " << *ni; + e << "given SOURCE name that could not be found or created: " << name; this->SetError(e.str()); return false; } @@ -303,9 +301,8 @@ bool cmSetPropertyCommand::HandleTestMode() if (!this->Names.empty()) { std::ostringstream e; e << "given TEST names that do not exist:\n"; - for (std::set<std::string>::const_iterator ni = this->Names.begin(); - ni != this->Names.end(); ++ni) { - e << " " << *ni << "\n"; + for (std::string const& name : this->Names) { + e << " " << name << "\n"; } this->SetError(e.str()); return false; @@ -359,19 +356,18 @@ bool cmSetPropertyCommand::HandleCacheMode() return false; } - for (std::set<std::string>::const_iterator ni = this->Names.begin(); - ni != this->Names.end(); ++ni) { + for (std::string const& name : this->Names) { // Get the source file. cmMakefile* mf = this->GetMakefile(); cmake* cm = mf->GetCMakeInstance(); - const char* existingValue = cm->GetState()->GetCacheEntryValue(*ni); + const char* existingValue = cm->GetState()->GetCacheEntryValue(name); if (existingValue) { - if (!this->HandleCacheEntry(*ni)) { + if (!this->HandleCacheEntry(name)) { return false; } } else { std::ostringstream e; - e << "could not find CACHE variable " << *ni + e << "could not find CACHE variable " << name << ". Perhaps it has not yet been created."; this->SetError(e.str()); return false; @@ -403,16 +399,15 @@ bool cmSetPropertyCommand::HandleInstallMode() { cmake* cm = this->Makefile->GetCMakeInstance(); - for (std::set<std::string>::const_iterator i = this->Names.begin(); - i != this->Names.end(); ++i) { + for (std::string const& name : this->Names) { if (cmInstalledFile* file = - cm->GetOrCreateInstalledFile(this->Makefile, *i)) { + cm->GetOrCreateInstalledFile(this->Makefile, name)) { if (!this->HandleInstall(file)) { return false; } } else { std::ostringstream e; - e << "given INSTALL name that could not be found or created: " << *i; + e << "given INSTALL name that could not be found or created: " << name; this->SetError(e.str()); return false; } diff --git a/Source/cmSetPropertyCommand.h b/Source/cmSetPropertyCommand.h index 4d3d996..f1126bb 100644 --- a/Source/cmSetPropertyCommand.h +++ b/Source/cmSetPropertyCommand.h @@ -22,14 +22,14 @@ class cmSetPropertyCommand : public cmCommand public: cmSetPropertyCommand(); - cmCommand* Clone() CM_OVERRIDE { return new cmSetPropertyCommand; } + cmCommand* Clone() override { return new cmSetPropertyCommand; } /** * This is called when the command is first encountered in * the input file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: std::set<std::string> Names; diff --git a/Source/cmSetSourceFilesPropertiesCommand.h b/Source/cmSetSourceFilesPropertiesCommand.h index ca3d74d..afb19f6 100644 --- a/Source/cmSetSourceFilesPropertiesCommand.h +++ b/Source/cmSetSourceFilesPropertiesCommand.h @@ -16,17 +16,14 @@ class cmMakefile; class cmSetSourceFilesPropertiesCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE - { - return new cmSetSourceFilesPropertiesCommand; - } + cmCommand* Clone() override { return new cmSetSourceFilesPropertiesCommand; } /** * This is called when the command is first encountered in * the input file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; static bool RunCommand(cmMakefile* mf, std::vector<std::string>::const_iterator filebeg, diff --git a/Source/cmSetTargetPropertiesCommand.h b/Source/cmSetTargetPropertiesCommand.h index de20a7b..c9755da 100644 --- a/Source/cmSetTargetPropertiesCommand.h +++ b/Source/cmSetTargetPropertiesCommand.h @@ -16,14 +16,14 @@ class cmMakefile; class cmSetTargetPropertiesCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE { return new cmSetTargetPropertiesCommand; } + cmCommand* Clone() override { return new cmSetTargetPropertiesCommand; } /** * This is called when the command is first encountered in * the input file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; /** * Used by this command and cmSetPropertiesCommand diff --git a/Source/cmSetTestsPropertiesCommand.h b/Source/cmSetTestsPropertiesCommand.h index cd9f486..84b2645 100644 --- a/Source/cmSetTestsPropertiesCommand.h +++ b/Source/cmSetTestsPropertiesCommand.h @@ -16,14 +16,14 @@ class cmMakefile; class cmSetTestsPropertiesCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE { return new cmSetTestsPropertiesCommand; } + cmCommand* Clone() override { return new cmSetTestsPropertiesCommand; } /** * This is called when the command is first encountered in * the input file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; static bool SetOneTest(const std::string& tname, std::vector<std::string>& propertyPairs, diff --git a/Source/cmSiteNameCommand.h b/Source/cmSiteNameCommand.h index c042a13..2d8dc17 100644 --- a/Source/cmSiteNameCommand.h +++ b/Source/cmSiteNameCommand.h @@ -23,14 +23,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmSiteNameCommand; } + cmCommand* Clone() override { return new cmSiteNameCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmSourceFile.cxx b/Source/cmSourceFile.cxx index 6d2b98d..0964bea 100644 --- a/Source/cmSourceFile.cxx +++ b/Source/cmSourceFile.cxx @@ -150,15 +150,13 @@ bool cmSourceFile::FindFullPath(std::string* error) if (this->TryFullPath(tryPath, "")) { return true; } - for (std::vector<std::string>::const_iterator ei = srcExts.begin(); - ei != srcExts.end(); ++ei) { - if (this->TryFullPath(tryPath, *ei)) { + for (std::string const& ext : srcExts) { + if (this->TryFullPath(tryPath, ext)) { return true; } } - for (std::vector<std::string>::const_iterator ei = hdrExts.begin(); - ei != hdrExts.end(); ++ei) { - if (this->TryFullPath(tryPath, *ei)) { + for (std::string const& ext : hdrExts) { + if (this->TryFullPath(tryPath, ext)) { return true; } } @@ -171,13 +169,11 @@ bool cmSourceFile::FindFullPath(std::string* error) } missing += this->Location.GetName(); e << "Cannot find source file:\n " << missing << "\nTried extensions"; - for (std::vector<std::string>::const_iterator ext = srcExts.begin(); - ext != srcExts.end(); ++ext) { - e << " ." << *ext; + for (std::string const& srcExt : srcExts) { + e << " ." << srcExt; } - for (std::vector<std::string>::const_iterator ext = hdrExts.begin(); - ext != hdrExts.end(); ++ext) { - e << " ." << *ext; + for (std::string const& ext : hdrExts) { + e << " ." << ext; } if (error) { *error = e.str(); diff --git a/Source/cmSourceFileLocation.cxx b/Source/cmSourceFileLocation.cxx index 727adeb..4f337f2 100644 --- a/Source/cmSourceFileLocation.cxx +++ b/Source/cmSourceFileLocation.cxx @@ -28,21 +28,6 @@ cmSourceFileLocation::cmSourceFileLocation(const cmSourceFileLocation& loc) this->Name = loc.Name; } -cmSourceFileLocation& cmSourceFileLocation::operator=( - const cmSourceFileLocation& loc) -{ - if (this == &loc) { - return *this; - } - this->Makefile = loc.Makefile; - this->AmbiguousDirectory = loc.AmbiguousDirectory; - this->AmbiguousExtension = loc.AmbiguousExtension; - this->Directory = loc.Directory; - this->Name = loc.Name; - this->UpdateExtension(this->Name); - return *this; -} - cmSourceFileLocation::cmSourceFileLocation(cmMakefile const* mf, const std::string& name) : Makefile(mf) diff --git a/Source/cmSourceFileLocation.h b/Source/cmSourceFileLocation.h index 6dbc2da..fb5b330 100644 --- a/Source/cmSourceFileLocation.h +++ b/Source/cmSourceFileLocation.h @@ -29,7 +29,6 @@ public: cmSourceFileLocation(cmMakefile const* mf, const std::string& name); cmSourceFileLocation(); cmSourceFileLocation(const cmSourceFileLocation& loc); - cmSourceFileLocation& operator=(const cmSourceFileLocation& loc); /** * Return whether the given source file location could refers to the @@ -79,7 +78,7 @@ public: */ cmMakefile const* GetMakefile() const { return this->Makefile; } private: - cmMakefile const* Makefile; + cmMakefile const* const Makefile; bool AmbiguousDirectory; bool AmbiguousExtension; std::string Directory; @@ -90,6 +89,9 @@ private: // Update the location with additional knowledge. void Update(cmSourceFileLocation const& loc); void UpdateExtension(const std::string& name); + + cmSourceFileLocation& operator=(const cmSourceFileLocation& loc) + CM_EQ_DELETE; }; #endif diff --git a/Source/cmSourceGroupCommand.cxx b/Source/cmSourceGroupCommand.cxx index 77fde7b..69983a8 100644 --- a/Source/cmSourceGroupCommand.cxx +++ b/Source/cmSourceGroupCommand.cxx @@ -41,8 +41,8 @@ std::set<std::string> getSourceGroupFilesPaths( std::set<std::string> ret; const std::string::size_type rootLength = root.length(); - for (size_t i = 0; i < files.size(); ++i) { - ret.insert(files[i].substr(rootLength + 1)); // +1 to also omnit last '/' + for (std::string const& file : files) { + ret.insert(file.substr(rootLength + 1)); // +1 to also omnit last '/' } return ret; @@ -51,9 +51,9 @@ std::set<std::string> getSourceGroupFilesPaths( bool rootIsPrefix(const std::string& root, const std::vector<std::string>& files, std::string& error) { - for (size_t i = 0; i < files.size(); ++i) { - if (!cmSystemTools::StringStartsWith(files[i], root.c_str())) { - error = "ROOT: " + root + " is not a prefix of file: " + files[i]; + for (std::string const& file : files) { + if (!cmSystemTools::StringStartsWith(file, root.c_str())) { + error = "ROOT: " + root + " is not a prefix of file: " + file; return false; } } @@ -61,23 +61,6 @@ bool rootIsPrefix(const std::string& root, return true; } -cmSourceGroup* addSourceGroup(const std::vector<std::string>& tokenizedPath, - cmMakefile& makefile) -{ - cmSourceGroup* sg; - - sg = makefile.GetSourceGroup(tokenizedPath); - if (!sg) { - makefile.AddSourceGroup(tokenizedPath); - sg = makefile.GetSourceGroup(tokenizedPath); - if (!sg) { - return nullptr; - } - } - - return sg; -} - std::string prepareFilePathForTree(const std::string& path, const std::string& currentSourceDir) { @@ -108,26 +91,25 @@ bool addFilesToItsSourceGroups(const std::string& root, { cmSourceGroup* sg; - for (std::set<std::string>::const_iterator it = sgFilesPaths.begin(); - it != sgFilesPaths.end(); ++it) { + for (std::string const& sgFilesPath : sgFilesPaths) { std::vector<std::string> tokenizedPath; if (!prefix.empty()) { - tokenizedPath = tokenizePath(prefix + '/' + *it); + tokenizedPath = tokenizePath(prefix + '/' + sgFilesPath); } else { - tokenizedPath = tokenizePath(*it); + tokenizedPath = tokenizePath(sgFilesPath); } if (tokenizedPath.size() > 1) { tokenizedPath.pop_back(); - sg = addSourceGroup(tokenizedPath, makefile); + sg = makefile.GetOrCreateSourceGroup(tokenizedPath); if (!sg) { - errorMsg = "Could not create source group for file: " + *it; + errorMsg = "Could not create source group for file: " + sgFilesPath; return false; } - const std::string fullPath = getFullFilePath(root, *it); + const std::string fullPath = getFullFilePath(root, sgFilesPath); sg->AddGroupFile(fullPath); } } @@ -158,20 +140,7 @@ bool cmSourceGroupCommand::InitialPass(std::vector<std::string> const& args, return true; } - std::string delimiter = "\\"; - if (this->Makefile->GetDefinition("SOURCE_GROUP_DELIMITER")) { - delimiter = this->Makefile->GetDefinition("SOURCE_GROUP_DELIMITER"); - } - - std::vector<std::string> folders = - cmSystemTools::tokenize(args[0], delimiter); - - cmSourceGroup* sg = nullptr; - sg = this->Makefile->GetSourceGroup(folders); - if (!sg) { - this->Makefile->AddSourceGroup(folders); - sg = this->Makefile->GetSourceGroup(folders); - } + cmSourceGroup* sg = this->Makefile->GetOrCreateSourceGroup(args[0]); if (!sg) { this->SetError("Could not create or find source group"); diff --git a/Source/cmSourceGroupCommand.h b/Source/cmSourceGroupCommand.h index 1af5274..ed02ca5 100644 --- a/Source/cmSourceGroupCommand.h +++ b/Source/cmSourceGroupCommand.h @@ -24,14 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmSourceGroupCommand; } + cmCommand* Clone() override { return new cmSourceGroupCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: bool processTree(const std::vector<std::string>& args, diff --git a/Source/cmState.cxx b/Source/cmState.cxx index 90d8b7b..5957b5b 100644 --- a/Source/cmState.cxx +++ b/Source/cmState.cxx @@ -444,15 +444,11 @@ std::vector<std::string> cmState::GetCommandNames() const std::vector<std::string> commandNames; commandNames.reserve(this->BuiltinCommands.size() + this->ScriptedCommands.size()); - for (std::map<std::string, cmCommand*>::const_iterator cmds = - this->BuiltinCommands.begin(); - cmds != this->BuiltinCommands.end(); ++cmds) { - commandNames.push_back(cmds->first); + for (auto const& bc : this->BuiltinCommands) { + commandNames.push_back(bc.first); } - for (std::map<std::string, cmCommand*>::const_iterator cmds = - this->ScriptedCommands.begin(); - cmds != this->ScriptedCommands.end(); ++cmds) { - commandNames.push_back(cmds->first); + for (auto const& sc : this->ScriptedCommands) { + commandNames.push_back(sc.first); } std::sort(commandNames.begin(), commandNames.end()); commandNames.erase(std::unique(commandNames.begin(), commandNames.end()), diff --git a/Source/cmStateDirectory.cxx b/Source/cmStateDirectory.cxx index 46a1858..5aa8e5b 100644 --- a/Source/cmStateDirectory.cxx +++ b/Source/cmStateDirectory.cxx @@ -6,7 +6,6 @@ #include <algorithm> #include <assert.h> #include <iterator> -#include <map> #include <utility> #include "cmProperty.h" @@ -81,7 +80,7 @@ void cmStateDirectory::ComputeRelativePathTopBinary() if (result.size() < 2 || result.substr(0, 2) != "//") { this->DirectoryState->RelativePathTopBinary = result; } else { - this->DirectoryState->RelativePathTopBinary = ""; + this->DirectoryState->RelativePathTopBinary.clear(); } } @@ -423,7 +422,7 @@ const char* cmStateDirectory::GetProperty(const std::string& prop, bool chain) const { static std::string output; - output = ""; + output.clear(); if (prop == "PARENT_DIRECTORY") { cmStateSnapshot parent = this->Snapshot_.GetBuildsystemDirectoryParent(); if (parent.IsValid()) { @@ -443,9 +442,8 @@ const char* cmStateDirectory::GetProperty(const std::string& prop, std::vector<std::string> child_dirs; std::vector<cmStateSnapshot> const& children = this->DirectoryState->Children; - for (std::vector<cmStateSnapshot>::const_iterator ci = children.begin(); - ci != children.end(); ++ci) { - child_dirs.push_back(ci->GetDirectory().GetCurrentSource()); + for (cmStateSnapshot const& ci : children) { + child_dirs.push_back(ci.GetDirectory().GetCurrentSource()); } output = cmJoin(child_dirs, ";"); return output.c_str(); @@ -514,10 +512,8 @@ std::vector<std::string> cmStateDirectory::GetPropertyKeys() const { std::vector<std::string> keys; keys.reserve(this->DirectoryState->Properties.size()); - for (cmPropertyMap::const_iterator it = - this->DirectoryState->Properties.begin(); - it != this->DirectoryState->Properties.end(); ++it) { - keys.push_back(it->first); + for (auto const& it : this->DirectoryState->Properties) { + keys.push_back(it.first); } return keys; } diff --git a/Source/cmStringCommand.cxx b/Source/cmStringCommand.cxx index 592f66e..55af078 100644 --- a/Source/cmStringCommand.cxx +++ b/Source/cmStringCommand.cxx @@ -4,6 +4,7 @@ #include "cmsys/RegularExpression.hxx" #include <ctype.h> +#include <memory> // IWYU pragma: keep #include <sstream> #include <stdio.h> #include <stdlib.h> @@ -15,7 +16,6 @@ #include "cmSystemTools.h" #include "cmTimestamp.h" #include "cmUuid.h" -#include "cm_auto_ptr.hxx" class cmExecutionStatus; @@ -108,8 +108,8 @@ bool cmStringCommand::HandleHashCommand(std::vector<std::string> const& args) return false; } - CM_AUTO_PTR<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str())); - if (hash.get()) { + std::unique_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str())); + if (hash) { std::string out = hash->HashString(args[2]); this->Makefile->AddDefinition(args[1], out.c_str()); return true; @@ -412,13 +412,13 @@ bool cmStringCommand::RegexReplace(std::vector<std::string> const& args) } // Concatenate the replacement for the match. - for (unsigned int i = 0; i < replacement.size(); ++i) { - if (replacement[i].number < 0) { + for (RegexReplacement const& i : replacement) { + if (i.number < 0) { // This is just a plain-text part of the replacement. - output += replacement[i].value; + output += i.value; } else { // Replace with part of the match. - int n = replacement[i].number; + int n = i.number; std::string::size_type start = re.start(n); std::string::size_type end = re.end(n); std::string::size_type len = input.length() - base; diff --git a/Source/cmStringCommand.h b/Source/cmStringCommand.h index f19f871..b287e37 100644 --- a/Source/cmStringCommand.h +++ b/Source/cmStringCommand.h @@ -22,14 +22,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmStringCommand; } + cmCommand* Clone() override { return new cmStringCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; protected: bool HandleConfigureCommand(std::vector<std::string> const& args); diff --git a/Source/cmSubdirCommand.cxx b/Source/cmSubdirCommand.cxx index 3727dfa..c74ca59 100644 --- a/Source/cmSubdirCommand.cxx +++ b/Source/cmSubdirCommand.cxx @@ -18,36 +18,35 @@ bool cmSubdirCommand::InitialPass(std::vector<std::string> const& args, bool res = true; bool excludeFromAll = false; - for (std::vector<std::string>::const_iterator i = args.begin(); - i != args.end(); ++i) { - if (*i == "EXCLUDE_FROM_ALL") { + for (std::string const& i : args) { + if (i == "EXCLUDE_FROM_ALL") { excludeFromAll = true; continue; } - if (*i == "PREORDER") { + if (i == "PREORDER") { // Ignored continue; } // if they specified a relative path then compute the full std::string srcPath = - std::string(this->Makefile->GetCurrentSourceDirectory()) + "/" + *i; + std::string(this->Makefile->GetCurrentSourceDirectory()) + "/" + i; if (cmSystemTools::FileIsDirectory(srcPath)) { std::string binPath = - std::string(this->Makefile->GetCurrentBinaryDirectory()) + "/" + *i; + std::string(this->Makefile->GetCurrentBinaryDirectory()) + "/" + i; this->Makefile->AddSubDirectory(srcPath, binPath, excludeFromAll, false); } // otherwise it is a full path - else if (cmSystemTools::FileIsDirectory(*i)) { + else if (cmSystemTools::FileIsDirectory(i)) { // we must compute the binPath from the srcPath, we just take the last // element from the source path and use that std::string binPath = std::string(this->Makefile->GetCurrentBinaryDirectory()) + "/" + - cmSystemTools::GetFilenameName(*i); - this->Makefile->AddSubDirectory(*i, binPath, excludeFromAll, false); + cmSystemTools::GetFilenameName(i); + this->Makefile->AddSubDirectory(i, binPath, excludeFromAll, false); } else { std::string error = "Incorrect SUBDIRS command. Directory: "; - error += *i + " does not exist."; + error += i + " does not exist."; this->SetError(error); res = false; } diff --git a/Source/cmSubdirCommand.h b/Source/cmSubdirCommand.h index e5fbb7d..adab757 100644 --- a/Source/cmSubdirCommand.h +++ b/Source/cmSubdirCommand.h @@ -25,14 +25,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmSubdirCommand; } + cmCommand* Clone() override { return new cmSubdirCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmSubdirDependsCommand.h b/Source/cmSubdirDependsCommand.h index bcda82e..2db28c6 100644 --- a/Source/cmSubdirDependsCommand.h +++ b/Source/cmSubdirDependsCommand.h @@ -15,9 +15,9 @@ class cmExecutionStatus; class cmSubdirDependsCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE { return new cmSubdirDependsCommand; } + cmCommand* Clone() override { return new cmSubdirDependsCommand; } bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmSystemTools.cxx b/Source/cmSystemTools.cxx index 5c63d98..4fd10a4 100644 --- a/Source/cmSystemTools.cxx +++ b/Source/cmSystemTools.cxx @@ -353,8 +353,8 @@ bool cmSystemTools::IsInternallyOn(const char* val) return false; } - for (std::string::iterator c = v.begin(); c != v.end(); c++) { - *c = static_cast<char>(toupper(*c)); + for (char& c : v) { + c = static_cast<char>(toupper(c)); } return v == "I_ON"; } @@ -378,8 +378,8 @@ bool cmSystemTools::IsOn(const char* val) onValues.insert("TRUE"); onValues.insert("Y"); } - for (std::string::iterator c = v.begin(); c != v.end(); c++) { - *c = static_cast<char>(toupper(*c)); + for (char& c : v) { + c = static_cast<char>(toupper(c)); } return (onValues.count(v) > 0); } @@ -414,8 +414,8 @@ bool cmSystemTools::IsOff(const char* val) } // Try and avoid toupper(). std::string v(val, len); - for (std::string::iterator c = v.begin(); c != v.end(); c++) { - *c = static_cast<char>(toupper(*c)); + for (char& c : v) { + c = static_cast<char>(toupper(c)); } return (offValues.count(v) > 0); } @@ -458,7 +458,7 @@ void cmSystemTools::ParseWindowsCommandLine(const char* command, arg.append(1, *c); } else if (in_argument) { args.push_back(arg); - arg = ""; + arg.clear(); in_argument = false; } } else { @@ -559,7 +559,7 @@ std::vector<std::string> cmSystemTools::ParseArguments(const char* command) while (*c == ' ' || *c == '\t') { ++c; } - arg = ""; + arg.clear(); if (*c == '"') { // Parse a quoted argument. ++c; @@ -603,6 +603,56 @@ std::vector<std::string> cmSystemTools::ParseArguments(const char* command) return args; } +bool cmSystemTools::SplitProgramFromArgs(std::string const& command, + std::string& program, + std::string& args) +{ + const char* c = command.c_str(); + + // Skip leading whitespace. + while (isspace(static_cast<unsigned char>(*c))) { + ++c; + } + + // Parse one command-line element up to an unquoted space. + bool in_escape = false; + bool in_double = false; + bool in_single = false; + for (; *c; ++c) { + if (in_single) { + if (*c == '\'') { + in_single = false; + } else { + program += *c; + } + } else if (in_escape) { + in_escape = false; + program += *c; + } else if (*c == '\\') { + in_escape = true; + } else if (in_double) { + if (*c == '"') { + in_double = false; + } else { + program += *c; + } + } else if (*c == '"') { + in_double = true; + } else if (*c == '\'') { + in_single = true; + } else if (isspace(static_cast<unsigned char>(*c))) { + break; + } else { + program += *c; + } + } + + // The remainder of the command line holds unparsed arguments. + args = c; + + return !in_single && !in_escape && !in_double; +} + size_t cmSystemTools::CalculateCommandLineLengthLimit() { size_t sz = @@ -650,9 +700,8 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command, double timeout, Encoding encoding) { std::vector<const char*> argv; - for (std::vector<std::string>::const_iterator a = command.begin(); - a != command.end(); ++a) { - argv.push_back(a->c_str()); + for (std::string const& cmd : command) { + argv.push_back(cmd.c_str()); } argv.push_back(nullptr); @@ -754,6 +803,8 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command, } if (captureStdErr) { captureStdErr->append(exception_str, strlen(exception_str)); + } else if (captureStdOut) { + captureStdOut->append(exception_str, strlen(exception_str)); } result = false; } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Error) { @@ -763,6 +814,8 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command, } if (captureStdErr) { captureStdErr->append(error_str, strlen(error_str)); + } else if (captureStdOut) { + captureStdOut->append(error_str, strlen(error_str)); } result = false; } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Expired) { @@ -814,11 +867,10 @@ bool cmSystemTools::DoesFileExistWithExtensions( { std::string hname; - for (std::vector<std::string>::const_iterator ext = headerExts.begin(); - ext != headerExts.end(); ++ext) { + for (std::string const& headerExt : headerExts) { hname = name; hname += "."; - hname += *ext; + hname += headerExt; if (cmSystemTools::FileExists(hname.c_str())) { return true; } @@ -1136,7 +1188,7 @@ void cmSystemTools::ExpandListArgument(const std::string& arg, if (!newArg.empty() || emptyArgs) { // Add the last argument if the string is not empty. newargs.push_back(newArg); - newArg = ""; + newArg.clear(); } } } break; @@ -1327,7 +1379,7 @@ std::string cmSystemTools::CollapseCombinedPath(std::string const& dir, if (fileComponents.empty()) { return dir; } - if (fileComponents[0] != "") { + if (!fileComponents[0].empty()) { // File is not a relative path. return file; } @@ -1367,9 +1419,8 @@ std::vector<std::string> cmSystemTools::GetEnvironmentVariables() void cmSystemTools::AppendEnv(std::vector<std::string> const& env) { - for (std::vector<std::string>::const_iterator eit = env.begin(); - eit != env.end(); ++eit) { - cmSystemTools::PutEnv(*eit); + for (std::string const& eit : env) { + cmSystemTools::PutEnv(eit); } } @@ -1382,10 +1433,7 @@ cmSystemTools::SaveRestoreEnvironment::~SaveRestoreEnvironment() { // First clear everything in the current environment: std::vector<std::string> currentEnv = GetEnvironmentVariables(); - for (std::vector<std::string>::const_iterator eit = currentEnv.begin(); - eit != currentEnv.end(); ++eit) { - std::string var(*eit); - + for (std::string var : currentEnv) { std::string::size_type pos = var.find('='); if (pos != std::string::npos) { var = var.substr(0, pos); @@ -1464,9 +1512,7 @@ bool cmSystemTools::CreateTar(const char* outFileName, a.SetMTime(mtime); a.SetVerbose(verbose); - for (std::vector<std::string>::const_iterator i = files.begin(); - i != files.end(); ++i) { - std::string path = *i; + for (auto path : files) { if (cmSystemTools::FileIsFullPath(path.c_str())) { // Get the relative path to the file. path = cmSystemTools::RelativePath(cwd.c_str(), path.c_str()); @@ -1729,7 +1775,7 @@ int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line, double timeout, std::vector<char>& out, std::vector<char>& err) { - line = ""; + line.clear(); std::vector<char>::iterator outiter = out.begin(); std::vector<char>::iterator erriter = err.begin(); cmProcessOutput processOutput; @@ -2069,19 +2115,19 @@ void cmSystemTools::FindCMakeResources(const char* argv0) cmSystemToolsCMakeGUICommand += "/cmake-gui"; cmSystemToolsCMakeGUICommand += cmSystemTools::GetExecutableExtension(); if (!cmSystemTools::FileExists(cmSystemToolsCMakeGUICommand.c_str())) { - cmSystemToolsCMakeGUICommand = ""; + cmSystemToolsCMakeGUICommand.clear(); } cmSystemToolsCMakeCursesCommand = exe_dir; cmSystemToolsCMakeCursesCommand += "/ccmake"; cmSystemToolsCMakeCursesCommand += cmSystemTools::GetExecutableExtension(); if (!cmSystemTools::FileExists(cmSystemToolsCMakeCursesCommand.c_str())) { - cmSystemToolsCMakeCursesCommand = ""; + cmSystemToolsCMakeCursesCommand.clear(); } cmSystemToolsCMClDepsCommand = exe_dir; cmSystemToolsCMClDepsCommand += "/cmcldeps"; cmSystemToolsCMClDepsCommand += cmSystemTools::GetExecutableExtension(); if (!cmSystemTools::FileExists(cmSystemToolsCMClDepsCommand.c_str())) { - cmSystemToolsCMClDepsCommand = ""; + cmSystemToolsCMClDepsCommand.clear(); } #ifdef CMAKE_BUILD_WITH_CMAKE diff --git a/Source/cmSystemTools.h b/Source/cmSystemTools.h index 9bec361..e7082e6 100644 --- a/Source/cmSystemTools.h +++ b/Source/cmSystemTools.h @@ -255,6 +255,11 @@ public: static void ParseUnixCommandLine(const char* command, std::vector<std::string>& args); + /** Split a command-line string into the parsed command and the unparsed + arguments. Returns false on unfinished quoting or escaping. */ + static bool SplitProgramFromArgs(std::string const& command, + std::string& program, std::string& args); + /** * Handle response file in an argument list and return a new argument list * **/ diff --git a/Source/cmTarget.cxx b/Source/cmTarget.cxx index 1ca013c..49b0664 100644 --- a/Source/cmTarget.cxx +++ b/Source/cmTarget.cxx @@ -5,6 +5,7 @@ #include "cmsys/RegularExpression.hxx" #include <algorithm> #include <assert.h> +#include <iterator> #include <map> #include <set> #include <sstream> @@ -80,22 +81,18 @@ const char* cmTargetPropertyComputer::GetSources<cmTarget>( std::ostringstream ss; const char* sep = ""; - for (std::vector<std::string>::const_iterator i = entries.begin(); - i != entries.end(); ++i) { - std::string const& entry = *i; - + for (std::string const& entry : entries) { std::vector<std::string> files; cmSystemTools::ExpandListArgument(entry, files); - for (std::vector<std::string>::const_iterator li = files.begin(); - li != files.end(); ++li) { - if (cmHasLiteralPrefix(*li, "$<TARGET_OBJECTS:") && - (*li)[li->size() - 1] == '>') { - std::string objLibName = li->substr(17, li->size() - 18); + for (std::string const& file : files) { + if (cmHasLiteralPrefix(file, "$<TARGET_OBJECTS:") && + file[file.size() - 1] == '>') { + std::string objLibName = file.substr(17, file.size() - 18); if (cmGeneratorExpression::Find(objLibName) != std::string::npos) { ss << sep; sep = ";"; - ss << *li; + ss << file; continue; } @@ -130,14 +127,14 @@ const char* cmTargetPropertyComputer::GetSources<cmTarget>( if (addContent) { ss << sep; sep = ";"; - ss << *li; + ss << file; } - } else if (cmGeneratorExpression::Find(*li) == std::string::npos) { + } else if (cmGeneratorExpression::Find(file) == std::string::npos) { ss << sep; sep = ";"; - ss << *li; + ss << file; } else { - cmSourceFile* sf = tgt->GetMakefile()->GetOrCreateSource(*li); + cmSourceFile* sf = tgt->GetMakefile()->GetOrCreateSource(file); // Construct what is known about this source file location. cmSourceFileLocation const& location = sf->GetLocation(); std::string sname = location.GetDirectory(); @@ -301,9 +298,8 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type, "COMPILE_PDB_OUTPUT_DIRECTORY_", "MAP_IMPORTED_CONFIG_", "INTERPROCEDURAL_OPTIMIZATION_", nullptr }; - for (std::vector<std::string>::iterator ci = configNames.begin(); - ci != configNames.end(); ++ci) { - std::string configUpper = cmSystemTools::UpperCase(*ci); + for (std::string const& configName : configNames) { + std::string configUpper = cmSystemTools::UpperCase(configName); for (const char** p = configProps; *p; ++p) { // Interface libraries have no output locations, so honor only // the configuration map. @@ -323,7 +319,7 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type, // property directly. if (this->TargetTypeValue != cmStateEnums::EXECUTABLE && this->TargetTypeValue != cmStateEnums::INTERFACE_LIBRARY) { - std::string property = cmSystemTools::UpperCase(*ci); + std::string property = cmSystemTools::UpperCase(configName); property += "_POSTFIX"; this->SetPropertyDefault(property, nullptr); } @@ -483,9 +479,7 @@ void cmTarget::AddSources(std::vector<std::string> const& srcs) { std::string srcFiles; const char* sep = ""; - for (std::vector<std::string>::const_iterator i = srcs.begin(); - i != srcs.end(); ++i) { - std::string filename = *i; + for (auto filename : srcs) { const char* src = filename.c_str(); if (!(src[0] == '$' && src[1] == '<')) { @@ -599,8 +593,9 @@ public: { std::vector<std::string> files; cmSystemTools::ExpandListArgument(entry, files); - std::vector<cmSourceFileLocation> locations(files.size()); - std::transform(files.begin(), files.end(), locations.begin(), + std::vector<cmSourceFileLocation> locations; + locations.reserve(files.size()); + std::transform(files.begin(), files.end(), std::back_inserter(locations), CreateLocation(this->Needle.GetMakefile())); return std::find_if(locations.begin(), locations.end(), @@ -714,12 +709,10 @@ void cmTarget::GetTllSignatureTraces(std::ostream& s, TLLSignature sig) const const char* sigString = (sig == cmTarget::KeywordTLLSignature ? "keyword" : "plain"); s << "The uses of the " << sigString << " signature are here:\n"; - typedef std::vector<std::pair<TLLSignature, cmListFileContext> > Container; cmOutputConverter converter(this->GetMakefile()->GetStateSnapshot()); - for (Container::const_iterator it = this->TLLCommands.begin(); - it != this->TLLCommands.end(); ++it) { - if (it->first == sig) { - cmListFileContext lfc = it->second; + for (auto const& cmd : this->TLLCommands) { + if (cmd.first == sig) { + cmListFileContext lfc = cmd.second; lfc.FilePath = converter.ConvertToRelativePath( this->Makefile->GetState()->GetSourceDirectory(), lfc.FilePath); s << " * " << lfc << std::endl; @@ -1539,7 +1532,7 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config, } // If it was found, set the suffix. if (*loc || *imp) { - suffix = ""; + suffix.clear(); } } else { std::string mcUpper = cmSystemTools::UpperCase(*mci); @@ -1586,7 +1579,7 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config, // configurations and no exact match. if (!*loc && !*imp) { // The suffix computed above is not useful. - suffix = ""; + suffix.clear(); // Look for a configuration-less location. This may be set by // manually-written code. diff --git a/Source/cmTarget.h b/Source/cmTarget.h index c335c81..940e26c 100644 --- a/Source/cmTarget.h +++ b/Source/cmTarget.h @@ -297,7 +297,7 @@ private: std::vector<cmCustomCommand> PreBuildCommands; std::vector<cmCustomCommand> PreLinkCommands; std::vector<cmCustomCommand> PostBuildCommands; - std::vector<std::pair<TLLSignature, cmListFileContext> > TLLCommands; + std::vector<std::pair<TLLSignature, cmListFileContext>> TLLCommands; LinkLibraryVectorType OriginalLinkLibraries; cmMakefile* Makefile; cmTargetInternalPointer Internal; diff --git a/Source/cmTargetCompileDefinitionsCommand.cxx b/Source/cmTargetCompileDefinitionsCommand.cxx index 008d1a2..d159d41 100644 --- a/Source/cmTargetCompileDefinitionsCommand.cxx +++ b/Source/cmTargetCompileDefinitionsCommand.cxx @@ -41,12 +41,11 @@ std::string cmTargetCompileDefinitionsCommand::Join( { std::string defs; std::string sep; - for (std::vector<std::string>::const_iterator it = content.begin(); - it != content.end(); ++it) { - if (cmHasLiteralPrefix(it->c_str(), "-D")) { - defs += sep + it->substr(2); + for (std::string const& it : content) { + if (cmHasLiteralPrefix(it.c_str(), "-D")) { + defs += sep + it.substr(2); } else { - defs += sep + *it; + defs += sep + it; } sep = ";"; } diff --git a/Source/cmTargetCompileDefinitionsCommand.h b/Source/cmTargetCompileDefinitionsCommand.h index 957123a..f910452 100644 --- a/Source/cmTargetCompileDefinitionsCommand.h +++ b/Source/cmTargetCompileDefinitionsCommand.h @@ -20,26 +20,23 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE - { - return new cmTargetCompileDefinitionsCommand; - } + cmCommand* Clone() override { return new cmTargetCompileDefinitionsCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: - void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE; - void HandleMissingTarget(const std::string& name) CM_OVERRIDE; + void HandleImportedTarget(const std::string& tgt) override; + void HandleMissingTarget(const std::string& name) override; bool HandleDirectContent(cmTarget* tgt, const std::vector<std::string>& content, - bool prepend, bool system) CM_OVERRIDE; - std::string Join(const std::vector<std::string>& content) CM_OVERRIDE; + bool prepend, bool system) override; + std::string Join(const std::vector<std::string>& content) override; }; #endif diff --git a/Source/cmTargetCompileFeaturesCommand.cxx b/Source/cmTargetCompileFeaturesCommand.cxx index 1b6c008..722bbe5 100644 --- a/Source/cmTargetCompileFeaturesCommand.cxx +++ b/Source/cmTargetCompileFeaturesCommand.cxx @@ -45,10 +45,9 @@ std::string cmTargetCompileFeaturesCommand::Join( bool cmTargetCompileFeaturesCommand::HandleDirectContent( cmTarget* tgt, const std::vector<std::string>& content, bool, bool) { - for (std::vector<std::string>::const_iterator it = content.begin(); - it != content.end(); ++it) { + for (std::string const& it : content) { std::string error; - if (!this->Makefile->AddRequiredTargetFeature(tgt, *it, &error)) { + if (!this->Makefile->AddRequiredTargetFeature(tgt, it, &error)) { this->SetError(error); return false; } diff --git a/Source/cmTargetCompileFeaturesCommand.h b/Source/cmTargetCompileFeaturesCommand.h index d28cf62..444d260 100644 --- a/Source/cmTargetCompileFeaturesCommand.h +++ b/Source/cmTargetCompileFeaturesCommand.h @@ -16,19 +16,19 @@ class cmTarget; class cmTargetCompileFeaturesCommand : public cmTargetPropCommandBase { - cmCommand* Clone() CM_OVERRIDE { return new cmTargetCompileFeaturesCommand; } + cmCommand* Clone() override { return new cmTargetCompileFeaturesCommand; } bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: - void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE; - void HandleMissingTarget(const std::string& name) CM_OVERRIDE; + void HandleImportedTarget(const std::string& tgt) override; + void HandleMissingTarget(const std::string& name) override; bool HandleDirectContent(cmTarget* tgt, const std::vector<std::string>& content, - bool prepend, bool system) CM_OVERRIDE; - std::string Join(const std::vector<std::string>& content) CM_OVERRIDE; + bool prepend, bool system) override; + std::string Join(const std::vector<std::string>& content) override; }; #endif diff --git a/Source/cmTargetCompileOptionsCommand.h b/Source/cmTargetCompileOptionsCommand.h index 7786896..3fab238 100644 --- a/Source/cmTargetCompileOptionsCommand.h +++ b/Source/cmTargetCompileOptionsCommand.h @@ -20,23 +20,23 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmTargetCompileOptionsCommand; } + cmCommand* Clone() override { return new cmTargetCompileOptionsCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: - void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE; - void HandleMissingTarget(const std::string& name) CM_OVERRIDE; + void HandleImportedTarget(const std::string& tgt) override; + void HandleMissingTarget(const std::string& name) override; bool HandleDirectContent(cmTarget* tgt, const std::vector<std::string>& content, - bool prepend, bool system) CM_OVERRIDE; - std::string Join(const std::vector<std::string>& content) CM_OVERRIDE; + bool prepend, bool system) override; + std::string Join(const std::vector<std::string>& content) override; }; #endif diff --git a/Source/cmTargetIncludeDirectoriesCommand.cxx b/Source/cmTargetIncludeDirectoriesCommand.cxx index 65a3149..4646c7e 100644 --- a/Source/cmTargetIncludeDirectoriesCommand.cxx +++ b/Source/cmTargetIncludeDirectoriesCommand.cxx @@ -47,13 +47,12 @@ std::string cmTargetIncludeDirectoriesCommand::Join( std::string sep; std::string prefix = this->Makefile->GetCurrentSourceDirectory() + std::string("/"); - for (std::vector<std::string>::const_iterator it = content.begin(); - it != content.end(); ++it) { - if (cmSystemTools::FileIsFullPath(it->c_str()) || - cmGeneratorExpression::Find(*it) == 0) { - dirs += sep + *it; + for (std::string const& it : content) { + if (cmSystemTools::FileIsFullPath(it.c_str()) || + cmGeneratorExpression::Find(it) == 0) { + dirs += sep + it; } else { - dirs += sep + prefix + *it; + dirs += sep + prefix + it; } sep = ";"; } @@ -70,13 +69,12 @@ bool cmTargetIncludeDirectoriesCommand::HandleDirectContent( std::string prefix = this->Makefile->GetCurrentSourceDirectory() + std::string("/"); std::set<std::string> sdirs; - for (std::vector<std::string>::const_iterator it = content.begin(); - it != content.end(); ++it) { - if (cmSystemTools::FileIsFullPath(it->c_str()) || - cmGeneratorExpression::Find(*it) == 0) { - sdirs.insert(*it); + for (std::string const& it : content) { + if (cmSystemTools::FileIsFullPath(it.c_str()) || + cmGeneratorExpression::Find(it) == 0) { + sdirs.insert(it); } else { - sdirs.insert(prefix + *it); + sdirs.insert(prefix + it); } } tgt->AddSystemIncludeDirectories(sdirs); diff --git a/Source/cmTargetIncludeDirectoriesCommand.h b/Source/cmTargetIncludeDirectoriesCommand.h index 96eedc8..27a2f43 100644 --- a/Source/cmTargetIncludeDirectoriesCommand.h +++ b/Source/cmTargetIncludeDirectoriesCommand.h @@ -20,30 +20,27 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE - { - return new cmTargetIncludeDirectoriesCommand; - } + cmCommand* Clone() override { return new cmTargetIncludeDirectoriesCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: - void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE; - void HandleMissingTarget(const std::string& name) CM_OVERRIDE; + void HandleImportedTarget(const std::string& tgt) override; + void HandleMissingTarget(const std::string& name) override; bool HandleDirectContent(cmTarget* tgt, const std::vector<std::string>& content, - bool prepend, bool system) CM_OVERRIDE; + bool prepend, bool system) override; void HandleInterfaceContent(cmTarget* tgt, const std::vector<std::string>& content, - bool prepend, bool system) CM_OVERRIDE; + bool prepend, bool system) override; - std::string Join(const std::vector<std::string>& content) CM_OVERRIDE; + std::string Join(const std::vector<std::string>& content) override; }; #endif diff --git a/Source/cmTargetLinkLibrariesCommand.cxx b/Source/cmTargetLinkLibrariesCommand.cxx index bfae53c..dda0464 100644 --- a/Source/cmTargetLinkLibrariesCommand.cxx +++ b/Source/cmTargetLinkLibrariesCommand.cxx @@ -366,6 +366,7 @@ bool cmTargetLinkLibrariesCommand::HandleLibrary(const std::string& lib, if (tgt && (tgt->GetType() != cmStateEnums::STATIC_LIBRARY) && (tgt->GetType() != cmStateEnums::SHARED_LIBRARY) && + (tgt->GetType() != cmStateEnums::UNKNOWN_LIBRARY) && (tgt->GetType() != cmStateEnums::INTERFACE_LIBRARY) && !tgt->IsExecutableWithExports()) { std::ostringstream e; @@ -428,10 +429,9 @@ bool cmTargetLinkLibrariesCommand::HandleLibrary(const std::string& lib, // Include this library in the link interface for the target. if (llt == DEBUG_LibraryType || llt == GENERAL_LibraryType) { // Put in the DEBUG configuration interfaces. - for (std::vector<std::string>::const_iterator i = debugConfigs.begin(); - i != debugConfigs.end(); ++i) { + for (std::string const& dc : debugConfigs) { prop = "LINK_INTERFACE_LIBRARIES_"; - prop += *i; + prop += dc; this->Target->AppendProperty(prop, lib.c_str()); } } @@ -441,10 +441,9 @@ bool cmTargetLinkLibrariesCommand::HandleLibrary(const std::string& lib, // Make sure the DEBUG configuration interfaces exist so that the // general one will not be used as a fall-back. - for (std::vector<std::string>::const_iterator i = debugConfigs.begin(); - i != debugConfigs.end(); ++i) { + for (std::string const& dc : debugConfigs) { prop = "LINK_INTERFACE_LIBRARIES_"; - prop += *i; + prop += dc; if (!this->Target->GetProperty(prop)) { this->Target->SetProperty(prop, ""); } diff --git a/Source/cmTargetLinkLibrariesCommand.h b/Source/cmTargetLinkLibrariesCommand.h index 333ab07..f41af49 100644 --- a/Source/cmTargetLinkLibrariesCommand.h +++ b/Source/cmTargetLinkLibrariesCommand.h @@ -27,14 +27,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmTargetLinkLibrariesCommand; } + cmCommand* Clone() override { return new cmTargetLinkLibrariesCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: void LinkLibraryTypeSpecifierWarning(int left, int right); diff --git a/Source/cmTargetSourcesCommand.h b/Source/cmTargetSourcesCommand.h index b4e08e4..0639e98 100644 --- a/Source/cmTargetSourcesCommand.h +++ b/Source/cmTargetSourcesCommand.h @@ -20,24 +20,24 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmTargetSourcesCommand; } + cmCommand* Clone() override { return new cmTargetSourcesCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: - void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE; - void HandleMissingTarget(const std::string& name) CM_OVERRIDE; + void HandleImportedTarget(const std::string& tgt) override; + void HandleMissingTarget(const std::string& name) override; bool HandleDirectContent(cmTarget* tgt, const std::vector<std::string>& content, - bool prepend, bool system) CM_OVERRIDE; + bool prepend, bool system) override; - std::string Join(const std::vector<std::string>& content) CM_OVERRIDE; + std::string Join(const std::vector<std::string>& content) override; }; #endif diff --git a/Source/cmTestGenerator.cxx b/Source/cmTestGenerator.cxx index 85d4b97..78ca6bc 100644 --- a/Source/cmTestGenerator.cxx +++ b/Source/cmTestGenerator.cxx @@ -2,7 +2,6 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmTestGenerator.h" -#include <map> #include <ostream> #include <utility> @@ -114,10 +113,10 @@ void cmTestGenerator::GenerateScriptForConfig(std::ostream& os, if (!pm.empty()) { os << indent << "set_tests_properties(" << this->Test->GetName() << " PROPERTIES "; - for (cmPropertyMap::const_iterator i = pm.begin(); i != pm.end(); ++i) { - os << " " << i->first << " " + for (auto const& i : pm) { + os << " " << i.first << " " << cmOutputConverter::EscapeForCMake( - ge.Parse(i->second.GetValue())->Evaluate(this->LG, config)); + ge.Parse(i.second.GetValue())->Evaluate(this->LG, config)); } os << ")" << std::endl; } @@ -154,15 +153,14 @@ void cmTestGenerator::GenerateOldStyle(std::ostream& fout, Indent indent) // Just double-quote all arguments so they are re-parsed // correctly by the test system. fout << " \""; - for (std::string::const_iterator c = argit->begin(); c != argit->end(); - ++c) { + for (char c : *argit) { // Escape quotes within arguments. We should escape // backslashes too but we cannot because it makes the result // inconsistent with previous behavior of this command. - if ((*c == '"')) { + if (c == '"') { fout << '\\'; } - fout << *c; + fout << c; } fout << "\""; } @@ -173,9 +171,9 @@ void cmTestGenerator::GenerateOldStyle(std::ostream& fout, Indent indent) if (!pm.empty()) { fout << indent << "set_tests_properties(" << this->Test->GetName() << " PROPERTIES "; - for (cmPropertyMap::const_iterator i = pm.begin(); i != pm.end(); ++i) { - fout << " " << i->first << " " - << cmOutputConverter::EscapeForCMake(i->second.GetValue()); + for (auto const& i : pm) { + fout << " " << i.first << " " + << cmOutputConverter::EscapeForCMake(i.second.GetValue()); } fout << ")" << std::endl; } diff --git a/Source/cmTestGenerator.h b/Source/cmTestGenerator.h index ab0f635..1ca61c2 100644 --- a/Source/cmTestGenerator.h +++ b/Source/cmTestGenerator.h @@ -26,17 +26,17 @@ public: cmTestGenerator(cmTest* test, std::vector<std::string> const& configurations = std::vector<std::string>()); - ~cmTestGenerator() CM_OVERRIDE; + ~cmTestGenerator() override; void Compute(cmLocalGenerator* lg); protected: - void GenerateScriptConfigs(std::ostream& os, Indent indent) CM_OVERRIDE; - void GenerateScriptActions(std::ostream& os, Indent indent) CM_OVERRIDE; + void GenerateScriptConfigs(std::ostream& os, Indent indent) override; + void GenerateScriptActions(std::ostream& os, Indent indent) override; void GenerateScriptForConfig(std::ostream& os, const std::string& config, - Indent indent) CM_OVERRIDE; - void GenerateScriptNoConfig(std::ostream& os, Indent indent) CM_OVERRIDE; - bool NeedsScriptNoConfig() const CM_OVERRIDE; + Indent indent) override; + void GenerateScriptNoConfig(std::ostream& os, Indent indent) override; + bool NeedsScriptNoConfig() const override; void GenerateOldStyle(std::ostream& os, Indent indent); cmLocalGenerator* LG; diff --git a/Source/cmTimestamp.cxx b/Source/cmTimestamp.cxx index 4dea24c..9fb79d9 100644 --- a/Source/cmTimestamp.cxx +++ b/Source/cmTimestamp.cxx @@ -123,7 +123,9 @@ std::string cmTimestamp::AddTimestampComponent(char flag, switch (flag) { case 'a': + case 'A': case 'b': + case 'B': case 'd': case 'H': case 'I': diff --git a/Source/cmTryCompileCommand.h b/Source/cmTryCompileCommand.h index b1f0da9..fbe0d78 100644 --- a/Source/cmTryCompileCommand.h +++ b/Source/cmTryCompileCommand.h @@ -24,14 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmTryCompileCommand; } + cmCommand* Clone() override { return new cmTryCompileCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmTryRunCommand.cxx b/Source/cmTryRunCommand.cxx index cc93b03..dcaa493 100644 --- a/Source/cmTryRunCommand.cxx +++ b/Source/cmTryRunCommand.cxx @@ -33,11 +33,11 @@ bool cmTryRunCommand::InitialPass(std::vector<std::string> const& argv, // build an arg list for TryCompile and extract the runArgs, std::vector<std::string> tryCompile; - this->CompileResultVariable = ""; - this->RunResultVariable = ""; - this->OutputVariable = ""; - this->RunOutputVariable = ""; - this->CompileOutputVariable = ""; + this->CompileResultVariable.clear(); + this->RunResultVariable.clear(); + this->OutputVariable.clear(); + this->RunOutputVariable.clear(); + this->CompileOutputVariable.clear(); std::string runArgs; unsigned int i; diff --git a/Source/cmTryRunCommand.h b/Source/cmTryRunCommand.h index 732dff1..b632ef5 100644 --- a/Source/cmTryRunCommand.h +++ b/Source/cmTryRunCommand.h @@ -24,14 +24,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmTryRunCommand; } + cmCommand* Clone() override { return new cmTryRunCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: void RunExecutable(const std::string& runArgs, diff --git a/Source/cmUnexpectedCommand.h b/Source/cmUnexpectedCommand.h index 5e3ac74..7154881 100644 --- a/Source/cmUnexpectedCommand.h +++ b/Source/cmUnexpectedCommand.h @@ -21,13 +21,13 @@ public: { } - cmCommand* Clone() CM_OVERRIDE + cmCommand* Clone() override { return new cmUnexpectedCommand(this->Name, this->Error); } bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; private: std::string Name; diff --git a/Source/cmUnsetCommand.h b/Source/cmUnsetCommand.h index 96d7010..4e1208a 100644 --- a/Source/cmUnsetCommand.h +++ b/Source/cmUnsetCommand.h @@ -23,14 +23,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmUnsetCommand; } + cmCommand* Clone() override { return new cmUnsetCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmUseMangledMesaCommand.cxx b/Source/cmUseMangledMesaCommand.cxx index 07095b1..c04a683 100644 --- a/Source/cmUseMangledMesaCommand.cxx +++ b/Source/cmUseMangledMesaCommand.cxx @@ -38,11 +38,10 @@ bool cmUseMangledMesaCommand::InitialPass(std::vector<std::string> const& args, return false; } cmSystemTools::MakeDirectory(destDir); - for (std::vector<std::string>::iterator i = files.begin(); i != files.end(); - ++i) { + for (std::string const& f : files) { std::string path = inputDir; path += "/"; - path += *i; + path += f; this->CopyAndFullPathMesaHeader(path.c_str(), destDir); } diff --git a/Source/cmUseMangledMesaCommand.h b/Source/cmUseMangledMesaCommand.h index 86ebbf1..78f8616 100644 --- a/Source/cmUseMangledMesaCommand.h +++ b/Source/cmUseMangledMesaCommand.h @@ -15,9 +15,9 @@ class cmExecutionStatus; class cmUseMangledMesaCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE { return new cmUseMangledMesaCommand; } + cmCommand* Clone() override { return new cmUseMangledMesaCommand; } bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; protected: void CopyAndFullPathMesaHeader(const char* source, const char* outdir); diff --git a/Source/cmUtilitySourceCommand.h b/Source/cmUtilitySourceCommand.h index 404ef3e..165ecef 100644 --- a/Source/cmUtilitySourceCommand.h +++ b/Source/cmUtilitySourceCommand.h @@ -15,9 +15,9 @@ class cmExecutionStatus; class cmUtilitySourceCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE { return new cmUtilitySourceCommand; } + cmCommand* Clone() override { return new cmUtilitySourceCommand; } bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmVS10LinkFlagTable.h b/Source/cmVS10LinkFlagTable.h index c30ea9a..6a0313a 100644 --- a/Source/cmVS10LinkFlagTable.h +++ b/Source/cmVS10LinkFlagTable.h @@ -29,6 +29,8 @@ static cmVS7FlagTable cmVS10LinkFlagTable[] = { { "CreateHotPatchableImage", "FUNCTIONPADMIN:16", "Itanium Image Only", "ItaniumImage", 0 }, + // correct flags for uac should be /MANIFESTUAC, but some projects already + // use this bug to access uac field, so keep these for compatibility { "UACExecutionLevel", "level='asInvoker'", "asInvoker", "AsInvoker", 0 }, { "UACExecutionLevel", "level='highestAvailable'", "highestAvailable", "HighestAvailable", 0 }, @@ -123,8 +125,12 @@ static cmVS7FlagTable cmVS10LinkFlagTable[] = { { "GenerateManifest", "MANIFEST:NO", "", "false", 0 }, { "GenerateManifest", "MANIFEST", "", "true", 0 }, { "AllowIsolation", "ALLOWISOLATION:NO", "", "false", 0 }, + + // correct flags for uac should be /MANIFESTUAC, but some projects already + // use this bug to access uac field, so keep these for compatibility { "UACUIAccess", "uiAccess='false'", "", "false", 0 }, { "UACUIAccess", "uiAccess='true'", "", "true", 0 }, + { "GenerateDebugInformation", "DEBUG", "", "true", cmVS7FlagTable::CaseInsensitive }, { "MapExports", "MAPINFO:EXPORTS", "", "true", 0 }, @@ -162,11 +168,8 @@ static cmVS7FlagTable cmVS10LinkFlagTable[] = { { "LinkDLL", "DLL", "", "true", 0 }, // Bool Properties With Argument - { "EnableUAC", "MANIFESTUAC:NO", "", "false", 0 }, - { "EnableUAC", "MANIFESTUAC:", "", "true", - cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue }, - { "UACUIAccess", "MANIFESTUAC:", "Enable User Account Control (UAC)", "", - cmVS7FlagTable::UserValueRequired }, + { "EnableUAC", "MANIFESTUAC:", "", "", + cmVS7FlagTable::UserValueRequired | cmVS7FlagTable::SpaceAppendable }, { "GenerateMapFile", "MAP", "", "true", cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue }, { "MapFileName", "MAP:", "Generate Map File", "", diff --git a/Source/cmVS11LinkFlagTable.h b/Source/cmVS11LinkFlagTable.h index 1b3a046..24ba8fd 100644 --- a/Source/cmVS11LinkFlagTable.h +++ b/Source/cmVS11LinkFlagTable.h @@ -29,6 +29,8 @@ static cmVS7FlagTable cmVS11LinkFlagTable[] = { { "CreateHotPatchableImage", "FUNCTIONPADMIN:16", "Itanium Image Only", "ItaniumImage", 0 }, + // correct flags for uac should be /MANIFESTUAC, but some projects already + // use this bug to access uac field, so keep these for compatibility { "UACExecutionLevel", "level='asInvoker'", "asInvoker", "AsInvoker", 0 }, { "UACExecutionLevel", "level='highestAvailable'", "highestAvailable", "HighestAvailable", 0 }, @@ -135,8 +137,12 @@ static cmVS7FlagTable cmVS11LinkFlagTable[] = { { "GenerateManifest", "MANIFEST:NO", "", "false", 0 }, { "GenerateManifest", "MANIFEST", "", "true", 0 }, { "AllowIsolation", "ALLOWISOLATION:NO", "", "false", 0 }, + + // correct flags for uac should be /MANIFESTUAC, but some projects already + // use this bug to access uac field, so keep these for compatibility { "UACUIAccess", "uiAccess='false'", "", "false", 0 }, { "UACUIAccess", "uiAccess='true'", "", "true", 0 }, + { "ManifestEmbed", "manifest:embed", "", "true", 0 }, { "GenerateDebugInformation", "DEBUG", "", "true", cmVS7FlagTable::CaseInsensitive }, @@ -179,11 +185,8 @@ static cmVS7FlagTable cmVS11LinkFlagTable[] = { { "LinkDLL", "DLL", "", "true", 0 }, // Bool Properties With Argument - { "EnableUAC", "MANIFESTUAC:NO", "", "false", 0 }, - { "EnableUAC", "MANIFESTUAC:", "", "true", - cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue }, - { "UACUIAccess", "MANIFESTUAC:", "Enable User Account Control (UAC)", "", - cmVS7FlagTable::UserValueRequired }, + { "EnableUAC", "MANIFESTUAC:", "", "", + cmVS7FlagTable::UserValueRequired | cmVS7FlagTable::SpaceAppendable }, { "GenerateMapFile", "MAP", "", "true", cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue }, { "MapFileName", "MAP:", "Generate Map File", "", diff --git a/Source/cmVS12LinkFlagTable.h b/Source/cmVS12LinkFlagTable.h index 168c34c..fc667c3 100644 --- a/Source/cmVS12LinkFlagTable.h +++ b/Source/cmVS12LinkFlagTable.h @@ -29,6 +29,8 @@ static cmVS7FlagTable cmVS12LinkFlagTable[] = { { "CreateHotPatchableImage", "FUNCTIONPADMIN:16", "Itanium Image Only", "ItaniumImage", 0 }, + // correct flags for uac should be /MANIFESTUAC, but some projects already + // use this bug to access uac field, so keep these for compatibility { "UACExecutionLevel", "level='asInvoker'", "asInvoker", "AsInvoker", 0 }, { "UACExecutionLevel", "level='highestAvailable'", "highestAvailable", "HighestAvailable", 0 }, @@ -135,8 +137,12 @@ static cmVS7FlagTable cmVS12LinkFlagTable[] = { { "GenerateManifest", "MANIFEST:NO", "", "false", 0 }, { "GenerateManifest", "MANIFEST", "", "true", 0 }, { "AllowIsolation", "ALLOWISOLATION:NO", "", "false", 0 }, + + // correct flags for uac should be /MANIFESTUAC, but some projects already + // use this bug to access uac field, so keep these for compatibility { "UACUIAccess", "uiAccess='false'", "", "false", 0 }, { "UACUIAccess", "uiAccess='true'", "", "true", 0 }, + { "ManifestEmbed", "manifest:embed", "", "true", 0 }, { "GenerateDebugInformation", "DEBUG", "", "true", cmVS7FlagTable::CaseInsensitive }, @@ -179,11 +185,8 @@ static cmVS7FlagTable cmVS12LinkFlagTable[] = { { "LinkDLL", "DLL", "", "true", 0 }, // Bool Properties With Argument - { "EnableUAC", "MANIFESTUAC:NO", "", "false", 0 }, - { "EnableUAC", "MANIFESTUAC:", "", "true", - cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue }, - { "UACUIAccess", "MANIFESTUAC:", "Enable User Account Control (UAC)", "", - cmVS7FlagTable::UserValueRequired }, + { "EnableUAC", "MANIFESTUAC:", "", "", + cmVS7FlagTable::UserValueRequired | cmVS7FlagTable::SpaceAppendable }, { "GenerateMapFile", "MAP", "", "true", cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue }, { "MapFileName", "MAP:", "Generate Map File", "", diff --git a/Source/cmVS140LinkFlagTable.h b/Source/cmVS140LinkFlagTable.h index b9a4dc3..7c9452a 100644 --- a/Source/cmVS140LinkFlagTable.h +++ b/Source/cmVS140LinkFlagTable.h @@ -29,6 +29,8 @@ static cmVS7FlagTable cmVS140LinkFlagTable[] = { { "CreateHotPatchableImage", "FUNCTIONPADMIN:16", "Itanium Image Only", "ItaniumImage", 0 }, + // correct flags for uac should be /MANIFESTUAC, but some projects already + // use this bug to access uac field, so keep these for compatibility { "UACExecutionLevel", "level='asInvoker'", "asInvoker", "AsInvoker", 0 }, { "UACExecutionLevel", "level='highestAvailable'", "highestAvailable", "HighestAvailable", 0 }, @@ -148,8 +150,12 @@ static cmVS7FlagTable cmVS140LinkFlagTable[] = { { "GenerateManifest", "MANIFEST:NO", "", "false", 0 }, { "GenerateManifest", "MANIFEST", "", "true", 0 }, { "AllowIsolation", "ALLOWISOLATION:NO", "", "false", 0 }, + + // correct flags for uac should be /MANIFESTUAC, but some projects already + // use this bug to access uac field, so keep these for compatibility { "UACUIAccess", "uiAccess='false'", "", "false", 0 }, { "UACUIAccess", "uiAccess='true'", "", "true", 0 }, + { "ManifestEmbed", "manifest:embed", "", "true", 0 }, { "MapExports", "MAPINFO:EXPORTS", "", "true", 0 }, { "AssemblyDebug", "ASSEMBLYDEBUG:DISABLE", "", "false", 0 }, @@ -190,11 +196,8 @@ static cmVS7FlagTable cmVS140LinkFlagTable[] = { { "LinkDLL", "DLL", "", "true", 0 }, // Bool Properties With Argument - { "EnableUAC", "MANIFESTUAC:NO", "", "false", 0 }, - { "EnableUAC", "MANIFESTUAC:", "", "true", - cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue }, - { "UACUIAccess", "MANIFESTUAC:", "Enable User Account Control (UAC)", "", - cmVS7FlagTable::UserValueRequired }, + { "EnableUAC", "MANIFESTUAC:", "", "", + cmVS7FlagTable::UserValueRequired | cmVS7FlagTable::SpaceAppendable }, { "GenerateMapFile", "MAP", "", "true", cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue }, { "MapFileName", "MAP:", "Generate Map File", "", diff --git a/Source/cmVS141CLFlagTable.h b/Source/cmVS141CLFlagTable.h index e8b8f5c..c780d46 100644 --- a/Source/cmVS141CLFlagTable.h +++ b/Source/cmVS141CLFlagTable.h @@ -79,6 +79,7 @@ static cmVS7FlagTable cmVS141CLFlagTable[] = { { "FloatingPointModel", "fp:strict", "Strict", "Strict", 0 }, { "FloatingPointModel", "fp:fast", "Fast", "Fast", 0 }, + { "LanguageStandard", "std:c++17", "ISO C++17 Standard", "stdcpp17", 0 }, { "LanguageStandard", "std:c++14", "ISO C++14 Standard", "stdcpp14", 0 }, { "LanguageStandard", "std:c++latest", "ISO C++ Latest Draft Standard", "stdcpplatest", 0 }, diff --git a/Source/cmVS141LinkFlagTable.h b/Source/cmVS141LinkFlagTable.h index 8f0f1f4..f159f70 100644 --- a/Source/cmVS141LinkFlagTable.h +++ b/Source/cmVS141LinkFlagTable.h @@ -29,6 +29,8 @@ static cmVS7FlagTable cmVS141LinkFlagTable[] = { { "CreateHotPatchableImage", "FUNCTIONPADMIN:16", "Itanium Image Only", "ItaniumImage", 0 }, + // correct flags for uac should be /MANIFESTUAC, but some projects already + // use this bug to access uac field, so keep these for compatibility { "UACExecutionLevel", "level='asInvoker'", "asInvoker", "AsInvoker", 0 }, { "UACExecutionLevel", "level='highestAvailable'", "highestAvailable", "HighestAvailable", 0 }, @@ -87,6 +89,7 @@ static cmVS7FlagTable cmVS141LinkFlagTable[] = { { "TargetMachine", "", "Not Set", "NotSet", 0 }, { "TargetMachine", "MACHINE:ARM", "MachineARM", "MachineARM", 0 }, + { "TargetMachine", "MACHINE:ARM64", "MachineARM64", "MachineARM64", 0 }, { "TargetMachine", "MACHINE:EBC", "MachineEBC", "MachineEBC", 0 }, { "TargetMachine", "MACHINE:IA64", "MachineIA64", "MachineIA64", 0 }, { "TargetMachine", "MACHINE:MIPS", "MachineMIPS", "MachineMIPS", 0 }, @@ -149,8 +152,12 @@ static cmVS7FlagTable cmVS141LinkFlagTable[] = { { "GenerateManifest", "MANIFEST:NO", "", "false", 0 }, { "GenerateManifest", "MANIFEST", "", "true", 0 }, { "AllowIsolation", "ALLOWISOLATION:NO", "", "false", 0 }, + + // correct flags for uac should be /MANIFESTUAC, but some projects already + // use this bug to access uac field, so keep these for compatibility { "UACUIAccess", "uiAccess='false'", "", "false", 0 }, { "UACUIAccess", "uiAccess='true'", "", "true", 0 }, + { "ManifestEmbed", "manifest:embed", "", "true", 0 }, { "MapExports", "MAPINFO:EXPORTS", "", "true", 0 }, { "AssemblyDebug", "ASSEMBLYDEBUG:DISABLE", "", "false", 0 }, @@ -191,11 +198,8 @@ static cmVS7FlagTable cmVS141LinkFlagTable[] = { { "LinkDLL", "DLL", "", "true", 0 }, // Bool Properties With Argument - { "EnableUAC", "MANIFESTUAC:NO", "", "false", 0 }, - { "EnableUAC", "MANIFESTUAC:", "", "true", - cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue }, - { "UACUIAccess", "MANIFESTUAC:", "Enable User Account Control (UAC)", "", - cmVS7FlagTable::UserValueRequired }, + { "EnableUAC", "MANIFESTUAC:", "", "", + cmVS7FlagTable::UserValueRequired | cmVS7FlagTable::SpaceAppendable }, { "GenerateMapFile", "MAP", "", "true", cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue }, { "MapFileName", "MAP:", "Generate Map File", "", diff --git a/Source/cmVS14LibFlagTable.h b/Source/cmVS14LibFlagTable.h index 7fa7138..be4652c 100644 --- a/Source/cmVS14LibFlagTable.h +++ b/Source/cmVS14LibFlagTable.h @@ -11,6 +11,7 @@ static cmVS7FlagTable cmVS14LibFlagTable[] = { 0 }, { "TargetMachine", "MACHINE:ARM", "MachineARM", "MachineARM", 0 }, + { "TargetMachine", "MACHINE:ARM64", "MachineARM64", "MachineARM64", 0 }, { "TargetMachine", "MACHINE:EBC", "MachineEBC", "MachineEBC", 0 }, { "TargetMachine", "MACHINE:IA64", "MachineIA64", "MachineIA64", 0 }, { "TargetMachine", "MACHINE:MIPS", "MachineMIPS", "MachineMIPS", 0 }, diff --git a/Source/cmVSSetupHelper.cxx b/Source/cmVSSetupHelper.cxx index 7168f26..3c50403 100644 --- a/Source/cmVSSetupHelper.cxx +++ b/Source/cmVSSetupHelper.cxx @@ -218,7 +218,7 @@ bool cmVSSetupAPIHelper::GetVSInstanceInfo( bool cmVSSetupAPIHelper::GetVSInstanceInfo(std::string& vsInstallLocation) { - vsInstallLocation = ""; + vsInstallLocation.clear(); bool isInstalled = this->EnumerateAndChooseVSInstance(); if (isInstalled) { diff --git a/Source/cmVariableRequiresCommand.h b/Source/cmVariableRequiresCommand.h index 811e02e..94970c5 100644 --- a/Source/cmVariableRequiresCommand.h +++ b/Source/cmVariableRequiresCommand.h @@ -15,9 +15,9 @@ class cmExecutionStatus; class cmVariableRequiresCommand : public cmCommand { public: - cmCommand* Clone() CM_OVERRIDE { return new cmVariableRequiresCommand; } + cmCommand* Clone() override { return new cmVariableRequiresCommand; } bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmVariableWatch.cxx b/Source/cmVariableWatch.cxx index 419e1a4..bd5d19c 100644 --- a/Source/cmVariableWatch.cxx +++ b/Source/cmVariableWatch.cxx @@ -2,11 +2,9 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmVariableWatch.h" -#include "cmAlgorithms.h" - -#include "cm_auto_ptr.hxx" -#include <algorithm> +#include <memory> #include <utility> +#include <vector> static const char* const cmVariableWatchAccessStrings[] = { "READ_ACCESS", "UNKNOWN_READ_ACCESS", "UNKNOWN_DEFINED_ACCESS", @@ -25,37 +23,27 @@ cmVariableWatch::cmVariableWatch() { } -template <typename C> -void deleteAllSecond(typename C::value_type it) -{ - cmDeleteAll(it.second); -} - cmVariableWatch::~cmVariableWatch() { - std::for_each(this->WatchMap.begin(), this->WatchMap.end(), - deleteAllSecond<cmVariableWatch::StringToVectorOfPairs>); } bool cmVariableWatch::AddWatch(const std::string& variable, WatchMethod method, void* client_data /*=0*/, DeleteData delete_data /*=0*/) { - CM_AUTO_PTR<cmVariableWatch::Pair> p(new cmVariableWatch::Pair); + auto p = std::make_shared<cmVariableWatch::Pair>(); p->Method = method; p->ClientData = client_data; p->DeleteDataCall = delete_data; - cmVariableWatch::VectorOfPairs* vp = &this->WatchMap[variable]; - cmVariableWatch::VectorOfPairs::size_type cc; - for (cc = 0; cc < vp->size(); cc++) { - cmVariableWatch::Pair* pair = (*vp)[cc]; + cmVariableWatch::VectorOfPairs& vp = this->WatchMap[variable]; + for (auto& pair : vp) { if (pair->Method == method && client_data && client_data == pair->ClientData) { // Callback already exists return false; } } - vp->push_back(p.release()); + vp.push_back(std::move(p)); return true; } @@ -72,7 +60,6 @@ void cmVariableWatch::RemoveWatch(const std::string& variable, // If client_data is NULL, we want to disconnect all watches against // the given method; otherwise match ClientData as well. (!client_data || (client_data == (*it)->ClientData))) { - delete *it; vp->erase(it); return; } @@ -86,10 +73,17 @@ bool cmVariableWatch::VariableAccessed(const std::string& variable, cmVariableWatch::StringToVectorOfPairs::const_iterator mit = this->WatchMap.find(variable); if (mit != this->WatchMap.end()) { - const cmVariableWatch::VectorOfPairs* vp = &mit->second; - cmVariableWatch::VectorOfPairs::const_iterator it; - for (it = vp->begin(); it != vp->end(); it++) { - (*it)->Method(variable, access_type, (*it)->ClientData, newValue, mf); + // The strategy here is to copy the list of callbacks, and ignore + // new callbacks that existing ones may add. + std::vector<std::weak_ptr<Pair>> vp(mit->second.begin(), + mit->second.end()); + for (auto& weak_it : vp) { + // In the case where a callback was removed, the weak_ptr will not be + // lockable, and so this ensures we don't attempt to call into freed + // memory + if (auto it = weak_it.lock()) { + it->Method(variable, access_type, it->ClientData, newValue, mf); + } } return true; } diff --git a/Source/cmVariableWatch.h b/Source/cmVariableWatch.h index 05a0a56..27d1b12 100644 --- a/Source/cmVariableWatch.h +++ b/Source/cmVariableWatch.h @@ -6,6 +6,7 @@ #include "cmConfigure.h" // IWYU pragma: keep #include <map> +#include <memory> // IWYU pragma: keep #include <string> #include <vector> @@ -79,7 +80,7 @@ protected: } }; - typedef std::vector<Pair*> VectorOfPairs; + typedef std::vector<std::shared_ptr<Pair>> VectorOfPairs; typedef std::map<std::string, VectorOfPairs> StringToVectorOfPairs; StringToVectorOfPairs WatchMap; diff --git a/Source/cmVariableWatchCommand.cxx b/Source/cmVariableWatchCommand.cxx index 281850e..9930086 100644 --- a/Source/cmVariableWatchCommand.cxx +++ b/Source/cmVariableWatchCommand.cxx @@ -91,11 +91,9 @@ cmVariableWatchCommand::cmVariableWatchCommand() cmVariableWatchCommand::~cmVariableWatchCommand() { - std::set<std::string>::const_iterator it; - for (it = this->WatchedVariables.begin(); it != this->WatchedVariables.end(); - ++it) { + for (std::string const& wv : this->WatchedVariables) { this->Makefile->GetCMakeInstance()->GetVariableWatch()->RemoveWatch( - *it, cmVariableWatchCommandVariableAccessed); + wv, cmVariableWatchCommandVariableAccessed); } } diff --git a/Source/cmVariableWatchCommand.h b/Source/cmVariableWatchCommand.h index 59baa4d..6a8115d 100644 --- a/Source/cmVariableWatchCommand.h +++ b/Source/cmVariableWatchCommand.h @@ -23,24 +23,24 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmVariableWatchCommand; } + cmCommand* Clone() override { return new cmVariableWatchCommand; } //! Default constructor cmVariableWatchCommand(); //! Destructor. - ~cmVariableWatchCommand() CM_OVERRIDE; + ~cmVariableWatchCommand() override; /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; /** This command does not really have a final pass but it needs to stay alive since it owns variable watch callback information. */ - bool HasFinalPass() const CM_OVERRIDE { return true; } + bool HasFinalPass() const override { return true; } protected: std::set<std::string> WatchedVariables; diff --git a/Source/cmVisualStudio10TargetGenerator.cxx b/Source/cmVisualStudio10TargetGenerator.cxx index 0e73806..e163783 100644 --- a/Source/cmVisualStudio10TargetGenerator.cxx +++ b/Source/cmVisualStudio10TargetGenerator.cxx @@ -15,7 +15,7 @@ #include "cmVisualStudioGeneratorOptions.h" #include "windows.h" -#include "cm_auto_ptr.hxx" +#include <memory> // IWYU pragma: keep static std::string cmVS10EscapeXML(std::string arg) { @@ -407,7 +407,7 @@ void cmVisualStudio10TargetGenerator::Generate() continue; std::string globalKey = keyIt->substr(strlen(prefix)); // Skip invalid or separately-handled properties. - if (globalKey == "" || globalKey == "PROJECT_TYPES" || + if (globalKey.empty() || globalKey == "PROJECT_TYPES" || globalKey == "ROOTNAMESPACE" || globalKey == "KEYWORD") { continue; } @@ -614,7 +614,7 @@ void cmVisualStudio10TargetGenerator::WriteDotNetReferences() ++i) { if (i->first.find("VS_DOTNET_REFERENCE_") == 0) { std::string name = i->first.substr(20); - if (name != "") { + if (!name.empty()) { std::string path = i->second.GetValue(); if (!cmsys::SystemTools::FileIsFullPath(path)) { path = std::string(this->GeneratorTarget->Target->GetMakefile() @@ -642,7 +642,7 @@ void cmVisualStudio10TargetGenerator::WriteDotNetReferences() this->WriteDotNetReference(*ri, ""); } } - for (std::vector<std::pair<std::string, std::string> >::const_iterator i = + for (std::vector<std::pair<std::string, std::string>>::const_iterator i = hintReferences.begin(); i != hintReferences.end(); ++i) { this->WriteDotNetReference(i->first, i->second); @@ -1612,7 +1612,7 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf) std::string srcDir = this->Makefile->GetCurrentSourceDirectory(); std::string binDir = this->Makefile->GetCurrentBinaryDirectory(); if (fullFileName.find(binDir) != std::string::npos) { - sourceLink = ""; + sourceLink.clear(); } else if (fullFileName.find(srcDir) != std::string::npos) { sourceLink = fullFileName.substr(srcDir.length() + 1); } else { @@ -1722,7 +1722,8 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf) if (!deployContent.empty()) { cmGeneratorExpression ge; - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(deployContent); + std::unique_ptr<cmCompiledGeneratorExpression> cge = + ge.Parse(deployContent); // Deployment location cannot be set on a configuration basis if (!deployLocation.empty()) { this->WriteString("<Link>", 3); @@ -2089,7 +2090,7 @@ bool cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags( } if (configDependentFlags) { cmGeneratorExpression ge; - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(flags); + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(flags); std::string evaluatedFlags = cge->Evaluate(this->LocalGenerator, *config); clOptions.Parse(evaluatedFlags.c_str()); @@ -2297,16 +2298,16 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions( cmGlobalVisualStudio10Generator* gg = static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); - CM_AUTO_PTR<Options> pOptions; + std::unique_ptr<Options> pOptions; switch (this->ProjectType) { case vcxproj: - pOptions = CM_AUTO_PTR<Options>(new Options( - this->LocalGenerator, Options::Compiler, gg->GetClFlagTable())); + pOptions = cm::make_unique<Options>( + this->LocalGenerator, Options::Compiler, gg->GetClFlagTable()); break; case csproj: - pOptions = CM_AUTO_PTR<Options>(new Options(this->LocalGenerator, - Options::CSharpCompiler, - gg->GetCSharpFlagTable())); + pOptions = + cm::make_unique<Options>(this->LocalGenerator, Options::CSharpCompiler, + gg->GetCSharpFlagTable()); break; } Options& clOptions = *pOptions; @@ -2471,8 +2472,7 @@ void cmVisualStudio10TargetGenerator::WriteClOptions( } if (this->MSTools) { - cmsys::RegularExpression clangToolset( - "(v[0-9]+_clang_.*|LLVM-vs[0-9]+.*)"); + cmsys::RegularExpression clangToolset("v[0-9]+_clang_.*"); const char* toolset = this->GlobalGenerator->GetPlatformToolset(); if (toolset && clangToolset.find(toolset)) { this->WriteString("<ObjectFileName>" @@ -2521,8 +2521,8 @@ bool cmVisualStudio10TargetGenerator::ComputeRcOptions( { cmGlobalVisualStudio10Generator* gg = static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); - CM_AUTO_PTR<Options> pOptions(new Options( - this->LocalGenerator, Options::ResourceCompiler, gg->GetRcFlagTable())); + auto pOptions = cm::make_unique<Options>( + this->LocalGenerator, Options::ResourceCompiler, gg->GetRcFlagTable()); Options& rcOptions = *pOptions; std::string CONFIG = cmSystemTools::UpperCase(configName); @@ -2582,8 +2582,8 @@ bool cmVisualStudio10TargetGenerator::ComputeCudaOptions( { cmGlobalVisualStudio10Generator* gg = static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); - CM_AUTO_PTR<Options> pOptions(new Options( - this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable())); + auto pOptions = cm::make_unique<Options>( + this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable()); Options& cudaOptions = *pOptions; // Get compile flags for CUDA in this directory. @@ -2690,8 +2690,8 @@ bool cmVisualStudio10TargetGenerator::ComputeCudaLinkOptions( { cmGlobalVisualStudio10Generator* gg = static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); - CM_AUTO_PTR<Options> pOptions(new Options( - this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable())); + auto pOptions = cm::make_unique<Options>( + this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable()); Options& cudaLinkOptions = *pOptions; // Determine if we need to do a device link @@ -2761,8 +2761,8 @@ bool cmVisualStudio10TargetGenerator::ComputeMasmOptions( { cmGlobalVisualStudio10Generator* gg = static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); - CM_AUTO_PTR<Options> pOptions(new Options( - this->LocalGenerator, Options::MasmCompiler, gg->GetMasmFlagTable())); + auto pOptions = cm::make_unique<Options>( + this->LocalGenerator, Options::MasmCompiler, gg->GetMasmFlagTable()); Options& masmOptions = *pOptions; std::string CONFIG = cmSystemTools::UpperCase(configName); @@ -2819,8 +2819,8 @@ bool cmVisualStudio10TargetGenerator::ComputeNasmOptions( { cmGlobalVisualStudio10Generator* gg = static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); - CM_AUTO_PTR<Options> pOptions(new Options( - this->LocalGenerator, Options::NasmCompiler, gg->GetNasmFlagTable())); + auto pOptions = cm::make_unique<Options>( + this->LocalGenerator, Options::NasmCompiler, gg->GetNasmFlagTable()); Options& nasmOptions = *pOptions; std::string CONFIG = cmSystemTools::UpperCase(configName); @@ -2981,7 +2981,7 @@ void cmVisualStudio10TargetGenerator::WriteAntBuildOptions( if (const char* nativeLibDirectoriesExpression = this->GeneratorTarget->GetProperty("ANDROID_NATIVE_LIB_DIRECTORIES")) { cmGeneratorExpression ge; - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(nativeLibDirectoriesExpression); std::string nativeLibDirs = cge->Evaluate(this->LocalGenerator, configName); @@ -2994,7 +2994,7 @@ void cmVisualStudio10TargetGenerator::WriteAntBuildOptions( this->GeneratorTarget->GetProperty( "ANDROID_NATIVE_LIB_DEPENDENCIES")) { cmGeneratorExpression ge; - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(nativeLibDependenciesExpression); std::string nativeLibDeps = cge->Evaluate(this->LocalGenerator, configName); @@ -3013,7 +3013,7 @@ void cmVisualStudio10TargetGenerator::WriteAntBuildOptions( if (const char* jarDirectoriesExpression = this->GeneratorTarget->GetProperty("ANDROID_JAR_DIRECTORIES")) { cmGeneratorExpression ge; - CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(jarDirectoriesExpression); std::string jarDirectories = cge->Evaluate(this->LocalGenerator, configName); @@ -3075,8 +3075,9 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions( { cmGlobalVisualStudio10Generator* gg = static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); - CM_AUTO_PTR<Options> pOptions(new Options( - this->LocalGenerator, Options::Linker, gg->GetLinkFlagTable(), 0, this)); + auto pOptions = + cm::make_unique<Options>(this->LocalGenerator, Options::Linker, + gg->GetLinkFlagTable(), nullptr, this); Options& linkOptions = *pOptions; cmGeneratorTarget::LinkClosure const* linkClosure = @@ -3261,6 +3262,7 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions( } linkOptions.Parse(flags.c_str()); + linkOptions.FixManifestUACFlags(); if (this->MSTools) { cmGeneratorTarget::ModuleDefinitionInfo const* mdi = @@ -3536,11 +3538,13 @@ void cmVisualStudio10TargetGenerator::WriteEvent( for (std::vector<cmCustomCommand>::const_iterator i = commands.begin(); i != commands.end(); ++i) { cmCustomCommandGenerator ccg(*i, configName, this->LocalGenerator); - comment += pre; - comment += lg->ConstructComment(ccg); - script += pre; - pre = "\n"; - script += cmVS10EscapeXML(lg->ConstructScript(ccg)); + if (!ccg.HasOnlyEmptyCommandLines()) { + comment += pre; + comment += lg->ConstructComment(ccg); + script += pre; + pre = "\n"; + script += cmVS10EscapeXML(lg->ConstructScript(ccg)); + } } comment = cmVS10EscapeComment(comment); if (this->ProjectType != csproj) { @@ -3607,6 +3611,13 @@ void cmVisualStudio10TargetGenerator::WriteProjectReferences() this->WriteString("<Name>", 3); (*this->BuildFileStream) << name << "</Name>\n"; this->WriteDotNetReferenceCustomTags(name); + if (csproj == this->ProjectType) { + if (!static_cast<cmGlobalVisualStudioGenerator*>(this->GlobalGenerator) + ->TargetCanBeReferenced(dt)) { + this->WriteString( + "<ReferenceOutputAssembly>false</ReferenceOutputAssembly>\n", 3); + } + } this->WriteString("</ProjectReference>\n", 2); } this->WriteString("</ItemGroup>\n", 1); @@ -3884,6 +3895,10 @@ void cmVisualStudio10TargetGenerator::WriteApplicationTypeSettings() this->WriteString("<AppContainerApplication>true" "</AppContainerApplication>\n", 2); + } else if (this->Platform == "ARM64") { + this->WriteString("<WindowsSDKDesktopARM64Support>true" + "</WindowsSDKDesktopARM64Support>\n", + 2); } else if (this->Platform == "ARM") { this->WriteString("<WindowsSDKDesktopARMSupport>true" "</WindowsSDKDesktopARMSupport>\n", diff --git a/Source/cmVisualStudioGeneratorOptions.cxx b/Source/cmVisualStudioGeneratorOptions.cxx index 51944fa..b1686be 100644 --- a/Source/cmVisualStudioGeneratorOptions.cxx +++ b/Source/cmVisualStudioGeneratorOptions.cxx @@ -256,6 +256,74 @@ void cmVisualStudioGeneratorOptions::FixCudaCodeGeneration() } } +void cmVisualStudioGeneratorOptions::FixManifestUACFlags() +{ + static const char* ENABLE_UAC = "EnableUAC"; + if (!HasFlag(ENABLE_UAC)) { + return; + } + + const std::string uacFlag = GetFlag(ENABLE_UAC); + std::vector<std::string> subOptions; + cmsys::SystemTools::Split(uacFlag, subOptions, ' '); + if (subOptions.empty()) { + AddFlag(ENABLE_UAC, "true"); + return; + } + + if (subOptions.size() == 1 && subOptions[0] == "NO") { + AddFlag(ENABLE_UAC, "false"); + return; + } + + std::map<std::string, std::string> uacMap; + uacMap["level"] = "UACExecutionLevel"; + uacMap["uiAccess"] = "UACUIAccess"; + + std::map<std::string, std::string> uacExecuteLevelMap; + uacExecuteLevelMap["asInvoker"] = "AsInvoker"; + uacExecuteLevelMap["highestAvailable"] = "HighestAvailable"; + uacExecuteLevelMap["requireAdministrator"] = "RequireAdministrator"; + + for (auto const& subopt : subOptions) { + std::vector<std::string> keyValue; + cmsys::SystemTools::Split(subopt, keyValue, '='); + if (keyValue.size() != 2 || (uacMap.find(keyValue[0]) == uacMap.end())) { + // ignore none key=value option or unknown flags + continue; + } + + if (keyValue[1].front() == '\'' && keyValue[1].back() == '\'') { + keyValue[1] = + keyValue[1].substr(1, std::max<int>(0, keyValue[1].size() - 2)); + } + + if (keyValue[0] == "level") { + if (uacExecuteLevelMap.find(keyValue[1]) == uacExecuteLevelMap.end()) { + // unknown level value + continue; + } + + AddFlag(uacMap[keyValue[0]].c_str(), + uacExecuteLevelMap[keyValue[1]].c_str()); + continue; + } + + if (keyValue[0] == "uiAccess") { + if (keyValue[1] != "true" && keyValue[1] != "false") { + // unknown uiAccess value + continue; + } + AddFlag(uacMap[keyValue[0]].c_str(), keyValue[1].c_str()); + continue; + } + + // unknwon sub option + } + + AddFlag(ENABLE_UAC, "true"); +} + void cmVisualStudioGeneratorOptions::Parse(const char* flags) { // Parse the input string as a windows command line since the string diff --git a/Source/cmVisualStudioGeneratorOptions.h b/Source/cmVisualStudioGeneratorOptions.h index 8d7942b..7c08a2c 100644 --- a/Source/cmVisualStudioGeneratorOptions.h +++ b/Source/cmVisualStudioGeneratorOptions.h @@ -77,6 +77,8 @@ public: void FixCudaCodeGeneration(); + void FixManifestUACFlags(); + bool IsDebug() const; bool IsWinRt() const; bool IsManaged() const; diff --git a/Source/cmVisualStudioSlnParser.cxx b/Source/cmVisualStudioSlnParser.cxx index 1a32aba..a9acb3f 100644 --- a/Source/cmVisualStudioSlnParser.cxx +++ b/Source/cmVisualStudioSlnParser.cxx @@ -329,7 +329,7 @@ bool cmVisualStudioSlnParser::State::Process( case FileStateIgnore: if (line.GetTag() == this->EndIgnoreTag) { this->Stack.pop(); - this->EndIgnoreTag = ""; + this->EndIgnoreTag.clear(); } break; default: diff --git a/Source/cmVisualStudioWCEPlatformParser.cxx b/Source/cmVisualStudioWCEPlatformParser.cxx index fc64d0f..3b113aa 100644 --- a/Source/cmVisualStudioWCEPlatformParser.cxx +++ b/Source/cmVisualStudioWCEPlatformParser.cxx @@ -56,12 +56,12 @@ void cmVisualStudioWCEPlatformParser::StartElement(const std::string& name, return; } - this->CharacterData = ""; + this->CharacterData.clear(); if (name == "PlatformData") { - this->PlatformName = ""; - this->OSMajorVersion = ""; - this->OSMinorVersion = ""; + this->PlatformName.clear(); + this->OSMajorVersion.clear(); + this->OSMinorVersion.clear(); this->Macros.clear(); } diff --git a/Source/cmWhileCommand.cxx b/Source/cmWhileCommand.cxx index 24d7bf1..a080034 100644 --- a/Source/cmWhileCommand.cxx +++ b/Source/cmWhileCommand.cxx @@ -7,9 +7,10 @@ #include "cmExpandedCommandArgument.h" #include "cmMakefile.h" #include "cmSystemTools.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" +#include <memory> // IWYU pragma: keep + cmWhileFunctionBlocker::cmWhileFunctionBlocker(cmMakefile* mf) : Makefile(mf) , Depth(0) @@ -34,7 +35,8 @@ bool cmWhileFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff, // if this is the endwhile for this while loop then execute if (!this->Depth) { // Remove the function blocker for this scope or bail. - CM_AUTO_PTR<cmFunctionBlocker> fb(mf.RemoveFunctionBlocker(this, lff)); + std::unique_ptr<cmFunctionBlocker> fb( + mf.RemoveFunctionBlocker(this, lff)); if (!fb.get()) { return false; } @@ -60,11 +62,10 @@ bool cmWhileFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff, while (isTrue) { if (!errorString.empty()) { std::string err = "had incorrect arguments: "; - unsigned int i; - for (i = 0; i < this->Args.size(); ++i) { - err += (this->Args[i].Delim ? "\"" : ""); - err += this->Args[i].Value; - err += (this->Args[i].Delim ? "\"" : ""); + for (cmListFileArgument const& arg : this->Args) { + err += (arg.Delim ? "\"" : ""); + err += arg.Value; + err += (arg.Delim ? "\"" : ""); err += " "; } err += "("; @@ -78,9 +79,9 @@ bool cmWhileFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff, } // Invoke all the functions that were collected in the block. - for (unsigned int c = 0; c < this->Functions.size(); ++c) { + for (cmListFileFunction const& fn : this->Functions) { cmExecutionStatus status; - mf.ExecuteCommand(this->Functions[c], status); + mf.ExecuteCommand(fn, status); if (status.GetReturnInvoked()) { inStatus.SetReturnInvoked(); return true; diff --git a/Source/cmWhileCommand.h b/Source/cmWhileCommand.h index dfd5afc..6f6d405 100644 --- a/Source/cmWhileCommand.h +++ b/Source/cmWhileCommand.h @@ -19,10 +19,10 @@ class cmWhileFunctionBlocker : public cmFunctionBlocker { public: cmWhileFunctionBlocker(cmMakefile* mf); - ~cmWhileFunctionBlocker() CM_OVERRIDE; + ~cmWhileFunctionBlocker() override; bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf, - cmExecutionStatus&) CM_OVERRIDE; - bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf) CM_OVERRIDE; + cmExecutionStatus&) override; + bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf) override; std::vector<cmListFileArgument> Args; std::vector<cmListFileFunction> Functions; @@ -39,21 +39,21 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmWhileCommand; } + cmCommand* Clone() override { return new cmWhileCommand; } /** * This overrides the default InvokeInitialPass implementation. * It records the arguments before expansion. */ bool InvokeInitialPass(const std::vector<cmListFileArgument>& args, - cmExecutionStatus&) CM_OVERRIDE; + cmExecutionStatus&) override; /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const&, - cmExecutionStatus&) CM_OVERRIDE + cmExecutionStatus&) override { return false; } diff --git a/Source/cmWriteFileCommand.h b/Source/cmWriteFileCommand.h index 36a08a4..9028f84 100644 --- a/Source/cmWriteFileCommand.h +++ b/Source/cmWriteFileCommand.h @@ -22,14 +22,14 @@ public: /** * This is a virtual constructor for the command. */ - cmCommand* Clone() CM_OVERRIDE { return new cmWriteFileCommand; } + cmCommand* Clone() override { return new cmWriteFileCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) CM_OVERRIDE; + cmExecutionStatus& status) override; }; #endif diff --git a/Source/cmXCodeObject.cxx b/Source/cmXCodeObject.cxx index 0def8c3..957adb4 100644 --- a/Source/cmXCodeObject.cxx +++ b/Source/cmXCodeObject.cxx @@ -42,8 +42,8 @@ cmXCodeObject::~cmXCodeObject() cmXCodeObject::cmXCodeObject(PBXType ptype, Type type) { this->Version = 15; - this->Target = 0; - this->Object = 0; + this->Target = nullptr; + this->Object = nullptr; this->IsA = ptype; @@ -71,7 +71,7 @@ cmXCodeObject::cmXCodeObject(PBXType ptype, Type type) this->TypeValue = type; if (this->TypeValue == OBJECT) { - this->AddAttribute("isa", 0); + this->AddAttribute("isa", nullptr); } } @@ -86,7 +86,7 @@ bool cmXCodeObject::IsEmpty() const return this->ObjectAttributes.empty(); case OBJECT_REF: case OBJECT: - return this->Object == 0; + return this->Object == nullptr; } return true; // unreachable, but quiets warnings } diff --git a/Source/cmXCodeObject.h b/Source/cmXCodeObject.h index b92e6e3..b51aac7 100644 --- a/Source/cmXCodeObject.h +++ b/Source/cmXCodeObject.h @@ -114,7 +114,7 @@ public: if (i != this->ObjectAttributes.end()) { return i->second; } - return 0; + return nullptr; } // search the attribute list for an object of the specified type cmXCodeObject* GetObject(cmXCodeObject::PBXType t) const @@ -126,7 +126,7 @@ public: return o; } } - return 0; + return nullptr; } void CopyAttributes(cmXCodeObject*); diff --git a/Source/cmXMLWriter.h b/Source/cmXMLWriter.h index 9d89fec..981255d 100644 --- a/Source/cmXMLWriter.h +++ b/Source/cmXMLWriter.h @@ -107,7 +107,7 @@ private: private: std::ostream& Output; - std::stack<std::string, std::vector<std::string> > Elements; + std::stack<std::string, std::vector<std::string>> Elements; std::string IndentationElement; std::size_t Level; bool ElementOpen; diff --git a/Source/cm_auto_ptr.hxx b/Source/cm_auto_ptr.hxx deleted file mode 100644 index 1ac9220..0000000 --- a/Source/cm_auto_ptr.hxx +++ /dev/null @@ -1,220 +0,0 @@ -/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying - file Copyright.txt or https://cmake.org/licensing for details. */ -#ifndef CM_AUTO_PTR_HXX -#define CM_AUTO_PTR_HXX - -#include "cmConfigure.h" - -#ifdef CMake_HAVE_CXX_AUTO_PTR - -#include <memory> -#define CM_AUTO_PTR std::auto_ptr - -#else - -#define CM_AUTO_PTR cm::auto_ptr - -// The HP compiler cannot handle the conversions necessary to use -// auto_ptr_ref to pass an auto_ptr returned from one function -// directly to another function as in use_auto_ptr(get_auto_ptr()). -// We instead use const_cast to achieve the syntax on those platforms. -// We do not use const_cast on other platforms to maintain the C++ -// standard design and guarantee that if an auto_ptr is bound -// to a reference-to-const then ownership will be maintained. -#if defined(__HP_aCC) -#define cm_AUTO_PTR_REF 0 -#define cm_AUTO_PTR_CONST const -#define cm_AUTO_PTR_CAST(a) cast(a) -#else -#define cm_AUTO_PTR_REF 1 -#define cm_AUTO_PTR_CONST -#define cm_AUTO_PTR_CAST(a) a -#endif - -// In C++11, clang will warn about using dynamic exception specifications -// as they are deprecated. But as this class is trying to faithfully -// mimic std::auto_ptr, we want to keep the 'throw()' decorations below. -// So we suppress the warning. -#if defined(__clang__) && defined(__has_warning) -#if __has_warning("-Wdeprecated") -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated" -#endif -#endif - -namespace cm { - -template <class X> -class auto_ptr; - -#if cm_AUTO_PTR_REF -namespace detail { -// The auto_ptr_ref template is supposed to be a private member of -// auto_ptr but Borland 5.8 cannot handle it. Instead put it in -// a private namespace. -template <class Y> -struct auto_ptr_ref -{ - Y* p_; - - // The extra constructor argument prevents implicit conversion to - // auto_ptr_ref from auto_ptr through the constructor. Normally - // this should be done with the explicit keyword but Borland 5.x - // generates code in the conversion operator to call itself - // infinately. - auto_ptr_ref(Y* p, int) - : p_(p) - { - } -}; -} -#endif - -/** C++98 Standard Section 20.4.5 - Template class auto_ptr. */ -template <class X> -class auto_ptr -{ -#if !cm_AUTO_PTR_REF - template <typename Y> - static inline auto_ptr<Y>& cast(auto_ptr<Y> const& a) - { - return const_cast<auto_ptr<Y>&>(a); - } -#endif - - /** The pointer to the object held. */ - X* x_; - -public: - /** The type of object held by the auto_ptr. */ - typedef X element_type; - - /** Construct from an auto_ptr holding a compatible object. This - transfers ownership to the newly constructed auto_ptr. */ - template <class Y> - auto_ptr(auto_ptr<Y> cm_AUTO_PTR_CONST& a) throw() - : x_(cm_AUTO_PTR_CAST(a).release()) - { - } - - /** Assign from an auto_ptr holding a compatible object. This - transfers ownership to the left-hand-side of the assignment. */ - template <class Y> - auto_ptr& operator=(auto_ptr<Y> cm_AUTO_PTR_CONST& a) throw() // NOLINT - { - this->reset(cm_AUTO_PTR_CAST(a).release()); - return *this; // NOLINT - } - - /** - * Explicitly construct from a raw pointer. This is typically - * called with the result of operator new. For example: - * - * auto_ptr<X> ptr(new X()); - */ - explicit auto_ptr(X* p = nullptr) throw() - : x_(p) - { - } - - /** Construct from another auto_ptr holding an object of the same - type. This transfers ownership to the newly constructed - auto_ptr. */ - auto_ptr(auto_ptr cm_AUTO_PTR_CONST& a) throw() - : x_(cm_AUTO_PTR_CAST(a).release()) - { - } - - /** Assign from another auto_ptr holding an object of the same type. - This transfers ownership to the newly constructed auto_ptr. */ - auto_ptr& operator=(auto_ptr cm_AUTO_PTR_CONST& a) throw() // NOLINT - { - this->reset(cm_AUTO_PTR_CAST(a).release()); - return *this; // NOLINT - } - - /** Destruct and delete the object held. */ - ~auto_ptr() throw() - { - // Assume object destructor is nothrow. - delete this->x_; - } - - /** Dereference and return a reference to the object held. */ - X& operator*() const throw() { return *this->x_; } - - /** Return a pointer to the object held. */ - X* operator->() const throw() { return this->x_; } - - /** Return a pointer to the object held. */ - X* get() const throw() { return this->x_; } - - /** Return a pointer to the object held and reset to hold no object. - This transfers ownership to the caller. */ - X* release() throw() - { - X* x = this->x_; - this->x_ = nullptr; - return x; - } - - /** Assume ownership of the given object. The object previously - held is deleted. */ - void reset(X* p = 0) throw() - { - if (this->x_ != p) { - // Assume object destructor is nothrow. - delete this->x_; - this->x_ = p; - } - } - - /** Convert to an auto_ptr holding an object of a compatible type. - This transfers ownership to the returned auto_ptr. */ - template <class Y> - operator auto_ptr<Y>() throw() - { - return auto_ptr<Y>(this->release()); - } - -#if cm_AUTO_PTR_REF - /** Construct from an auto_ptr_ref. This is used when the - constructor argument is a call to a function returning an - auto_ptr. */ - auto_ptr(detail::auto_ptr_ref<X> r) throw() - : x_(r.p_) - { - } - - /** Assign from an auto_ptr_ref. This is used when a function - returning an auto_ptr is passed on the right-hand-side of an - assignment. */ - auto_ptr& operator=(detail::auto_ptr_ref<X> r) throw() - { - this->reset(r.p_); - return *this; // NOLINT - } - - /** Convert to an auto_ptr_ref. This is used when a function - returning an auto_ptr is the argument to the constructor of - another auto_ptr. */ - template <class Y> - operator detail::auto_ptr_ref<Y>() throw() - { - return detail::auto_ptr_ref<Y>(this->release(), 1); - } -#endif -}; - -} // namespace cm - -// Undo warning suppression. -#if defined(__clang__) && defined(__has_warning) -#if __has_warning("-Wdeprecated") -#pragma clang diagnostic pop -#endif -#endif - -#endif - -#endif diff --git a/Source/cm_codecvt.hxx b/Source/cm_codecvt.hxx index 30c6d54..3a5606b 100644 --- a/Source/cm_codecvt.hxx +++ b/Source/cm_codecvt.hxx @@ -3,7 +3,7 @@ #ifndef cm_codecvt_hxx #define cm_codecvt_hxx -#include "cmConfigure.h" +#include "cmConfigure.h" // IWYU pragma: keep #include <locale> #include <wchar.h> @@ -23,15 +23,15 @@ public: codecvt(Encoding e); protected: - ~codecvt() CM_OVERRIDE; - bool do_always_noconv() const throw() CM_OVERRIDE; + ~codecvt() override; + bool do_always_noconv() const throw() override; result do_out(mbstate_t& state, const char* from, const char* from_end, const char*& from_next, char* to, char* to_end, - char*& to_next) const CM_OVERRIDE; + char*& to_next) const override; result do_unshift(mbstate_t& state, char* to, char*, - char*& to_next) const CM_OVERRIDE; - int do_max_length() const throw() CM_OVERRIDE; - int do_encoding() const throw() CM_OVERRIDE; + char*& to_next) const override; + int do_max_length() const throw() override; + int do_encoding() const throw() override; private: // The mbstate_t argument to do_out and do_unshift is responsible diff --git a/Source/cmake.cxx b/Source/cmake.cxx index 425e221..61595d5 100644 --- a/Source/cmake.cxx +++ b/Source/cmake.cxx @@ -24,7 +24,6 @@ #include "cmUtils.hxx" #include "cmVersionConfig.h" #include "cmWorkingDirectory.h" -#include "cm_auto_ptr.hxx" #include "cm_sys_stat.h" #if defined(CMAKE_BUILD_WITH_CMAKE) @@ -111,6 +110,7 @@ #include "cmsys/RegularExpression.hxx" #include <algorithm> #include <iostream> +#include <memory> // IWYU pragma: keep #include <sstream> #include <stdio.h> #include <stdlib.h> @@ -244,31 +244,28 @@ Json::Value cmake::ReportCapabilitiesJson(bool haveServerMode) const this->GetRegisteredGenerators(generatorInfoList); JsonValueMapType generatorMap; - for (std::vector<cmake::GeneratorInfo>::const_iterator i = - generatorInfoList.begin(); - i != generatorInfoList.end(); ++i) { - if (i->isAlias) { // skip aliases, they are there for compatibility reasons + for (cmake::GeneratorInfo const& gi : generatorInfoList) { + if (gi.isAlias) { // skip aliases, they are there for compatibility reasons // only continue; } - if (i->extraName.empty()) { + if (gi.extraName.empty()) { Json::Value gen = Json::objectValue; - gen["name"] = i->name; - gen["toolsetSupport"] = i->supportsToolset; - gen["platformSupport"] = i->supportsPlatform; + gen["name"] = gi.name; + gen["toolsetSupport"] = gi.supportsToolset; + gen["platformSupport"] = gi.supportsPlatform; gen["extraGenerators"] = Json::arrayValue; - generatorMap[i->name] = gen; + generatorMap[gi.name] = gen; } else { - Json::Value& gen = generatorMap[i->baseName]; - gen["extraGenerators"].append(i->extraName); + Json::Value& gen = generatorMap[gi.baseName]; + gen["extraGenerators"].append(gi.extraName); } } Json::Value generators = Json::arrayValue; - for (JsonValueMapType::const_iterator i = generatorMap.begin(); - i != generatorMap.end(); ++i) { - generators.append(i->second); + for (auto const& i : generatorMap) { + generators.append(i.second); } obj["generators"] = generators; obj["serverMode"] = haveServerMode; @@ -407,21 +404,18 @@ bool cmake::SetCacheArgs(const std::vector<std::string>& args) // removed std::vector<std::string> entriesToDelete; std::vector<std::string> cacheKeys = this->State->GetCacheEntryKeys(); - for (std::vector<std::string>::const_iterator it = cacheKeys.begin(); - it != cacheKeys.end(); ++it) { - cmStateEnums::CacheEntryType t = this->State->GetCacheEntryType(*it); + for (std::string const& ck : cacheKeys) { + cmStateEnums::CacheEntryType t = this->State->GetCacheEntryType(ck); if (t != cmStateEnums::STATIC) { - if (regex.find(it->c_str())) { - entriesToDelete.push_back(*it); + if (regex.find(ck.c_str())) { + entriesToDelete.push_back(ck); } } } // now remove them from the cache - for (std::vector<std::string>::const_iterator currentEntry = - entriesToDelete.begin(); - currentEntry != entriesToDelete.end(); ++currentEntry) { - this->State->RemoveCacheEntry(*currentEntry); + for (std::string const& currentEntry : entriesToDelete) { + this->State->RemoveCacheEntry(currentEntry); } } else if (arg.find("-C", 0) == 0) { std::string path = arg.substr(2); @@ -488,15 +482,15 @@ void cmake::ReadListFile(const std::vector<std::string>& args, snapshot.GetDirectory().SetCurrentSource( cmSystemTools::GetCurrentWorkingDirectory()); snapshot.SetDefaultDefinitions(); - CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(gg, snapshot)); + cmMakefile mf(gg, snapshot); if (this->GetWorkingMode() != NORMAL_MODE) { std::string file(cmSystemTools::CollapseFullPath(path)); cmSystemTools::ConvertToUnixSlashes(file); - mf->SetScriptModeFile(file.c_str()); + mf.SetScriptModeFile(file.c_str()); - mf->SetArgcArgv(args); + mf.SetArgcArgv(args); } - if (!mf->ReadListFile(path)) { + if (!mf.ReadListFile(path)) { cmSystemTools::Error("Error processing file: ", path); } this->SetHomeDirectory(homeDir); @@ -568,9 +562,8 @@ bool cmake::FindPackage(const std::vector<std::string>& args) std::string libs = mf->GetSafeDefinition("PACKAGE_LIBRARIES"); std::vector<std::string> libList; cmSystemTools::ExpandListArgument(libs, libList); - for (std::vector<std::string>::const_iterator libIt = libList.begin(); - libIt != libList.end(); ++libIt) { - tgt->AddLinkLibrary(*mf, *libIt, GENERAL_LibraryType); + for (std::string const& lib : libList) { + tgt->AddLinkLibrary(*mf, lib, GENERAL_LibraryType); } std::string buildType = mf->GetSafeDefinition("CMAKE_BUILD_TYPE"); @@ -906,49 +899,42 @@ void cmake::AddDefaultExtraGenerators() void cmake::GetRegisteredGenerators( std::vector<GeneratorInfo>& generators) const { - for (RegisteredGeneratorsVector::const_iterator i = this->Generators.begin(), - e = this->Generators.end(); - i != e; ++i) { + for (cmGlobalGeneratorFactory* gen : this->Generators) { std::vector<std::string> names; - (*i)->GetGenerators(names); + gen->GetGenerators(names); - for (size_t j = 0; j < names.size(); ++j) { + for (std::string const& name : names) { GeneratorInfo info; - info.supportsToolset = (*i)->SupportsToolset(); - info.supportsPlatform = (*i)->SupportsPlatform(); - info.name = names[j]; - info.baseName = names[j]; + info.supportsToolset = gen->SupportsToolset(); + info.supportsPlatform = gen->SupportsPlatform(); + info.name = name; + info.baseName = name; info.isAlias = false; generators.push_back(info); } } - for (RegisteredExtraGeneratorsVector::const_iterator - i = this->ExtraGenerators.begin(), - e = this->ExtraGenerators.end(); - i != e; ++i) { + for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) { const std::vector<std::string> genList = - (*i)->GetSupportedGlobalGenerators(); - for (std::vector<std::string>::const_iterator gen = genList.begin(); - gen != genList.end(); ++gen) { + eg->GetSupportedGlobalGenerators(); + for (std::string const& gen : genList) { GeneratorInfo info; info.name = cmExternalMakefileProjectGenerator::CreateFullGeneratorName( - *gen, (*i)->GetName()); - info.baseName = *gen; - info.extraName = (*i)->GetName(); + gen, eg->GetName()); + info.baseName = gen; + info.extraName = eg->GetName(); info.supportsPlatform = false; info.supportsToolset = false; info.isAlias = false; generators.push_back(info); } - for (std::vector<std::string>::const_iterator a = (*i)->Aliases.begin(); - a != (*i)->Aliases.end(); ++a) { + for (std::string const& a : eg->Aliases) { GeneratorInfo info; - info.name = *a; + info.name = a; if (!genList.empty()) { info.baseName = genList.at(0); } - info.extraName = (*i)->GetName(); + info.extraName = eg->GetName(); info.supportsPlatform = false; info.supportsToolset = false; info.isAlias = true; @@ -962,23 +948,19 @@ createExtraGenerator( const std::vector<cmExternalMakefileProjectGeneratorFactory*>& in, const std::string& name) { - for (std::vector<cmExternalMakefileProjectGeneratorFactory*>::const_iterator - i = in.begin(); - i != in.end(); ++i) { + for (cmExternalMakefileProjectGeneratorFactory* i : in) { const std::vector<std::string> generators = - (*i)->GetSupportedGlobalGenerators(); - if ((*i)->GetName() == name) { // Match aliases - return std::make_pair((*i)->CreateExternalMakefileProjectGenerator(), + i->GetSupportedGlobalGenerators(); + if (i->GetName() == name) { // Match aliases + return std::make_pair(i->CreateExternalMakefileProjectGenerator(), generators.at(0)); } - for (std::vector<std::string>::const_iterator g = generators.begin(); - g != generators.end(); ++g) { + for (std::string const& g : generators) { const std::string fullName = cmExternalMakefileProjectGenerator::CreateFullGeneratorName( - *g, (*i)->GetName()); + g, i->GetName()); if (fullName == name) { - return std::make_pair((*i)->CreateExternalMakefileProjectGenerator(), - *g); + return std::make_pair(i->CreateExternalMakefileProjectGenerator(), g); } } } @@ -994,9 +976,8 @@ cmGlobalGenerator* cmake::CreateGlobalGenerator(const std::string& gname) const std::string name = extra.second; cmGlobalGenerator* generator = nullptr; - for (RegisteredGeneratorsVector::const_iterator i = this->Generators.begin(); - i != this->Generators.end(); ++i) { - generator = (*i)->CreateGlobalGenerator(name, this); + for (cmGlobalGeneratorFactory* g : this->Generators) { + generator = g->CreateGlobalGenerator(name, this); if (generator) { break; } @@ -1091,10 +1072,10 @@ void cmake::SetGlobalGenerator(cmGlobalGenerator* gg) // Save the environment variables CXX and CC if (!cmSystemTools::GetEnv("CXX", this->CXXEnvironment)) { - this->CXXEnvironment = ""; + this->CXXEnvironment.clear(); } if (!cmSystemTools::GetEnv("CC", this->CCEnvironment)) { - this->CCEnvironment = ""; + this->CCEnvironment.clear(); } } @@ -1192,9 +1173,8 @@ int cmake::HandleDeleteCacheVariables(const std::string& var) // load the empty cache this->LoadCache(); // restore the changed compilers - for (std::vector<SaveCacheEntry>::iterator i = saved.begin(); - i != saved.end(); ++i) { - this->AddCacheEntry(i->key, i->value.c_str(), i->help.c_str(), i->type); + for (SaveCacheEntry const& i : saved) { + this->AddCacheEntry(i.key, i.value.c_str(), i.help.c_str(), i.type); } cmSystemTools::Message(warning.str().c_str()); // avoid reconfigure if there were errors @@ -1791,35 +1771,30 @@ void cmake::SetIsInTryCompile(bool b) void cmake::GetGeneratorDocumentation(std::vector<cmDocumentationEntry>& v) { - for (RegisteredGeneratorsVector::const_iterator i = this->Generators.begin(); - i != this->Generators.end(); ++i) { + for (cmGlobalGeneratorFactory* g : this->Generators) { cmDocumentationEntry e; - (*i)->GetDocumentation(e); + g->GetDocumentation(e); v.push_back(e); } - for (RegisteredExtraGeneratorsVector::const_iterator i = - this->ExtraGenerators.begin(); - i != this->ExtraGenerators.end(); ++i) { - const std::string doc = (*i)->GetDocumentation(); - const std::string name = (*i)->GetName(); + for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) { + const std::string doc = eg->GetDocumentation(); + const std::string name = eg->GetName(); // Aliases: - for (std::vector<std::string>::const_iterator a = (*i)->Aliases.begin(); - a != (*i)->Aliases.end(); ++a) { + for (std::string const& a : eg->Aliases) { cmDocumentationEntry e; - e.Name = *a; + e.Name = a; e.Brief = doc; v.push_back(e); } // Full names: const std::vector<std::string> generators = - (*i)->GetSupportedGlobalGenerators(); - for (std::vector<std::string>::const_iterator g = generators.begin(); - g != generators.end(); ++g) { + eg->GetSupportedGlobalGenerators(); + for (std::string const& g : generators) { cmDocumentationEntry e; e.Name = - cmExternalMakefileProjectGenerator::CreateFullGeneratorName(*g, name); + cmExternalMakefileProjectGenerator::CreateFullGeneratorName(g, name); e.Brief = doc; v.push_back(e); } @@ -1899,8 +1874,8 @@ int cmake::CheckBuildSystem() cm.SetHomeOutputDirectory(""); cm.GetCurrentSnapshot().SetDefaultDefinitions(); cmGlobalGenerator gg(&cm); - CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot())); - if (!mf->ReadListFile(this->CheckBuildSystemArgument.c_str()) || + cmMakefile mf(&gg, cm.GetCurrentSnapshot()); + if (!mf.ReadListFile(this->CheckBuildSystemArgument.c_str()) || cmSystemTools::GetErrorOccuredFlag()) { if (verbose) { std::ostringstream msg; @@ -1914,34 +1889,33 @@ int cmake::CheckBuildSystem() if (this->ClearBuildSystem) { // Get the generator used for this build system. - const char* genName = mf->GetDefinition("CMAKE_DEPENDS_GENERATOR"); + const char* genName = mf.GetDefinition("CMAKE_DEPENDS_GENERATOR"); if (!genName || genName[0] == '\0') { genName = "Unix Makefiles"; } // Create the generator and use it to clear the dependencies. - CM_AUTO_PTR<cmGlobalGenerator> ggd(this->CreateGlobalGenerator(genName)); - if (ggd.get()) { + std::unique_ptr<cmGlobalGenerator> ggd( + this->CreateGlobalGenerator(genName)); + if (ggd) { cm.GetCurrentSnapshot().SetDefaultDefinitions(); - CM_AUTO_PTR<cmMakefile> mfd( - new cmMakefile(ggd.get(), cm.GetCurrentSnapshot())); - CM_AUTO_PTR<cmLocalGenerator> lgd(ggd->CreateLocalGenerator(mfd.get())); - lgd->ClearDependencies(mfd.get(), verbose); + cmMakefile mfd(ggd.get(), cm.GetCurrentSnapshot()); + std::unique_ptr<cmLocalGenerator> lgd(ggd->CreateLocalGenerator(&mfd)); + lgd->ClearDependencies(&mfd, verbose); } } // If any byproduct of makefile generation is missing we must re-run. std::vector<std::string> products; - if (const char* productStr = mf->GetDefinition("CMAKE_MAKEFILE_PRODUCTS")) { + if (const char* productStr = mf.GetDefinition("CMAKE_MAKEFILE_PRODUCTS")) { cmSystemTools::ExpandListArgument(productStr, products); } - for (std::vector<std::string>::const_iterator pi = products.begin(); - pi != products.end(); ++pi) { - if (!(cmSystemTools::FileExists(pi->c_str()) || - cmSystemTools::FileIsSymlink(*pi))) { + for (std::string const& p : products) { + if (!(cmSystemTools::FileExists(p.c_str()) || + cmSystemTools::FileIsSymlink(p))) { if (verbose) { std::ostringstream msg; - msg << "Re-run cmake, missing byproduct: " << *pi << "\n"; + msg << "Re-run cmake, missing byproduct: " << p << "\n"; cmSystemTools::Stdout(msg.str().c_str()); } return 1; @@ -1951,8 +1925,8 @@ int cmake::CheckBuildSystem() // Get the set of dependencies and outputs. std::vector<std::string> depends; std::vector<std::string> outputs; - const char* dependsStr = mf->GetDefinition("CMAKE_MAKEFILE_DEPENDS"); - const char* outputsStr = mf->GetDefinition("CMAKE_MAKEFILE_OUTPUTS"); + const char* dependsStr = mf.GetDefinition("CMAKE_MAKEFILE_DEPENDS"); + const char* outputsStr = mf.GetDefinition("CMAKE_MAKEFILE_OUTPUTS"); if (dependsStr && outputsStr) { cmSystemTools::ExpandListArgument(dependsStr, depends); cmSystemTools::ExpandListArgument(outputsStr, outputs); @@ -2065,19 +2039,18 @@ void cmake::MarkCliAsUsed(const std::string& variable) void cmake::GenerateGraphViz(const char* fileName) const { #ifdef CMAKE_BUILD_WITH_CMAKE - CM_AUTO_PTR<cmGraphVizWriter> gvWriter( - new cmGraphVizWriter(this->GetGlobalGenerator()->GetLocalGenerators())); + cmGraphVizWriter gvWriter(this->GetGlobalGenerator()->GetLocalGenerators()); std::string settingsFile = this->GetHomeOutputDirectory(); settingsFile += "/CMakeGraphVizOptions.cmake"; std::string fallbackSettingsFile = this->GetHomeDirectory(); fallbackSettingsFile += "/CMakeGraphVizOptions.cmake"; - gvWriter->ReadSettings(settingsFile.c_str(), fallbackSettingsFile.c_str()); + gvWriter.ReadSettings(settingsFile.c_str(), fallbackSettingsFile.c_str()); - gvWriter->WritePerTargetFiles(fileName); - gvWriter->WriteTargetDependersFiles(fileName); - gvWriter->WriteGlobalFile(fileName); + gvWriter.WritePerTargetFiles(fileName); + gvWriter.WriteTargetDependersFiles(fileName); + gvWriter.WriteGlobalFile(fileName); #endif } @@ -2383,7 +2356,7 @@ int cmake::Build(const std::string& dir, const std::string& target, std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n"; return 1; } - CM_AUTO_PTR<cmGlobalGenerator> gen( + std::unique_ptr<cmGlobalGenerator> gen( this->CreateGlobalGenerator(cachedGenerator)); if (!gen.get()) { std::cerr << "Error: could create CMAKE_GENERATOR \"" << cachedGenerator @@ -2479,12 +2452,10 @@ void cmake::RunCheckForUnusedVariables() bool haveUnused = false; std::ostringstream msg; msg << "Manually-specified variables were not used by the project:"; - for (std::map<std::string, bool>::const_iterator it = - this->UsedCliVariables.begin(); - it != this->UsedCliVariables.end(); ++it) { - if (!it->second) { + for (auto const& it : this->UsedCliVariables) { + if (!it.second) { haveUnused = true; - msg << "\n " << it->first; + msg << "\n " << it.first; } } if (haveUnused) { diff --git a/Source/cmakemain.cxx b/Source/cmakemain.cxx index e6f88a7..a1dfc3e 100644 --- a/Source/cmakemain.cxx +++ b/Source/cmakemain.cxx @@ -14,12 +14,13 @@ #ifdef CMAKE_BUILD_WITH_CMAKE #include "cmDocumentation.h" #include "cmDynamicLoader.h" +#endif + #ifdef _WIN32 #include <fcntl.h> /* _O_TEXT */ #include <stdlib.h> /* _set_fmode, _fmode */ #endif #include "cm_uv.h" -#endif #include "cmsys/Encoding.hxx" #if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE) @@ -102,7 +103,7 @@ static int do_build(int ac, char const* const* av); static cmMakefile* cmakemainGetMakefile(void* clientdata) { - cmake* cm = reinterpret_cast<cmake*>(clientdata); + cmake* cm = static_cast<cmake*>(clientdata); if (cm && cm->GetDebugOutput()) { cmGlobalGenerator* gg = cm->GetGlobalGenerator(); if (gg) { @@ -167,7 +168,7 @@ int main(int ac, char const* const* av) ac = args.argc(); av = args.argv(); -#if defined(CMAKE_BUILD_WITH_CMAKE) && defined(_WIN32) +#if defined(_WIN32) // Perform libuv one-time initialization now, and then un-do its // global _fmode setting so that using libuv does not change the // default file text/binary mode. See libuv issue 840. @@ -192,8 +193,8 @@ int main(int ac, char const* const* av) int ret = do_cmake(ac, av); #ifdef CMAKE_BUILD_WITH_CMAKE cmDynamicLoader::FlushCache(); - uv_loop_close(uv_default_loop()); #endif + uv_loop_close(uv_default_loop()); return ret; } @@ -311,22 +312,20 @@ int do_cmake(int ac, char const* const* av) if (list_cached || list_all_cached) { std::cout << "-- Cache values" << std::endl; std::vector<std::string> keys = cm.GetState()->GetCacheEntryKeys(); - for (std::vector<std::string>::const_iterator it = keys.begin(); - it != keys.end(); ++it) { - cmStateEnums::CacheEntryType t = cm.GetState()->GetCacheEntryType(*it); + for (std::string const& k : keys) { + cmStateEnums::CacheEntryType t = cm.GetState()->GetCacheEntryType(k); if (t != cmStateEnums::INTERNAL && t != cmStateEnums::STATIC && t != cmStateEnums::UNINITIALIZED) { const char* advancedProp = - cm.GetState()->GetCacheEntryProperty(*it, "ADVANCED"); + cm.GetState()->GetCacheEntryProperty(k, "ADVANCED"); if (list_all_cached || !advancedProp) { if (list_help) { std::cout << "// " - << cm.GetState()->GetCacheEntryProperty(*it, - "HELPSTRING") + << cm.GetState()->GetCacheEntryProperty(k, "HELPSTRING") << std::endl; } - std::cout << *it << ":" << cmState::CacheEntryTypeToString(t) << "=" - << cm.GetState()->GetCacheEntryValue(*it) << std::endl; + std::cout << k << ":" << cmState::CacheEntryTypeToString(t) << "=" + << cm.GetState()->GetCacheEntryValue(k) << std::endl; if (list_help) { std::cout << std::endl; } @@ -374,7 +373,7 @@ static int do_build(int ac, char const* const* av) hasTarget = true; } else { std::cerr << "'--target' may not be specified more than once.\n\n"; - dir = ""; + dir.clear(); break; } } else if (strcmp(av[i], "--config") == 0) { @@ -402,7 +401,7 @@ static int do_build(int ac, char const* const* av) break; default: std::cerr << "Unknown argument " << av[i] << std::endl; - dir = ""; + dir.clear(); break; } } diff --git a/Source/cmakexbuild.cxx b/Source/cmakexbuild.cxx index 72da456..20ead47 100644 --- a/Source/cmakexbuild.cxx +++ b/Source/cmakexbuild.cxx @@ -47,7 +47,7 @@ int RunXCode(std::vector<const char*>& argv, bool& hitbug) } pipe = cmSystemTools::WaitForLine(cp, line, 100, out, err); } - cmsysProcess_WaitForExit(cp, 0); + cmsysProcess_WaitForExit(cp, nullptr); if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exited) { return cmsysProcess_GetExitValue(cp); } @@ -64,7 +64,7 @@ int main(int ac, char* av[]) for (int i = 1; i < ac; i++) { argv.push_back(av[i]); } - argv.push_back(0); + argv.push_back(nullptr); bool hitbug = true; int ret = 0; while (hitbug) { diff --git a/Source/cmcmd.cxx b/Source/cmcmd.cxx index 0791cb3..5a9e321 100644 --- a/Source/cmcmd.cxx +++ b/Source/cmcmd.cxx @@ -12,7 +12,6 @@ #include "cmSystemTools.h" #include "cmUtils.hxx" #include "cmVersion.h" -#include "cm_auto_ptr.hxx" #include "cmake.h" #if defined(CMAKE_BUILD_WITH_CMAKE) @@ -34,11 +33,15 @@ #include "cmsys/Process.h" #include "cmsys/Terminal.h" #include <algorithm> +#include <functional> #include <iostream> +#include <map> +#include <memory> // IWYU pragma: keep #include <sstream> #include <stdio.h> #include <stdlib.h> #include <time.h> +#include <utility> class cmConnection; @@ -157,6 +160,277 @@ static bool cmTarFilesFrom(std::string const& file, return true; } +int cmcmd::HandleIWYU(const std::string& runCmd, const std::string&, + const std::vector<std::string>& orig_cmd) +{ + // Construct the iwyu command line by taking what was given + // and adding all the arguments we give to the compiler. + std::vector<std::string> iwyu_cmd; + cmSystemTools::ExpandListArgument(runCmd, iwyu_cmd, true); + iwyu_cmd.insert(iwyu_cmd.end(), orig_cmd.begin() + 1, orig_cmd.end()); + // Run the iwyu command line. Capture its stderr and hide its stdout. + // Ignore its return code because the tool always returns non-zero. + std::string stdErr; + int ret; + if (!cmSystemTools::RunSingleCommand(iwyu_cmd, nullptr, &stdErr, &ret, + nullptr, cmSystemTools::OUTPUT_NONE)) { + std::cerr << "Error running '" << iwyu_cmd[0] << "': " << stdErr << "\n"; + return 1; + } + // Warn if iwyu reported anything. + if (stdErr.find("should remove these lines:") != std::string::npos || + stdErr.find("should add these lines:") != std::string::npos) { + std::cerr << "Warning: include-what-you-use reported diagnostics:\n" + << stdErr << "\n"; + } + // always return 0 we don't want to break the compile + return 0; +} + +int cmcmd::HandleTidy(const std::string& runCmd, const std::string& sourceFile, + const std::vector<std::string>& orig_cmd) +{ + // Construct the clang-tidy command line by taking what was given + // and adding our compiler command line. The clang-tidy tool will + // automatically skip over the compiler itself and extract the + // options. + int ret; + std::vector<std::string> tidy_cmd; + cmSystemTools::ExpandListArgument(runCmd, tidy_cmd, true); + tidy_cmd.push_back(sourceFile); + tidy_cmd.push_back("--"); + tidy_cmd.insert(tidy_cmd.end(), orig_cmd.begin(), orig_cmd.end()); + + // Run the tidy command line. Capture its stdout and hide its stderr. + std::string stdOut; + std::string stdErr; + if (!cmSystemTools::RunSingleCommand(tidy_cmd, &stdOut, &stdErr, &ret, + nullptr, cmSystemTools::OUTPUT_NONE)) { + std::cerr << "Error running '" << tidy_cmd[0] << "': " << stdErr << "\n"; + return 1; + } + // Output the stdout from clang-tidy to stderr + std::cerr << stdOut; + // If clang-tidy exited with an error do the same. + if (ret != 0) { + std::cerr << stdErr; + } + return ret; +} + +int cmcmd::HandleLWYU(const std::string& runCmd, const std::string&, + const std::vector<std::string>&) +{ + // Construct the ldd -r -u (link what you use lwyu) command line + // ldd -u -r lwuy target + std::vector<std::string> lwyu_cmd; + lwyu_cmd.push_back("ldd"); + lwyu_cmd.push_back("-u"); + lwyu_cmd.push_back("-r"); + lwyu_cmd.push_back(runCmd); + + // Run the ldd -u -r command line. + // Capture its stdout and hide its stderr. + // Ignore its return code because the tool always returns non-zero + // if there are any warnings, but we just want to warn. + std::string stdOut; + std::string stdErr; + int ret; + if (!cmSystemTools::RunSingleCommand(lwyu_cmd, &stdOut, &stdErr, &ret, + nullptr, cmSystemTools::OUTPUT_NONE)) { + std::cerr << "Error running '" << lwyu_cmd[0] << "': " << stdErr << "\n"; + return 1; + } + + // Output the stdout from ldd -r -u to stderr + // Warn if lwyu reported anything. + if (stdOut.find("Unused direct dependencies:") != std::string::npos) { + std::cerr << "Warning: " << stdOut; + } + return 0; +} + +int cmcmd::HandleCppLint(const std::string& runCmd, + const std::string& sourceFile, + const std::vector<std::string>&) +{ + // Construct the cpplint command line. + std::vector<std::string> cpplint_cmd; + cmSystemTools::ExpandListArgument(runCmd, cpplint_cmd, true); + cpplint_cmd.push_back(sourceFile); + + // Run the cpplint command line. Capture its output. + std::string stdOut; + int ret; + if (!cmSystemTools::RunSingleCommand(cpplint_cmd, &stdOut, &stdOut, &ret, + nullptr, cmSystemTools::OUTPUT_NONE)) { + std::cerr << "Error running '" << cpplint_cmd[0] << "': " << stdOut + << "\n"; + return 1; + } + + // Output the output from cpplint to stderr + std::cerr << stdOut; + return ret; +} + +int cmcmd::HandleCppCheck(const std::string& runCmd, + const std::string& sourceFile, + const std::vector<std::string>& orig_cmd) +{ + // Construct the cpplint command line. + std::vector<std::string> cppcheck_cmd; + cmSystemTools::ExpandListArgument(runCmd, cppcheck_cmd, true); + // extract all the -D, -U, and -I options from the compile line + for (auto const& opt : orig_cmd) { + if (opt.size() > 2) { + if ((opt[0] == '-') && + ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) { + cppcheck_cmd.push_back(opt); +// convert cl / options to - options if needed +#if defined(_WIN32) + } else if ((opt[0] == '/') && + ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) { + std::string optcopy = opt; + optcopy[0] = '-'; + cppcheck_cmd.push_back(optcopy); +#endif + } + } + } + // add the source file + cppcheck_cmd.push_back(sourceFile); + + // Run the cpplint command line. Capture its output. + std::string stdOut; + std::string stdErr; + int ret; + if (!cmSystemTools::RunSingleCommand(cppcheck_cmd, &stdOut, &stdErr, &ret, + nullptr, cmSystemTools::OUTPUT_NONE)) { + std::cerr << "Error running '" << cppcheck_cmd[0] << "': " << stdOut + << "\n"; + return 1; + } + std::cerr << stdOut; + // Output the output from cpplint to stderr + if (stdErr.find("(error)") != std::string::npos || + stdErr.find("(warning)") != std::string::npos || + stdErr.find("(style)") != std::string::npos || + stdErr.find("(performance)") != std::string::npos || + stdErr.find("(portability)") != std::string::npos || + stdErr.find("(information)") != std::string::npos) { + std::cerr << "Warning: cppcheck reported diagnostics:\n"; + } + std::cerr << stdErr; + // ignore errors so build continues + return 0; +} + +// called when args[0] == "__run_co_compile" +int cmcmd::HandleCoCompileCommands(std::vector<std::string>& args) +{ + // initialize a map from command option to handler function + std::map<std::string, + std::function<int(const std::string&, const std::string&, + const std::vector<std::string>&)>> + coCompileTypes; + auto a1 = std::placeholders::_1; + auto a2 = std::placeholders::_2; + auto a3 = std::placeholders::_3; + // create a map from option to handler function for option + // if the option does not call the original command then it will need + // to set runOriginalCmd to false later in this function + coCompileTypes["--iwyu="] = std::bind(&cmcmd::HandleIWYU, a1, a2, a3); + coCompileTypes["--tidy="] = std::bind(&cmcmd::HandleTidy, a1, a2, a3); + coCompileTypes["--lwyu="] = std::bind(&cmcmd::HandleLWYU, a1, a2, a3); + coCompileTypes["--cpplint="] = std::bind(&cmcmd::HandleCppLint, a1, a2, a3); + coCompileTypes["--cppcheck="] = + std::bind(&cmcmd::HandleCppCheck, a1, a2, a3); + // copy the command options to a vector of strings + std::vector<std::string> commandOptions; + for (const auto& i : coCompileTypes) { + commandOptions.push_back(i.first); + } + + std::string runCmd; // command to be run from --thing=command + std::string sourceFile; // store --source= + std::string commandFound; // the command that was in the args list + std::vector<std::string> orig_cmd; + bool doing_options = true; + for (std::string::size_type cc = 2; cc < args.size(); cc++) { + std::string const& arg = args[cc]; + // if the arg is -- then the rest of the args after + // go into orig_cmd + if (arg == "--") { + doing_options = false; + } else if (doing_options) { + bool optionFound = false; + // check arg against all the commandOptions + for (auto const& command : commandOptions) { + if (arg.compare(0, command.size(), command) == 0) { + optionFound = true; + runCmd = arg.substr(command.size()); + commandFound = command; + } + } + // check arg with --source= + if (cmHasLiteralPrefix(arg, "--source=")) { + sourceFile = arg.substr(9); + optionFound = true; + } + // if it was not a commandOptions or --source then error + if (!optionFound) { + std::cerr << "__run_co_compile given unknown argument: " << arg + << "\n"; + return 1; + } + } else { // if not doing_options then push to orig_cmd + orig_cmd.push_back(arg); + } + } + if (commandFound.empty()) { + std::cerr << "__run_co_compile missing command to run. Looking for one of " + "the following:\n"; + for (const auto& i : commandOptions) { + std::cerr << i << "\n"; + } + return 1; + } + // Default is to run the original command found after -- if the option + // does not need to do that, it should be specified here, currently only + // lwyu does that. + bool runOriginalCmd = true; + if (commandFound == "--lwyu=") { + runOriginalCmd = false; + } + if (runOriginalCmd && orig_cmd.empty()) { + std::cerr << "__run_co_compile missing compile command after --\n"; + return 1; + } + + // call the command handler here + int ret = coCompileTypes[commandFound](runCmd, sourceFile, orig_cmd); + // if the command returns non-zero then return and fail. + // for commands that do not want to break the build, they should return + // 0 no matter what. + if (ret != 0) { + return ret; + } + // if there is no original command to run return now + if (!runOriginalCmd) { + return ret; + } + // Now run the real compiler command and return its result value + if (!cmSystemTools::RunSingleCommand(orig_cmd, nullptr, nullptr, &ret, + nullptr, + cmSystemTools::OUTPUT_PASSTHROUGH)) { + std::cerr << "Error running '" << orig_cmd[0] << "'\n"; + return 1; + } + // return the return value from the original compiler command + return ret; +} + int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args) { // IF YOU ADD A NEW COMMAND, DOCUMENT IT ABOVE and in cmakemain.cxx @@ -280,234 +554,8 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args) return 0; } #endif - // run include what you use command and then run the compile - // command. This is an internal undocumented option and should - // only be used by CMake itself when running iwyu. - if (args[1] == "__run_iwyu") { - if (args.size() < 3) { - std::cerr << "__run_iwyu Usage: -E __run_iwyu [--iwyu=/path/iwyu]" - " [--cpplint=/path/cpplint] [--tidy=/path/tidy]" - " -- compile command\n"; - return 1; - } - bool doing_options = true; - std::vector<std::string> orig_cmd; - std::string iwyu; - std::string tidy; - std::string sourceFile; - std::string lwyu; - std::string cpplint; - std::string cppcheck; - for (std::string::size_type cc = 2; cc < args.size(); cc++) { - std::string const& arg = args[cc]; - if (arg == "--") { - doing_options = false; - } else if (doing_options && cmHasLiteralPrefix(arg, "--iwyu=")) { - iwyu = arg.substr(7); - } else if (doing_options && cmHasLiteralPrefix(arg, "--tidy=")) { - tidy = arg.substr(7); - } else if (doing_options && cmHasLiteralPrefix(arg, "--source=")) { - sourceFile = arg.substr(9); - } else if (doing_options && cmHasLiteralPrefix(arg, "--lwyu=")) { - lwyu = arg.substr(7); - } else if (doing_options && cmHasLiteralPrefix(arg, "--cpplint=")) { - cpplint = arg.substr(10); - } else if (doing_options && cmHasLiteralPrefix(arg, "--cppcheck=")) { - cppcheck = arg.substr(11); - } else if (doing_options) { - std::cerr << "__run_iwyu given unknown argument: " << arg << "\n"; - return 1; - } else { - orig_cmd.push_back(arg); - } - } - if (tidy.empty() && iwyu.empty() && lwyu.empty() && cpplint.empty() && - cppcheck.empty()) { - std::cerr << "__run_iwyu missing --cpplint=, --iwyu=, --lwyu=, " - "--cppcheck= and/or --tidy=\n"; - return 1; - } - if ((!cpplint.empty() || !tidy.empty() || !cppcheck.empty()) && - sourceFile.empty()) { - std::cerr << "__run_iwyu --cpplint=, __run_iwyu --tidy=" - ", __run_iwyu --cppcheck require --source=\n"; - return 1; - } - if (orig_cmd.empty() && lwyu.empty()) { - std::cerr << "__run_iwyu missing compile command after --\n"; - return 1; - } - - int ret = 0; - - if (!iwyu.empty()) { - // Construct the iwyu command line by taking what was given - // and adding all the arguments we give to the compiler. - std::vector<std::string> iwyu_cmd; - cmSystemTools::ExpandListArgument(iwyu, iwyu_cmd, true); - iwyu_cmd.insert(iwyu_cmd.end(), orig_cmd.begin() + 1, orig_cmd.end()); - - // Run the iwyu command line. Capture its stderr and hide its stdout. - // Ignore its return code because the tool always returns non-zero. - std::string stdErr; - if (!cmSystemTools::RunSingleCommand(iwyu_cmd, nullptr, &stdErr, &ret, - nullptr, - cmSystemTools::OUTPUT_NONE)) { - std::cerr << "Error running '" << iwyu_cmd[0] << "': " << stdErr - << "\n"; - return 1; - } - - // Warn if iwyu reported anything. - if (stdErr.find("should remove these lines:") != std::string::npos || - stdErr.find("should add these lines:") != std::string::npos) { - std::cerr << "Warning: include-what-you-use reported diagnostics:\n" - << stdErr << "\n"; - } - } - - if (!tidy.empty()) { - // Construct the clang-tidy command line by taking what was given - // and adding our compiler command line. The clang-tidy tool will - // automatically skip over the compiler itself and extract the - // options. - std::vector<std::string> tidy_cmd; - cmSystemTools::ExpandListArgument(tidy, tidy_cmd, true); - tidy_cmd.push_back(sourceFile); - tidy_cmd.push_back("--"); - tidy_cmd.insert(tidy_cmd.end(), orig_cmd.begin(), orig_cmd.end()); - - // Run the tidy command line. Capture its stdout and hide its stderr. - std::string stdOut; - std::string stdErr; - if (!cmSystemTools::RunSingleCommand(tidy_cmd, &stdOut, &stdErr, &ret, - nullptr, - cmSystemTools::OUTPUT_NONE)) { - std::cerr << "Error running '" << tidy_cmd[0] << "': " << stdErr - << "\n"; - return 1; - } - // Output the stdout from clang-tidy to stderr - std::cerr << stdOut; - // If clang-tidy exited with an error do the same. - if (ret != 0) { - std::cerr << stdErr; - return ret; - } - } - if (!lwyu.empty()) { - // Construct the ldd -r -u (link what you use lwyu) command line - // ldd -u -r lwuy target - std::vector<std::string> lwyu_cmd; - lwyu_cmd.push_back("ldd"); - lwyu_cmd.push_back("-u"); - lwyu_cmd.push_back("-r"); - lwyu_cmd.push_back(lwyu); - - // Run the ldd -u -r command line. - // Capture its stdout and hide its stderr. - // Ignore its return code because the tool always returns non-zero - // if there are any warnings, but we just want to warn. - std::string stdOut; - std::string stdErr; - if (!cmSystemTools::RunSingleCommand(lwyu_cmd, &stdOut, &stdErr, &ret, - nullptr, - cmSystemTools::OUTPUT_NONE)) { - std::cerr << "Error running '" << lwyu_cmd[0] << "': " << stdErr - << "\n"; - return 1; - } - - // Output the stdout from ldd -r -u to stderr - // Warn if lwyu reported anything. - if (stdOut.find("Unused direct dependencies:") != std::string::npos) { - std::cerr << "Warning: " << stdOut; - } - } - - if (!cpplint.empty()) { - // Construct the cpplint command line. - std::vector<std::string> cpplint_cmd; - cmSystemTools::ExpandListArgument(cpplint, cpplint_cmd, true); - cpplint_cmd.push_back(sourceFile); - - // Run the cpplint command line. Capture its output. - std::string stdOut; - if (!cmSystemTools::RunSingleCommand(cpplint_cmd, &stdOut, &stdOut, - &ret, nullptr, - cmSystemTools::OUTPUT_NONE)) { - std::cerr << "Error running '" << cpplint_cmd[0] << "': " << stdOut - << "\n"; - return 1; - } - - // Output the output from cpplint to stderr - std::cerr << stdOut; - - // If cpplint exited with an error do the same. - if (ret != 0) { - return ret; - } - } - - if (!cppcheck.empty()) { - // Construct the cpplint command line. - std::vector<std::string> cppcheck_cmd; - cmSystemTools::ExpandListArgument(cppcheck, cppcheck_cmd, true); - // extract all the -D, -U, and -I options from the compile line - for (size_t i = 0; i < orig_cmd.size(); i++) { - std::string& opt = orig_cmd[i]; - if (opt.size() > 2) { - if ((opt[0] == '-') && - ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) { - cppcheck_cmd.push_back(opt); -#if defined(_WIN32) - } else if ((opt[0] == '/') && - ((opt[1] == 'D') || (opt[1] == 'I') || - (opt[1] == 'U'))) { - std::string optcopy = opt; - optcopy[0] = '-'; - cppcheck_cmd.push_back(optcopy); -#endif - } - } - } - // add the source file - cppcheck_cmd.push_back(sourceFile); - - // Run the cpplint command line. Capture its output. - std::string stdOut; - if (!cmSystemTools::RunSingleCommand(cppcheck_cmd, &stdOut, &stdOut, - &ret, nullptr, - cmSystemTools::OUTPUT_NONE)) { - std::cerr << "Error running '" << cppcheck_cmd[0] << "': " << stdOut - << "\n"; - return 1; - } - // Output the output from cpplint to stderr - if (stdOut.find("(error)") != std::string::npos || - stdOut.find("(warning)") != std::string::npos || - stdOut.find("(style)") != std::string::npos || - stdOut.find("(performance)") != std::string::npos || - stdOut.find("(portability)") != std::string::npos || - stdOut.find("(information)") != std::string::npos) { - std::cerr << "Warning: cppcheck reported diagnostics:\n"; - } - std::cerr << stdOut; - } - // ignore the cppcheck error code because it is likely to have them - // from bad -D stuff - ret = 0; - // Now run the real compiler command and return its result value - // unless we are lwyu - if (lwyu.empty() && - !cmSystemTools::RunSingleCommand( - orig_cmd, nullptr, nullptr, &ret, nullptr, - cmSystemTools::OUTPUT_PASSTHROUGH)) { - std::cerr << "Error running '" << orig_cmd[0] << "'\n"; - return 1; - } - return ret; + if (args[1] == "__run_co_compile") { + return cmcmd::HandleCoCompileCommands(args); } // Echo string @@ -880,8 +928,8 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args) cmStateSnapshot snapshot = cm.GetCurrentSnapshot(); snapshot.GetDirectory().SetCurrentBinary(startOutDir); snapshot.GetDirectory().SetCurrentSource(startDir); - CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(ggd, snapshot)); - CM_AUTO_PTR<cmLocalGenerator> lgd(ggd->CreateLocalGenerator(mf.get())); + cmMakefile mf(ggd, snapshot); + std::unique_ptr<cmLocalGenerator> lgd(ggd->CreateLocalGenerator(&mf)); // Actually scan dependencies. return lgd->UpdateDependencies(depInfo.c_str(), verbose, color) ? 0 @@ -1462,24 +1510,23 @@ private: // For visual studio 2005 and newer manifest files need to be embedded into // exe and dll's. This code does that in such a way that incremental linking // still works. -int cmcmd::VisualStudioLink(std::vector<std::string>& args, int type) +int cmcmd::VisualStudioLink(std::vector<std::string> const& args, int type) { if (args.size() < 2) { return -1; } const bool verbose = cmSystemTools::HasEnv("VERBOSE"); std::vector<std::string> expandedArgs; - for (std::vector<std::string>::iterator i = args.begin(); i != args.end(); - ++i) { + for (std::string const& i : args) { // check for nmake temporary files - if ((*i)[0] == '@' && i->find("@CMakeFiles") != 0) { - cmsys::ifstream fin(i->substr(1).c_str()); + if (i[0] == '@' && i.find("@CMakeFiles") != 0) { + cmsys::ifstream fin(i.substr(1).c_str()); std::string line; while (cmSystemTools::GetLineFromStream(fin, line)) { cmSystemTools::ParseWindowsCommandLine(line.c_str(), expandedArgs); } } else { - expandedArgs.push_back(*i); + expandedArgs.push_back(i); } } @@ -1490,8 +1537,34 @@ int cmcmd::VisualStudioLink(std::vector<std::string>& args, int type) return vsLink.Link(); } +enum NumberFormat +{ + FORMAT_DECIMAL, + FORMAT_HEX +}; +struct NumberFormatter +{ + NumberFormat Format; + int Value; + NumberFormatter(NumberFormat format, int value) + : Format(format) + , Value(value) + { + } +}; +std::ostream& operator<<(std::ostream& stream, + NumberFormatter const& formatter) +{ + if (formatter.Format == FORMAT_DECIMAL) { + stream << formatter.Value; + } else { + stream << "0x" << std::hex << formatter.Value; + } + return stream; +} static bool RunCommand(const char* comment, std::vector<std::string>& command, - bool verbose, int* retCodeOut = nullptr) + bool verbose, NumberFormat exitFormat, + int* retCodeOut = nullptr) { if (verbose) { std::cout << comment << ":\n"; @@ -1499,31 +1572,33 @@ static bool RunCommand(const char* comment, std::vector<std::string>& command, } std::string output; int retCode = 0; - // use rc command to create .res file - bool res = cmSystemTools::RunSingleCommand( + bool commandResult = cmSystemTools::RunSingleCommand( command, &output, &output, &retCode, nullptr, cmSystemTools::OUTPUT_NONE); - // always print the output of the command, unless - // it is the dumb rc command banner, but if the command - // returned an error code then print the output anyway as - // the banner may be mixed with some other important information. - if (output.find("Resource Compiler Version") == std::string::npos || !res || - retCode) { - std::cout << output; - } - if (!res) { - std::cout << comment << " failed to run." << std::endl; - return false; - } - // if retCodeOut is requested then always return true - // and set the retCodeOut to retCode + bool returnValue; if (retCodeOut) { - *retCodeOut = retCode; - return true; + if (!commandResult) { + *retCodeOut = (retCode == 0) ? -1 : retCode; + } else { + *retCodeOut = retCode; + } + returnValue = true; // always return true if retCodeOut is requested + } else { + returnValue = commandResult && (retCode == 0); } - if (retCode != 0) { - std::cout << comment << " failed. with " << retCode << "\n"; + if (!commandResult || retCode) { + std::cout << comment << ": command \"" << cmJoin(command, " ") + << "\" failed (exit code " + << NumberFormatter(exitFormat, retCode) + << ") with the following output:\n" + << output; + } else { + // always print the output of the command, unless + // it is the dumb rc command banner + if (output.find("Resource Compiler Version") == std::string::npos) { + std::cout << output; + } } - return retCode == 0; + return returnValue; } bool cmVSLink::Parse(std::vector<std::string>::const_iterator argBeg, @@ -1673,10 +1748,10 @@ int cmVSLink::LinkIncremental() // Compile the resource file. std::vector<std::string> rcCommand; - rcCommand.push_back(cmSystemTools::FindProgram("rc.exe")); + rcCommand.push_back("rc"); rcCommand.push_back("/fo" + this->ManifestFileRes); rcCommand.push_back(this->ManifestFileRC); - if (!RunCommand("RC Pass 1", rcCommand, this->Verbose)) { + if (!RunCommand("RC Pass 1", rcCommand, this->Verbose, FORMAT_DECIMAL)) { return -1; } @@ -1684,7 +1759,8 @@ int cmVSLink::LinkIncremental() this->LinkCommand.push_back(this->ManifestFileRes); // Run the link command (possibly generates intermediate manifest). - if (!RunCommand("LINK Pass 1", this->LinkCommand, this->Verbose)) { + if (!RunCommand("LINK Pass 1", this->LinkCommand, this->Verbose, + FORMAT_DECIMAL)) { return -1; } @@ -1698,12 +1774,13 @@ int cmVSLink::LinkIncremental() } // Compile the resource file again. - if (!RunCommand("RC Pass 2", rcCommand, this->Verbose)) { + if (!RunCommand("RC Pass 2", rcCommand, this->Verbose, FORMAT_DECIMAL)) { return -1; } // Link incrementally again to use the updated resource. - if (!RunCommand("FINAL LINK", this->LinkCommand, this->Verbose)) { + if (!RunCommand("FINAL LINK", this->LinkCommand, this->Verbose, + FORMAT_DECIMAL)) { return -1; } return 0; @@ -1712,7 +1789,7 @@ int cmVSLink::LinkIncremental() int cmVSLink::LinkNonIncremental() { // Run the link command (possibly generates intermediate manifest). - if (!RunCommand("LINK", this->LinkCommand, this->Verbose)) { + if (!RunCommand("LINK", this->LinkCommand, this->Verbose, FORMAT_DECIMAL)) { return -1; } @@ -1730,7 +1807,7 @@ int cmVSLink::LinkNonIncremental() int cmVSLink::RunMT(std::string const& out, bool notify) { std::vector<std::string> mtCommand; - mtCommand.push_back(cmSystemTools::FindProgram("mt.exe")); + mtCommand.push_back("mt"); mtCommand.push_back("/nologo"); mtCommand.push_back("/manifest"); if (this->LinkGeneratesManifest) { @@ -1745,7 +1822,7 @@ int cmVSLink::RunMT(std::string const& out, bool notify) mtCommand.push_back("/notify_update"); } int mtRet = 0; - if (!RunCommand("MT", mtCommand, this->Verbose, &mtRet)) { + if (!RunCommand("MT", mtCommand, this->Verbose, FORMAT_HEX, &mtRet)) { return -1; } return mtRet; diff --git a/Source/cmcmd.h b/Source/cmcmd.h index faac1d2..090ca08 100644 --- a/Source/cmcmd.h +++ b/Source/cmcmd.h @@ -18,7 +18,26 @@ public: */ static int ExecuteCMakeCommand(std::vector<std::string>&); + // define co-compile command handlers they must be public + // because they are used in a std::function map + static int HandleIWYU(const std::string& runCmd, + const std::string& sourceFile, + const std::vector<std::string>& orig_cmd); + static int HandleTidy(const std::string& runCmd, + const std::string& sourceFile, + const std::vector<std::string>& orig_cmd); + static int HandleLWYU(const std::string& runCmd, + const std::string& sourceFile, + const std::vector<std::string>& orig_cmd); + static int HandleCppLint(const std::string& runCmd, + const std::string& sourceFile, + const std::vector<std::string>& orig_cmd); + static int HandleCppCheck(const std::string& runCmd, + const std::string& sourceFile, + const std::vector<std::string>& orig_cmd); + protected: + static int HandleCoCompileCommands(std::vector<std::string>& args); static int HashSumFile(std::vector<std::string>& args, cmCryptoHash::Algo algo); static int SymlinkLibrary(std::vector<std::string>& args); @@ -29,7 +48,7 @@ protected: static int ExecuteLinkScript(std::vector<std::string>& args); static int WindowsCEEnvironment(const char* version, const std::string& name); - static int VisualStudioLink(std::vector<std::string>& args, int type); + static int VisualStudioLink(std::vector<std::string> const& args, int type); }; #endif diff --git a/Source/kwsys/CMakeLists.txt b/Source/kwsys/CMakeLists.txt index d7d0c51..5b8ce00 100644 --- a/Source/kwsys/CMakeLists.txt +++ b/Source/kwsys/CMakeLists.txt @@ -1032,6 +1032,7 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR) testSystemTools testCommandLineArguments testCommandLineArguments1 + testDirectory ) IF(KWSYS_STL_HAS_WSTRING) SET(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS} diff --git a/Source/kwsys/Directory.cxx b/Source/kwsys/Directory.cxx index 5141d45..69068aa 100644 --- a/Source/kwsys/Directory.cxx +++ b/Source/kwsys/Directory.cxx @@ -118,8 +118,8 @@ bool Directory::Load(const std::string& name) struct _wfinddata_t data; // data of current file // Now put them into the file array - srchHandle = - _wfindfirst_func((wchar_t*)Encoding::ToWide(buf).c_str(), &data); + srchHandle = _wfindfirst_func( + (wchar_t*)Encoding::ToWindowsExtendedPath(buf).c_str(), &data); delete[] buf; if (srchHandle == -1) { diff --git a/Source/kwsys/SystemTools.cxx b/Source/kwsys/SystemTools.cxx index 11f3b81..0a22d63 100644 --- a/Source/kwsys/SystemTools.cxx +++ b/Source/kwsys/SystemTools.cxx @@ -2269,11 +2269,7 @@ bool SystemTools::CopyADirectory(const std::string& source, const std::string& destination, bool always) { Directory dir; -#ifdef _WIN32 - dir.Load(Encoding::ToNarrow(Encoding::ToWindowsExtendedPath(source))); -#else dir.Load(source); -#endif size_t fileNum; if (!SystemTools::MakeDirectory(destination)) { return false; @@ -2626,11 +2622,7 @@ bool SystemTools::RemoveADirectory(const std::string& source) } Directory dir; -#ifdef _WIN32 - dir.Load(Encoding::ToNarrow(Encoding::ToWindowsExtendedPath(source))); -#else dir.Load(source); -#endif size_t fileNum; for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum) { if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), ".") && @@ -4110,66 +4102,6 @@ bool SystemTools::GetShortPath(const std::string& path, std::string& shortPath) #endif } -void SystemTools::SplitProgramFromArgs(const std::string& path, - std::string& program, std::string& args) -{ - // see if this is a full path to a program - // if so then set program to path and args to nothing - if (SystemTools::FileExists(path)) { - program = path; - args = ""; - return; - } - // Try to find the program in the path, note the program - // may have spaces in its name so we have to look for it - std::vector<std::string> e; - std::string findProg = SystemTools::FindProgram(path, e); - if (!findProg.empty()) { - program = findProg; - args = ""; - return; - } - - // Now try and peel off space separated chunks from the end of the string - // so the largest path possible is found allowing for spaces in the path - std::string dir = path; - std::string::size_type spacePos = dir.rfind(' '); - while (spacePos != std::string::npos) { - std::string tryProg = dir.substr(0, spacePos); - // See if the file exists - if (SystemTools::FileExists(tryProg)) { - program = tryProg; - // remove trailing spaces from program - std::string::size_type pos = program.size() - 1; - while (program[pos] == ' ') { - program.erase(pos); - pos--; - } - args = dir.substr(spacePos, dir.size() - spacePos); - return; - } - // Now try and find the program in the path - findProg = SystemTools::FindProgram(tryProg, e); - if (!findProg.empty()) { - program = findProg; - // remove trailing spaces from program - std::string::size_type pos = program.size() - 1; - while (program[pos] == ' ') { - program.erase(pos); - pos--; - } - args = dir.substr(spacePos, dir.size() - spacePos); - return; - } - // move past the space for the next search - spacePos--; - spacePos = dir.rfind(' ', spacePos); - } - - program = ""; - args = ""; -} - std::string SystemTools::GetCurrentDateTime(const char* format) { char buf[1024]; diff --git a/Source/kwsys/SystemTools.hxx.in b/Source/kwsys/SystemTools.hxx.in index 1672e92..41a60d3 100644 --- a/Source/kwsys/SystemTools.hxx.in +++ b/Source/kwsys/SystemTools.hxx.in @@ -498,12 +498,6 @@ public: static std::string GetFilenameName(const std::string&); /** - * Split a program from its arguments and handle spaces in the paths - */ - static void SplitProgramFromArgs(const std::string& path, - std::string& program, std::string& args); - - /** * Return longest file extension of a full filename (dot included) */ static std::string GetFilenameExtension(const std::string&); diff --git a/Source/kwsys/kwsysPlatformTestsCXX.cxx b/Source/kwsys/kwsysPlatformTestsCXX.cxx index 01c6951..e67d436 100644 --- a/Source/kwsys/kwsysPlatformTestsCXX.cxx +++ b/Source/kwsys/kwsysPlatformTestsCXX.cxx @@ -265,6 +265,12 @@ int main() #ifdef TEST_KWSYS_CXX_HAS_UTIMENSAT #include <fcntl.h> #include <sys/stat.h> +#if defined(__APPLE__) +#include <AvailabilityMacros.h> +#if MAC_OS_X_VERSION_MIN_REQUIRED < 101300 +#error "utimensat not available on macOS < 10.13" +#endif +#endif int main() { struct timespec times[2] = { { 0, UTIME_OMIT }, { 0, UTIME_NOW } }; diff --git a/Source/kwsys/testDirectory.cxx b/Source/kwsys/testDirectory.cxx new file mode 100644 index 0000000..983f2c6 --- /dev/null +++ b/Source/kwsys/testDirectory.cxx @@ -0,0 +1,79 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying +file Copyright.txt or https://cmake.org/licensing#kwsys for details. */ +#include "kwsysPrivate.h" +#include KWSYS_HEADER(Directory.hxx) +#include KWSYS_HEADER(Encoding.hxx) +#include KWSYS_HEADER(SystemTools.hxx) + +// Work-around CMake dependency scanning limitation. This must +// duplicate the above list of headers. +#if 0 +#include "Directory.hxx.in" +#include "Encoding.hxx.in" +#include "SystemTools.hxx.in" +#endif + +#include <fstream> +#include <iostream> +#include <sstream> + +#include <testSystemTools.h> + +int _doLongPathTest() +{ + using namespace kwsys; + static const int LONG_PATH_THRESHOLD = 512; + int res = 0; + std::string topdir(TEST_SYSTEMTOOLS_BINARY_DIR "/directory_testing/"); + std::stringstream testpathstrm; + std::string testdirpath; + std::string extendedtestdirpath; + + testpathstrm << topdir; + size_t pathlen = testpathstrm.str().length(); + testpathstrm.seekp(0, std::ios_base::end); + while (pathlen < LONG_PATH_THRESHOLD) { + testpathstrm << "0123456789/"; + pathlen = testpathstrm.str().length(); + } + + testdirpath = testpathstrm.str(); +#ifdef _WIN32 + extendedtestdirpath = + Encoding::ToNarrow(SystemTools::ConvertToWindowsExtendedPath(testdirpath)); +#else + extendedtestdirpath = testdirpath; +#endif + + if (SystemTools::MakeDirectory(extendedtestdirpath)) { + std::ofstream testfile1( + (extendedtestdirpath + "longfilepathtest1.txt").c_str()); + std::ofstream testfile2( + (extendedtestdirpath + "longfilepathtest2.txt").c_str()); + testfile1 << "foo"; + testfile2 << "bar"; + testfile1.close(); + testfile2.close(); + + Directory testdir; + // Set res to failure if the directory doesn't load + res += !testdir.Load(testdirpath); + // Increment res failure if the directory appears empty + res += testdir.GetNumberOfFiles() == 0; + // Increment res failures if the path has changed from + // what was provided. + res += testdirpath != testdir.GetPath(); + + SystemTools::RemoveADirectory(topdir); + } else { + std::cerr << "Failed to create directory with long path: " + << extendedtestdirpath << std::endl; + res += 1; + } + return res; +} + +int testDirectory(int, char* []) +{ + return _doLongPathTest(); +} diff --git a/Tests/CMakeLib/run_compile_commands.cxx b/Tests/CMakeLib/run_compile_commands.cxx index 0d692ca..b49803b 100644 --- a/Tests/CMakeLib/run_compile_commands.cxx +++ b/Tests/CMakeLib/run_compile_commands.cxx @@ -144,14 +144,11 @@ int main() cmsys::ifstream file("compile_commands.json"); CompileCommandParser parser(file); parser.Parse(); - for (CompileCommandParser::TranslationUnitsType::const_iterator - it = parser.GetTranslationUnits().begin(), - end = parser.GetTranslationUnits().end(); - it != end; ++it) { + for (auto const& tu : parser.GetTranslationUnits()) { std::vector<std::string> command; - cmSystemTools::ParseUnixCommandLine(it->at("command").c_str(), command); + cmSystemTools::ParseUnixCommandLine(tu.at("command").c_str(), command); if (!cmSystemTools::RunSingleCommand(command, nullptr, nullptr, nullptr, - it->at("directory").c_str())) { + tu.at("directory").c_str())) { std::cout << "ERROR: Failed to run command \"" << command[0] << "\"" << std::endl; exit(1); diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt index f0e58ee..ce53454 100644 --- a/Tests/CMakeLists.txt +++ b/Tests/CMakeLists.txt @@ -146,6 +146,10 @@ if(BUILD_TESTING) if(NOT CMake_TEST_EXTERNAL_CMAKE) add_subdirectory(CMakeLib) + + if(CMake_TEST_SERVER_MODE) + add_subdirectory(CMakeServerLib) + endif() endif() add_subdirectory(CMakeOnly) add_subdirectory(RunCMake) @@ -264,7 +268,7 @@ if(BUILD_TESTING) endif() add_test(NAME CMake.Copyright - COMMAND cmake -P ${CMAKE_CURRENT_SOURCE_DIR}/CMakeCopyright.cmake) + COMMAND ${CMAKE_CMAKE_COMMAND} -P ${CMAKE_CURRENT_SOURCE_DIR}/CMakeCopyright.cmake) # add a bunch of standard build-and-test style tests ADD_TEST_MACRO(CommandLineTest CommandLineTest) @@ -325,7 +329,7 @@ if(BUILD_TESTING) set(CMAKE_SKIP_VSGNUFortran TRUE) endif() if(NOT CMAKE_SKIP_VSGNUFortran) - ADD_TEST_MACRO(VSGNUFortran ${CMAKE_COMMAND} -P runtest.cmake) + ADD_TEST_MACRO(VSGNUFortran ${CMAKE_CMAKE_COMMAND} -P runtest.cmake) endif() endif() @@ -809,31 +813,6 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release ) list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/CustomCommandWorkingDirectory") - #add_test(SimpleExclude ${CMAKE_CTEST_COMMAND} - # --build-and-test - # "${CMake_SOURCE_DIR}/Tests/SimpleExclude" - # "${CMake_BINARY_DIR}/Tests/SimpleExclude" - # ${build_generator_args} - # --build-project SimpleExclude - # --build-two-config - # --build-options ${build_options} - # --test-command t4 - #--test-command "${CMAKE_COMMAND}" - #"-DCONFIGURATION=\${CTEST_CONFIGURATION_TYPE}" - #-P "${CMake_BINARY_DIR}/Tests/SimpleExclude/run.cmake" - #) - -# add_test(SameName ${CMAKE_CTEST_COMMAND} -# --build-and-test -# "${CMake_SOURCE_DIR}/Tests/SameName" -# "${CMake_BINARY_DIR}/Tests/SameName" -# ${build_generator_args} -# --build-project SameName -# --build-two-config -# --build-options ${build_options} -# --test-command -# "${CMake_BINARY_DIR}/Tests/SameName/Exe1/mytest2") - add_test(OutOfSource ${CMAKE_CTEST_COMMAND} --build-and-test "${CMake_SOURCE_DIR}/Tests/OutOfSource" @@ -1427,6 +1406,14 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release add_subdirectory(FindDoxygen) endif() + if(CMake_TEST_FindEXPAT) + add_subdirectory(FindEXPAT) + endif() + + if(CMake_TEST_FindFreetype) + add_subdirectory(FindFreetype) + endif() + if(CMake_TEST_FindGSL) add_subdirectory(FindGSL) endif() @@ -1480,6 +1467,10 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release add_subdirectory(FindPNG) endif() + if(CMake_TEST_FindPatch) + add_subdirectory(FindPatch) + endif() + if(CMake_TEST_FindProtobuf) add_subdirectory(FindProtobuf) endif() @@ -2650,7 +2641,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release file(COPY "${CMake_SOURCE_DIR}/Tests/MumpsCoverage/VistA-FOIA" DESTINATION "${CMake_BINARY_DIR}/Testing/MumpsCoverage") add_test(NAME CTestGTMCoverage - COMMAND cmake -E chdir + COMMAND ${CMAKE_CMAKE_COMMAND} -E chdir ${CMake_BINARY_DIR}/Testing/MumpsCoverage $<TARGET_FILE:ctest> -T Coverage --debug) set_tests_properties(CTestGTMCoverage PROPERTIES @@ -2668,7 +2659,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release file(COPY "${CMake_SOURCE_DIR}/Tests/MumpsCoverage/VistA-FOIA" DESTINATION "${CMake_BINARY_DIR}/Testing/MumpsCacheCoverage") add_test(NAME CTestCacheCoverage - COMMAND cmake -E chdir + COMMAND ${CMAKE_CMAKE_COMMAND} -E chdir ${CMake_BINARY_DIR}/Testing/MumpsCacheCoverage $<TARGET_FILE:ctest> -T Coverage --debug) set_tests_properties(CTestCacheCoverage PROPERTIES @@ -2686,7 +2677,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release file(COPY "${CMake_SOURCE_DIR}/Tests/PythonCoverage/coveragetest" DESTINATION "${CMake_BINARY_DIR}/Testing/PythonCoverage") add_test(NAME CTestPythonCoverage - COMMAND cmake -E chdir + COMMAND ${CMAKE_CMAKE_COMMAND} -E chdir ${CMake_BINARY_DIR}/Testing/PythonCoverage $<TARGET_FILE:ctest> -T Coverage --debug) set_tests_properties(CTestPythonCoverage PROPERTIES @@ -2704,7 +2695,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release file(COPY "${CMake_SOURCE_DIR}/Tests/CoberturaCoverage/src" DESTINATION "${CMake_BINARY_DIR}/Testing/CoberturaCoverage") add_test(NAME CTestCoberturaCoverage - COMMAND cmake -E chdir + COMMAND ${CMAKE_CMAKE_COMMAND} -E chdir ${CMake_BINARY_DIR}/Testing/CoberturaCoverage $<TARGET_FILE:ctest> -T Coverage --debug) set_tests_properties(CTestCoberturaCoverage PROPERTIES @@ -2723,7 +2714,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release configure_file("${CMake_BINARY_DIR}/Testing/JacocoCoverage/Coverage/target/site/jacoco.xml.in" "${CMake_BINARY_DIR}/Testing/JacocoCoverage/Coverage/target/site/jacoco.xml") add_test(NAME CTestJacocoCoverage - COMMAND cmake -E chdir + COMMAND ${CMAKE_CMAKE_COMMAND} -E chdir ${CMake_BINARY_DIR}/Testing/JacocoCoverage $<TARGET_FILE:ctest> -T Coverage --debug) set_tests_properties(CTestJacocoCoverage PROPERTIES @@ -2742,7 +2733,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release DESTINATION "${CMake_BINARY_DIR}/Testing/JavascriptCoverage" FILES_MATCHING PATTERN "*.js") add_test(NAME CTestJavascriptCoverage - COMMAND cmake -E chdir + COMMAND ${CMAKE_CMAKE_COMMAND} -E chdir ${CMake_BINARY_DIR}/Testing/JavascriptCoverage $<TARGET_FILE:ctest> -T Coverage --debug) set_tests_properties(CTestJavascriptCoverage PROPERTIES @@ -2760,7 +2751,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release "${CMake_SOURCE_DIR}/Tests/DelphiCoverage/UTCovTest(UTCovTest.pas).html.in" "${CMake_BINARY_DIR}/Testing/DelphiCoverage/UTCovTest(UTCovTest.pas).html") add_test(NAME CTestDelphiCoverage - COMMAND cmake -E chdir + COMMAND ${CMAKE_CMAKE_COMMAND} -E chdir ${CMake_BINARY_DIR}/Testing/DelphiCoverage $<TARGET_FILE:ctest> -T Coverage --debug) set_tests_properties(CTestDelphiCoverage PROPERTIES diff --git a/Tests/CMakeServerLib/CMakeLists.txt b/Tests/CMakeServerLib/CMakeLists.txt new file mode 100644 index 0000000..f5351fd --- /dev/null +++ b/Tests/CMakeServerLib/CMakeLists.txt @@ -0,0 +1,17 @@ +include_directories( + ${CMAKE_CURRENT_BINARY_DIR} + ${CMake_BINARY_DIR}/Source + ${CMake_SOURCE_DIR}/Source + ) + +set(CMakeServerLib_TESTS + testServerBuffering + ) + +create_test_sourcelist(CMakeLib_TEST_SRCS CMakeServerLibTests.cxx ${CMakeServerLib_TESTS}) +add_executable(CMakeServerLibTests ${CMakeLib_TEST_SRCS}) +target_link_libraries(CMakeServerLibTests CMakeLib CMakeServerLib) + +foreach(test ${CMakeServerLib_TESTS}) + add_test(CMakeServerLib.${test} CMakeServerLibTests ${test} ${${test}_ARGS}) +endforeach() diff --git a/Tests/CMakeServerLib/testServerBuffering.cpp b/Tests/CMakeServerLib/testServerBuffering.cpp new file mode 100644 index 0000000..97be891 --- /dev/null +++ b/Tests/CMakeServerLib/testServerBuffering.cpp @@ -0,0 +1,86 @@ +#include "cmConnection.h" +#include "cmServerConnection.h" +#include <iostream> +#include <stddef.h> +#include <string> +#include <vector> + +void print_error(const std::vector<std::string>& input, + const std::vector<std::string>& output) +{ + std::cerr << "Responses don't equal input messages input." << std::endl; + std::cerr << "Responses: " << std::endl; + + for (auto& msg : output) { + std::cerr << "'" << msg << "'" << std::endl; + } + + std::cerr << "Input messages" << std::endl; + for (auto& msg : input) { + std::cerr << "'" << msg << "'" << std::endl; + } +} + +std::string trim_newline(const std::string& _buffer) +{ + auto buffer = _buffer; + while (!buffer.empty() && (buffer.back() == '\n' || buffer.back() == '\r')) { + buffer.pop_back(); + } + return buffer; +} + +int testServerBuffering(int, char** const) +{ + std::vector<std::string> messages = { + "{ \"test\": 10}", "{ \"test\": { \"test2\": false} }", + "{ \"test\": [1, 2, 3] }", + "{ \"a\": { \"1\": {}, \n\n\n \"2\":[] \t\t\t\t}}" + }; + + std::string fullMessage; + for (auto& msg : messages) { + fullMessage += "[== \"CMake Server\" ==[\n"; + fullMessage += msg; + fullMessage += "\n]== \"CMake Server\" ==]\n"; + } + + // The buffering strategy should cope with any fragmentation, including + // just getting the characters one at a time. + auto bufferingStrategy = + std::unique_ptr<cmConnectionBufferStrategy>(new cmServerBufferStrategy); + std::vector<std::string> response; + std::string rawBuffer; + for (size_t i = 0; i < fullMessage.size(); i++) { + rawBuffer += fullMessage[i]; + std::string packet = bufferingStrategy->BufferMessage(rawBuffer); + do { + if (!packet.empty() && packet != "\r\n") { + response.push_back(trim_newline(packet)); + } + packet = bufferingStrategy->BufferMessage(rawBuffer); + } while (!packet.empty()); + } + + if (response != messages) { + print_error(messages, response); + return 1; + } + + // We should also be able to deal with getting a bunch at once + response.clear(); + std::string packet = bufferingStrategy->BufferMessage(fullMessage); + do { + if (!packet.empty() && packet != "\r\n") { + response.push_back(trim_newline(packet)); + } + packet = bufferingStrategy->BufferMessage(fullMessage); + } while (!packet.empty()); + + if (response != messages) { + print_error(messages, response); + return 1; + } + + return 0; +} diff --git a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-depend1.cmake b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-depend1.cmake index 70d6edf..73fd0ab 100644 --- a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-depend1.cmake +++ b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-depend1.cmake @@ -6,7 +6,7 @@ include(${CPackComponentsDEB_SOURCE_DIR}/RunCPackVerifyResult.cmake) # expected results -set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2-1_*.deb") +set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2_*.deb") set(expected_count 3) diff --git a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-depend2.cmake b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-depend2.cmake index 415d536..81dbbc5 100644 --- a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-depend2.cmake +++ b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-depend2.cmake @@ -6,7 +6,7 @@ include(${CPackComponentsDEB_SOURCE_DIR}/RunCPackVerifyResult.cmake) # expected results -set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2-1_*.deb") +set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2_*.deb") set(expected_count 3) set(config_verbose -V) diff --git a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-description1.cmake b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-description1.cmake index 337cc16..ad52f56 100644 --- a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-description1.cmake +++ b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-description1.cmake @@ -6,7 +6,7 @@ include(${CPackComponentsDEB_SOURCE_DIR}/RunCPackVerifyResult.cmake) # expected results -set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2-1_*.deb") +set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2_*.deb") set(expected_count 3) diff --git a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-description2.cmake b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-description2.cmake index 35ca74c..af27c51 100644 --- a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-description2.cmake +++ b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-description2.cmake @@ -7,7 +7,7 @@ include(${CPackComponentsDEB_SOURCE_DIR}/RunCPackVerifyResult.cmake) # expected results -set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2-1_*.deb") +set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2_*.deb") set(expected_count 3) diff --git a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-lintian-dpkgdeb-checks.cmake b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-lintian-dpkgdeb-checks.cmake index f1391cd..1fe9258 100644 --- a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-lintian-dpkgdeb-checks.cmake +++ b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-lintian-dpkgdeb-checks.cmake @@ -5,7 +5,7 @@ endif() include(${CPackComponentsDEB_SOURCE_DIR}/RunCPackVerifyResult.cmake) # TODO: currently debian doens't produce lower cased names -set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2-1_*.deb") +set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2_*.deb") set(expected_count 3) diff --git a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-shlibdeps1.cmake b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-shlibdeps1.cmake index fcfc7ea..e57488c 100644 --- a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-shlibdeps1.cmake +++ b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-shlibdeps1.cmake @@ -9,7 +9,7 @@ include(${CPackComponentsDEB_SOURCE_DIR}/RunCPackVerifyResult.cmake) # requirements # debian now produces lower case names -set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2-1_*.deb") +set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2_*.deb") set(expected_count 3) diff --git a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-source.cmake b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-source.cmake index 351bf21..5ee057a 100644 --- a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-source.cmake +++ b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-source.cmake @@ -6,7 +6,7 @@ include(${CPackComponentsDEB_SOURCE_DIR}/RunCPackVerifyResult.cmake) # expected results -set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2-1_*.deb") +set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2_*.deb") set(expected_count 3) set(config_verbose -V) diff --git a/Tests/CPackComponentsDEB/RunCPackVerifyResult-compression.cmake b/Tests/CPackComponentsDEB/RunCPackVerifyResult-compression.cmake index c97ecb0..13a626a 100644 --- a/Tests/CPackComponentsDEB/RunCPackVerifyResult-compression.cmake +++ b/Tests/CPackComponentsDEB/RunCPackVerifyResult-compression.cmake @@ -5,7 +5,7 @@ endif() include(${CPackComponentsDEB_SOURCE_DIR}/RunCPackVerifyResult.cmake) # TODO: currently debian doens't produce lower cased names -set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib_1.0.2-1_*.deb") +set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib_1.0.2_*.deb") set(expected_count 1) set(actual_output) diff --git a/Tests/CPackComponentsForAll/RunCPackVerifyResult.cmake b/Tests/CPackComponentsForAll/RunCPackVerifyResult.cmake index a5b38fd..2c3a849 100644 --- a/Tests/CPackComponentsForAll/RunCPackVerifyResult.cmake +++ b/Tests/CPackComponentsForAll/RunCPackVerifyResult.cmake @@ -60,7 +60,7 @@ elseif (CPackGen MATCHES "RPM") set(expected_count 1) endif () elseif (CPackGen MATCHES "DEB") - set(expected_file_mask "${CPackComponentsForAll_BINARY_DIR}/mylib*_1.0.2-1_*.deb") + set(expected_file_mask "${CPackComponentsForAll_BINARY_DIR}/mylib*_1.0.2_*.deb") if (${CPackComponentWay} STREQUAL "default") set(expected_count 1) elseif (${CPackComponentWay} STREQUAL "OnePackPerGroup") diff --git a/Tests/CSharpLinkToCxx/CMakeLists.txt b/Tests/CSharpLinkToCxx/CMakeLists.txt index c4269e0..153c57c 100644 --- a/Tests/CSharpLinkToCxx/CMakeLists.txt +++ b/Tests/CSharpLinkToCxx/CMakeLists.txt @@ -15,3 +15,9 @@ target_compile_options(CLIApp PRIVATE "/clr") add_executable(CSharpLinkToCxx csharp.cs) target_link_libraries(CSharpLinkToCxx CLIApp) + +# this unmanaged C++ library will be added to the C#/.NET +# references of CSharpLinkToCxx but it will show a warning +# because it is unmanaged +add_library(CppNativeApp SHARED cpp_native.hpp cpp_native.cpp) +target_link_libraries(CSharpLinkToCxx CppNativeApp) diff --git a/Tests/CSharpLinkToCxx/cpp_native.cpp b/Tests/CSharpLinkToCxx/cpp_native.cpp new file mode 100644 index 0000000..dc7670f --- /dev/null +++ b/Tests/CSharpLinkToCxx/cpp_native.cpp @@ -0,0 +1,10 @@ +#include "cpp_native.hpp" + +#include <iostream> + +namespace CppApp { +void MyCpp::testMyCpp() +{ + std::cout << "#message from CppApp" << std::endl; +} +} diff --git a/Tests/CSharpLinkToCxx/cpp_native.hpp b/Tests/CSharpLinkToCxx/cpp_native.hpp new file mode 100644 index 0000000..0fa1a3b --- /dev/null +++ b/Tests/CSharpLinkToCxx/cpp_native.hpp @@ -0,0 +1,9 @@ +#pragma once + +namespace CppApp { +class MyCpp +{ +public: + void testMyCpp(); +}; +} diff --git a/Tests/CompileFeatures/cxx_digit_separators.cpp b/Tests/CompileFeatures/cxx_digit_separators.cpp index a40ac0a..abcd1c8 100644 --- a/Tests/CompileFeatures/cxx_digit_separators.cpp +++ b/Tests/CompileFeatures/cxx_digit_separators.cpp @@ -1,5 +1,6 @@ int someFunc() { - int one_thousand = 1'000; return one_thousand - 1000; + int one_thousand = 1'000; + return one_thousand - 1000; } diff --git a/Tests/CompileFeatures/cxx_raw_string_literals.cpp b/Tests/CompileFeatures/cxx_raw_string_literals.cpp index ea4d231..0f83a7c 100644 --- a/Tests/CompileFeatures/cxx_raw_string_literals.cpp +++ b/Tests/CompileFeatures/cxx_raw_string_literals.cpp @@ -1,7 +1,7 @@ void someFunc() { -const char p[] = R"(a\ + const char p[] = R"(a\ b c)"; } diff --git a/Tests/CompileFeatures/cxx_variadic_templates.cpp b/Tests/CompileFeatures/cxx_variadic_templates.cpp index 3dc2570..6951230 100644 --- a/Tests/CompileFeatures/cxx_variadic_templates.cpp +++ b/Tests/CompileFeatures/cxx_variadic_templates.cpp @@ -35,7 +35,7 @@ struct eval }; template <template <typename...> class T, typename... U> -struct eval<T<U...> > +struct eval<T<U...>> { enum { @@ -62,11 +62,11 @@ struct D // Note: This test assumes that a compiler supporting this feature // supports static_assert. Add a workaround if that does not hold. -static_assert(eval<A<> >::Matched, "A Matches"); -static_assert(eval<A<int> >::Matched, "A Matches"); -static_assert(eval<A<int, char> >::Matched, "A Matches"); -static_assert(eval<B<int> >::Matched, "B Matches"); -static_assert(eval<C<int, char> >::Matched, "C Matches"); -static_assert(eval<D<int, char> >::Matched, "D Matches"); -static_assert(eval<D<int, char, bool> >::Matched, "D Matches"); -static_assert(eval<D<int, char, bool, double> >::Matched, "D Matches"); +static_assert(eval<A<>>::Matched, "A Matches"); +static_assert(eval<A<int>>::Matched, "A Matches"); +static_assert(eval<A<int, char>>::Matched, "A Matches"); +static_assert(eval<B<int>>::Matched, "B Matches"); +static_assert(eval<C<int, char>>::Matched, "C Matches"); +static_assert(eval<D<int, char>>::Matched, "D Matches"); +static_assert(eval<D<int, char, bool>>::Matched, "D Matches"); +static_assert(eval<D<int, char, bool, double>>::Matched, "D Matches"); diff --git a/Tests/Cuda/.clang-format b/Tests/Cuda/.clang-format deleted file mode 100644 index a77589a..0000000 --- a/Tests/Cuda/.clang-format +++ /dev/null @@ -1,9 +0,0 @@ ---- -# This configuration requires clang-format 3.8 or higher. -BasedOnStyle: Mozilla -AlignOperands: false -AlwaysBreakAfterReturnType: None -AlwaysBreakAfterDefinitionReturnType: None -ColumnLimit: 79 -Standard: Cpp11 -... diff --git a/Tests/CudaOnly/.clang-format b/Tests/CudaOnly/.clang-format deleted file mode 100644 index a77589a..0000000 --- a/Tests/CudaOnly/.clang-format +++ /dev/null @@ -1,9 +0,0 @@ ---- -# This configuration requires clang-format 3.8 or higher. -BasedOnStyle: Mozilla -AlignOperands: false -AlwaysBreakAfterReturnType: None -AlwaysBreakAfterDefinitionReturnType: None -ColumnLimit: 79 -Standard: Cpp11 -... diff --git a/Tests/FindEXPAT/CMakeLists.txt b/Tests/FindEXPAT/CMakeLists.txt new file mode 100644 index 0000000..a74174a --- /dev/null +++ b/Tests/FindEXPAT/CMakeLists.txt @@ -0,0 +1,10 @@ +add_test(NAME FindEXPAT.Test COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/FindEXPAT/Test" + "${CMake_BINARY_DIR}/Tests/FindEXPAT/Test" + ${build_generator_args} + --build-project TestFindEXPAT + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) diff --git a/Tests/FindEXPAT/Test/CMakeLists.txt b/Tests/FindEXPAT/Test/CMakeLists.txt new file mode 100644 index 0000000..5681f74 --- /dev/null +++ b/Tests/FindEXPAT/Test/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 3.9) +project(TestFindEXPAT C) +include(CTest) + +find_package(EXPAT REQUIRED) + +add_definitions(-DCMAKE_EXPECTED_EXPAT_VERSION="${EXPAT_VERSION_STRING}") + +add_executable(testexpat_tgt main.c) +target_link_libraries(testexpat_tgt EXPAT::EXPAT) +add_test(NAME testexpat_tgt COMMAND testexpat_tgt) + +add_executable(testexpat_var main.c) +target_include_directories(testexpat_var PRIVATE ${EXPAT_INCLUDE_DIRS}) +target_link_libraries(testexpat_var PRIVATE ${EXPAT_LIBRARIES}) +add_test(NAME testexpat_var COMMAND testexpat_var) diff --git a/Tests/FindEXPAT/Test/main.c b/Tests/FindEXPAT/Test/main.c new file mode 100644 index 0000000..94ee3ef --- /dev/null +++ b/Tests/FindEXPAT/Test/main.c @@ -0,0 +1,21 @@ +#include <expat.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +int main() +{ + XML_Expat_Version expat_version; + char expat_version_string[16]; + + expat_version = XML_ExpatVersionInfo(); + + snprintf(expat_version_string, 16, "%i.%i.%i", expat_version.major, + expat_version.minor, expat_version.micro); + + if (strcmp(expat_version_string, CMAKE_EXPECTED_EXPAT_VERSION) != 0) { + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} diff --git a/Tests/FindFreetype/CMakeLists.txt b/Tests/FindFreetype/CMakeLists.txt new file mode 100644 index 0000000..490c25b --- /dev/null +++ b/Tests/FindFreetype/CMakeLists.txt @@ -0,0 +1,10 @@ +add_test(NAME FindFreetype.Test COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/FindFreetype/Test" + "${CMake_BINARY_DIR}/Tests/FindFreetype/Test" + ${build_generator_args} + --build-project TestFindFreetype + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) diff --git a/Tests/FindFreetype/Test/CMakeLists.txt b/Tests/FindFreetype/Test/CMakeLists.txt new file mode 100644 index 0000000..bc869a1 --- /dev/null +++ b/Tests/FindFreetype/Test/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 3.9) +project(TestFindFreetype C) +include(CTest) + +find_package(Freetype REQUIRED) + +add_definitions(-DCMAKE_EXPECTED_FREETYPE_VERSION="${FREETYPE_VERSION_STRING}") + +add_executable(testfreetype_tgt main.c) +target_link_libraries(testfreetype_tgt Freetype::Freetype) +add_test(NAME testfreetype_tgt COMMAND testfreetype_tgt) + +add_executable(testfreetype_var main.c) +target_include_directories(testfreetype_var PRIVATE ${FREETYPE_INCLUDE_DIRS}) +target_link_libraries(testfreetype_var PRIVATE ${FREETYPE_LIBRARIES}) +add_test(NAME testfreetype_var COMMAND testfreetype_var) diff --git a/Tests/FindFreetype/Test/main.c b/Tests/FindFreetype/Test/main.c new file mode 100644 index 0000000..bb838a5 --- /dev/null +++ b/Tests/FindFreetype/Test/main.c @@ -0,0 +1,34 @@ +#include <ft2build.h> +#include <stdlib.h> +#include FT_FREETYPE_H +#include <string.h> + +int main() +{ + FT_Library library; + FT_Error error; + + error = FT_Init_FreeType(&library); + if (error) { + return EXIT_FAILURE; + } + + FT_Int major = 0; + FT_Int minor = 0; + FT_Int patch = 0; + FT_Library_Version(library, &major, &minor, &patch); + + char ft_version_string[16]; + snprintf(ft_version_string, 16, "%i.%i.%i", major, minor, patch); + + if (strcmp(ft_version_string, CMAKE_EXPECTED_FREETYPE_VERSION) != 0) { + return EXIT_FAILURE; + } + + error = FT_Done_FreeType(library); + if (error) { + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} diff --git a/Tests/FindGTest/Test/main.cxx b/Tests/FindGTest/Test/main.cxx index 0572a5d..19d2967 100644 --- a/Tests/FindGTest/Test/main.cxx +++ b/Tests/FindGTest/Test/main.cxx @@ -2,5 +2,7 @@ TEST(FindCMake, LinksAndRuns) { + using namespace testing; + EXPECT_FALSE(GTEST_FLAG(list_tests)); ASSERT_TRUE(true); } diff --git a/Tests/FindMPI/Test/CMakeLists.txt b/Tests/FindMPI/Test/CMakeLists.txt index 3910c25..efe8c62 100644 --- a/Tests/FindMPI/Test/CMakeLists.txt +++ b/Tests/FindMPI/Test/CMakeLists.txt @@ -20,12 +20,17 @@ foreach(c C CXX Fortran) endif() endforeach() +set(MPI_CXX_SKIP_MPICXX TRUE) +set(MPI_CXX_VALIDATE_SKIP_MPICXX TRUE) find_package(MPI REQUIRED) foreach(c C CXX Fortran) if(NOT "${MPI_TEST_${c}}") continue() endif() + if(${c} STREQUAL CXX AND MPI_MPICXX_FOUND) + message(FATAL_ERROR "Could not suppress MPI-2 C++ bindings for this MPI.") + endif() source_code_mapper_helper(${c}) add_executable(test_tgt_${c} ${MPITEST_SOURCE_FILE}) target_link_libraries(test_tgt_${c} MPI::MPI_${c}) diff --git a/Tests/FindOpenGL/CMakeLists.txt b/Tests/FindOpenGL/CMakeLists.txt index 9aa3aba..97c9e60 100644 --- a/Tests/FindOpenGL/CMakeLists.txt +++ b/Tests/FindOpenGL/CMakeLists.txt @@ -1,3 +1,9 @@ +if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMake_TEST_FindOpenGL_VND) + set(_vnd_testing TRUE) +else() + set(_vnd_testing FALSE) +endif() + add_test(NAME FindOpenGL.Test COMMAND ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> --build-and-test @@ -6,5 +12,6 @@ add_test(NAME FindOpenGL.Test COMMAND ${build_generator_args} --build-project TestFindOpenGL --build-options ${build_options} + -DOpenGL_TEST_VND=${_vnd_testing} --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> ) diff --git a/Tests/FindOpenGL/Test/CMakeLists.txt b/Tests/FindOpenGL/Test/CMakeLists.txt index cac3424..3b5ffee 100644 --- a/Tests/FindOpenGL/Test/CMakeLists.txt +++ b/Tests/FindOpenGL/Test/CMakeLists.txt @@ -1,14 +1,70 @@ -cmake_minimum_required(VERSION 3.7) +cmake_minimum_required(VERSION 3.9) project(TestFindOpenGL C) include(CTest) find_package(OpenGL REQUIRED) +# import target for GLU add_executable(test_tgt main.c) target_link_libraries(test_tgt OpenGL::GLU) add_test(NAME test_tgt COMMAND test_tgt) +# OPENGL_LIBRARIES should be whatever libraries are needed to link. add_executable(test_var main.c) target_include_directories(test_var PRIVATE ${OPENGL_INGLUDE_DIRS}) target_link_libraries(test_var PRIVATE ${OPENGL_LIBRARIES}) add_test(NAME test_var COMMAND test_var) + +# VND support adds an ::OpenGL import target. This can be used for OpenGL-only +# code (code that does not manipulate contexts, like our 'main.c'). Without +# VND, ::GL can be used for both context and non-context OpenGL code. +if(OpenGL_TEST_VND) + add_executable(test_comp_none main.c) + target_link_libraries(test_comp_none PRIVATE OpenGL::OpenGL) + add_test(NAME test_comp_none COMMAND test_comp_none) +else() + add_executable(test_comp_none main.c) + target_link_libraries(test_comp_none PRIVATE OpenGL::GL) + add_test(NAME test_comp_none COMMAND test_comp_none) +endif() + +# GLX +if(OpenGL_TEST_VND) + find_package(OpenGL REQUIRED COMPONENTS OpenGL GLX) + add_executable(test_comp_glx main.c) + target_link_libraries(test_comp_glx PRIVATE OpenGL::OpenGL OpenGL::GLX) + add_test(NAME test_comp_glx COMMAND test_comp_glx) +else() + # non-VND systems won't have it, but an optional search for GLX should still + # be okay. + find_package(OpenGL COMPONENTS GLX) + add_executable(test_comp_glx_novnd main.c) + target_link_libraries(test_comp_glx_novnd PRIVATE OpenGL::GL) + add_test(NAME test_comp_glx_novnd COMMAND test_comp_glx_novnd) +endif() + +# EGL is only available on Linux+GLVND at present. +if(OpenGL_TEST_VND) + find_package(OpenGL COMPONENTS OpenGL EGL) + if(OpenGL_EGL_FOUND) + add_executable(test_comp_egl main.c) + target_link_libraries(test_comp_egl PRIVATE OpenGL::OpenGL OpenGL::EGL) + add_test(NAME test_comp_egl COMMAND test_comp_egl) + # EGL-only code should not link to GLX. + execute_process(COMMAND ldd test_comp_egl + OUTPUT_VARIABLE LDD_OUT + ERROR_VARIABLE LDD_ERR) + if("${LDD_OUT}" MATCHES "GLX") + message(FATAL_ERROR "EGL-only code links to GLX!") + endif() + endif() + + # all three COMPONENTS together. + find_package(OpenGL COMPONENTS OpenGL EGL GLX) + if(OpenGL_EGL_FOUND AND OpenGL_GLX_FOUND) + add_executable(test_comp_both main.c) + target_link_libraries(test_comp_both PRIVATE OpenGL::OpenGL OpenGL::EGL + OpenGL::GLX) + add_test(NAME test_comp_both COMMAND test_comp_both) + endif() +endif() diff --git a/Tests/FindPatch/CMakeLists.txt b/Tests/FindPatch/CMakeLists.txt new file mode 100644 index 0000000..541f5bd --- /dev/null +++ b/Tests/FindPatch/CMakeLists.txt @@ -0,0 +1,8 @@ +add_test(NAME FindPatch.Test COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/FindPatch/Test" + "${CMake_BINARY_DIR}/Tests/FindPatch/Test" + ${build_generator_args} + --build-options ${build_options} +) diff --git a/Tests/FindPatch/Test/CMakeLists.txt b/Tests/FindPatch/Test/CMakeLists.txt new file mode 100644 index 0000000..f4cd621 --- /dev/null +++ b/Tests/FindPatch/Test/CMakeLists.txt @@ -0,0 +1,77 @@ +cmake_minimum_required(VERSION 3.8) +project(TestFindPatch VERSION 1.0 LANGUAGES NONE) + +macro(_check) + if(NOT EXISTS "${Patch_EXECUTABLE}") + message(FATAL_ERROR "Failed to lookup Patch_EXECUTABLE [${Patch_EXECUTABLE}]") + endif() + + if(NOT DEFINED PATCH_FOUND) + message(FATAL_ERROR "Variable PATCH_FOUND is not defined") + endif() + + # Is import target available ? + if(NOT TARGET Patch::patch) + message(FATAL_ERROR "Target Patch::patch is not defined") + endif() + + # Check Patch::patch imported location + get_property(_imported_location TARGET Patch::patch PROPERTY IMPORTED_LOCATION) + if(NOT "${Patch_EXECUTABLE}" STREQUAL "${_imported_location}") + message(FATAL_ERROR "\ +Patch_EXECUTABLE is expected to be equal to Patch::patch IMPORTED_LOCATION + Patch_EXECUTABLE [${Patch_EXECUTABLE}] + Patch::patch IMPORTED_LOCATION [${_imported_location}] +") + endif() + +endmacro() + +find_package(Patch REQUIRED) +_check() + +# Calling twice should not fail +find_package(Patch REQUIRED) +_check() + +add_custom_target(TestPatchVersion ALL + COMMAND ${Patch_EXECUTABLE} -v + ) + +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/QUOTE.txt.baseline" +[=[Because it's there. +- George Mallory, 1923 +]=] +) + +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/QUOTE.txt" "Because it's there.\n") + +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/quote-add-author.patch" +[=[diff --git a/QUOTE.txt b/QUOTE.txt +index b36681d..68059b3 100644 +--- a/QUOTE.txt ++++ b/QUOTE.txt +@@ -1 +1,2 @@ + Because it's there. ++- George Mallory +]=] +) + +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/quote-add-date.patch" +[=[diff --git a/QUOTE.txt b/QUOTE.txt +index 68059b3..c6f30c2 100644 +--- a/QUOTE.txt ++++ b/QUOTE.txt +@@ -1,2 +1,2 @@ + Because it's there. +-- George Mallory ++- George Mallory, 1923 +]=] +) + +add_custom_target(TestPatch ALL + COMMAND ${Patch_EXECUTABLE} -p1 -i quote-add-author.patch + COMMAND Patch::patch -p1 -i quote-add-date.patch + COMMAND ${CMAKE_COMMAND} -E compare_files QUOTE.txt QUOTE.txt.baseline + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + ) diff --git a/Tests/QtAutogen/mocDepends/CMakeLists.txt b/Tests/QtAutogen/mocDepends/CMakeLists.txt index d71d740..8217b8d 100644 --- a/Tests/QtAutogen/mocDepends/CMakeLists.txt +++ b/Tests/QtAutogen/mocDepends/CMakeLists.txt @@ -15,81 +15,137 @@ else() endif() include_directories(${CMAKE_CURRENT_BINARY_DIR}) +set(CSD ${CMAKE_CURRENT_SOURCE_DIR}) +set(CBD ${CMAKE_CURRENT_BINARY_DIR}) -# -- Test 1: Depend on generated header +# -- Test dependency on header generated by a custom command +# # The ORIGIN_autogen target must depend on the same *GENERATED* source files as # the ORIGIN target. This is a requirement to ensure that all files for the # ORIGIN target are generated before the ORIGIN_autogen target is built. # -# This tests the dependency of the mocDepends1_autogen target of mocDepends1 -# to the source file test1_object.hpp, which is *GENERATED* by a custom command. -# If mocDepends1_autogen gets built *before* or in *parallel* to the -# custom command, the build will fail. That's because test1_object.hpp, -# which is required by mocDepends1_autogen, is only valid after the +# This tests the dependency of the mocDepGenFile_autogen target of +# mocDepGenFile to the source file GenFile.hpp, which is *GENERATED* +# by a custom command. +# If mocDepGenFile_autogen gets built *before* or in *parallel* to the +# custom command, the build will fail. That's because GenFile.hpp, +# which is required by mocDepGenFile_autogen, is only valid after the # custom command has been completed. # # The sleep seconds artificially increase the build time of the custom command # to simulate a slow file generation process that takes longer to run than -# the build of the mocDepends1_autogen target. +# the build of the mocDepGenFile_autogen target. add_custom_command( - OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/test1_object.hpp - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/invalid.hpp.in ${CMAKE_CURRENT_BINARY_DIR}/test1_object.hpp + OUTPUT ${CBD}/GenFile.hpp + COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/object_invalid.hpp.in ${CBD}/GenFile.hpp COMMAND ${CMAKE_COMMAND} -E sleep 3 - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/object.hpp.in ${CMAKE_CURRENT_BINARY_DIR}/test1_object.hpp) + COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/object_valid.hpp.in ${CBD}/GenFile.hpp) + +add_executable(mocDepGenFile testGenFile.cpp ${CBD}/GenFile.hpp) +target_link_libraries(mocDepGenFile ${QT_CORE_TARGET}) +set_target_properties(mocDepGenFile PROPERTIES AUTOMOC TRUE) -add_executable(mocDepends1 test1.cpp ${CMAKE_CURRENT_BINARY_DIR}/test1_object.hpp) -target_link_libraries(mocDepends1 ${QT_CORE_TARGET}) -set_target_properties(mocDepends1 PROPERTIES AUTOMOC TRUE) -# -- Test 2: Depend on header generating target +# -- Test dependency on header generating custom target +# # The ORIGIN_autogen target must depend on the same user defined targets # as the ORIGIN target. This is a requirement to ensure that all files for the # ORIGIN target are generated before the ORIGIN_autogen target is built. # -# This tests the dependency of the mocDepends2_autogen target of mocDepends2 -# to the utility target mocDepends2Object. If mocDepends2_autogen gets built -# *before* or in *parallel* to mocDepends2Object, the build will fail. That's -# because test2_object.hpp, which is required by mocDepends2_autogen, -# is only valid after the mocDepends2Object build has been completed. +# This tests the dependency of the mocDepTarget_autogen target of +# mocDepTarget to the utility target mocDepTargetUtil. +# If mocDepTarget_autogen gets built *before* or in *parallel* to +# mocDepTargetUtil, the build will fail. That's +# because GenTarget.hpp, which is required by mocDepTarget_autogen, +# is only valid after the mocDepTargetUtil build has been completed. # -# The sleep seconds artificially increase the build time of mocDepends2Object +# The sleep seconds artificially increase the build time of mocDepTargetUtil # to simulate a slow utility target build that takes longer to run than -# the build of the mocDepends2_autogen target. -add_custom_target(mocDepends2Object - BYPRODUCTS ${CMAKE_CURRENT_BINARY_DIR}/test2_object.hpp - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/invalid.hpp.in ${CMAKE_CURRENT_BINARY_DIR}/test2_object.hpp +# the build of the mocDepTarget_autogen target. +add_custom_target(mocDepTargetUtil + BYPRODUCTS ${CBD}/GenTarget.hpp + COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/object_invalid.hpp.in ${CBD}/GenTarget.hpp COMMAND ${CMAKE_COMMAND} -E sleep 3 - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/object.hpp.in ${CMAKE_CURRENT_BINARY_DIR}/test2_object.hpp) + COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/object_valid.hpp.in ${CBD}/GenTarget.hpp) + +add_executable(mocDepTarget testGenTarget.cpp) +target_link_libraries(mocDepTarget ${QT_CORE_TARGET}) +set_target_properties(mocDepTarget PROPERTIES AUTOMOC TRUE) +add_dependencies(mocDepTarget mocDepTargetUtil) -add_executable(mocDepends2 test2.cpp) -target_link_libraries(mocDepends2 ${QT_CORE_TARGET}) -set_target_properties(mocDepends2 PROPERTIES AUTOMOC TRUE) -add_dependencies(mocDepends2 mocDepends2Object) # -- Test 3: Depend on generated linked library # The ORIGIN_autogen target must depend on the same linked libraries # as the ORIGIN target. This is a requirement to ensure that all files for the # ORIGIN target are generated before the ORIGIN_autogen target is built. # -# This tests the dependency of the mocDepends3_autogen target of mocDepends3 -# to the user generated library SimpleLib, which mocDepends3 links to. -# If mocDepends3_autogen gets built *before* or in *parallel* to SimpleLib, +# This tests the dependency of the mocDepGenLib_autogen target of mocDepGenLib +# to the user generated library SimpleLib, which mocDepGenLib links to. +# If mocDepGenLib_autogen gets built *before* or in *parallel* to SimpleLib, # the build will fail. That's because simpleLib.hpp, which is required by -# mocDepends3_autogen, is only valid after the SimpleLib build has been +# mocDepGenLib_autogen, is only valid after the SimpleLib build has been # completed. # # The sleep seconds artificially increase the build time of SimpleLib # to simulate a slow utility library build that takes longer to run than -# the build of the mocDepends3_autogen target. +# the build of the mocDepGenLib_autogen target. add_custom_command( - OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/simpleLib.hpp ${CMAKE_CURRENT_BINARY_DIR}/simpleLib.cpp - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/invalid.hpp.in ${CMAKE_CURRENT_BINARY_DIR}/simpleLib.hpp + OUTPUT ${CBD}/simpleLib.hpp ${CBD}/simpleLib.cpp + COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/object_invalid.hpp.in ${CBD}/simpleLib.hpp COMMAND ${CMAKE_COMMAND} -E sleep 3 - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/simpleLib.hpp.in ${CMAKE_CURRENT_BINARY_DIR}/simpleLib.hpp - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/simpleLib.cpp.in ${CMAKE_CURRENT_BINARY_DIR}/simpleLib.cpp) -add_library(SimpleLib STATIC ${CMAKE_CURRENT_BINARY_DIR}/simpleLib.hpp ${CMAKE_CURRENT_BINARY_DIR}/simpleLib.cpp) + COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/simpleLib.hpp.in ${CBD}/simpleLib.hpp + COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/simpleLib.cpp.in ${CBD}/simpleLib.cpp) +add_library(SimpleLib STATIC ${CBD}/simpleLib.hpp ${CBD}/simpleLib.cpp) target_link_libraries(SimpleLib ${QT_CORE_TARGET}) -add_executable(mocDepends3 test3.cpp) -target_link_libraries(mocDepends3 SimpleLib ${QT_CORE_TARGET}) -set_target_properties(mocDepends3 PROPERTIES AUTOMOC TRUE) +add_executable(mocDepGenLib testGenLib.cpp) +target_link_libraries(mocDepGenLib SimpleLib ${QT_CORE_TARGET}) +set_target_properties(mocDepGenLib PROPERTIES AUTOMOC TRUE) + + +# -- Test AUTOGEN_TARGET_DEPENDS with GENERATED file dependency +# +# This tests the dependency of the mocDepATDFile_autogen target of +# mocDepATDTarget to the utility target mocDepATDFileUtil. +# If mocDepATDFile_autogen gets built *before* or in *parallel* to +# mocDepATDFileUtil, the build will fail. That's +# because ATDFile.hpp, which is required by mocDepATDFile_autogen, +# is only valid after the mocDepATDFileUtil build has been completed. +# +# The sleep seconds artificially increase the build time of +# mocDepATDFileUtil to simulate a slow utility target build that takes +# longer to run than the build of the mocDepATDFile_autogen target. +add_custom_command( + OUTPUT ${CBD}/ATDFile.hpp + COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/object_invalid.hpp.in ${CBD}/ATDFile.hpp + COMMAND ${CMAKE_COMMAND} -E sleep 3 + COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/object_valid.hpp.in ${CBD}/ATDFile.hpp) + +add_executable(mocDepATDFile testATDFile.cpp) +target_link_libraries(mocDepATDFile ${QT_CORE_TARGET}) +set_target_properties(mocDepATDFile PROPERTIES AUTOMOC TRUE) +set_target_properties(mocDepATDFile PROPERTIES AUTOGEN_TARGET_DEPENDS ${CBD}/ATDFile.hpp) + + +# -- Test AUTOGEN_TARGET_DEPENDS with target dependency +# +# This tests the dependency of the mocDepATDTarget_autogen target of +# mocDepATDTarget to the utility target mocDepATDTargetUtil. +# If mocDepATDTarget_autogen gets built *before* or in *parallel* to +# mocDepATDTargetUtil, the build will fail. That's +# because ATDTarget.hpp, which is required by mocDepATDTarget_autogen, +# is only valid after the mocDepATDTargetUtil build has been completed. +# +# The sleep seconds artificially increase the build time of +# mocDepATDTargetUtil to simulate a slow utility target build that takes +# longer to run than the build of the mocDepATDTarget_autogen target. +add_custom_target(mocDepATDTargetUtil + BYPRODUCTS ${CBD}/ATDTarget.hpp + COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/object_invalid.hpp.in ${CBD}/ATDTarget.hpp + COMMAND ${CMAKE_COMMAND} -E sleep 3 + COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/object_valid.hpp.in ${CBD}/ATDTarget.hpp) + +add_executable(mocDepATDTarget testATDTarget.cpp) +target_link_libraries(mocDepATDTarget ${QT_CORE_TARGET}) +set_target_properties(mocDepATDTarget PROPERTIES AUTOMOC TRUE) +set_target_properties(mocDepATDTarget PROPERTIES AUTOGEN_TARGET_DEPENDS mocDepATDTargetUtil) diff --git a/Tests/QtAutogen/mocDepends/invalid.hpp.in b/Tests/QtAutogen/mocDepends/object_invalid.hpp.in index 854d9a1..854d9a1 100644 --- a/Tests/QtAutogen/mocDepends/invalid.hpp.in +++ b/Tests/QtAutogen/mocDepends/object_invalid.hpp.in diff --git a/Tests/QtAutogen/mocDepends/object.hpp.in b/Tests/QtAutogen/mocDepends/object_valid.hpp.in index f364f7c..f364f7c 100644 --- a/Tests/QtAutogen/mocDepends/object.hpp.in +++ b/Tests/QtAutogen/mocDepends/object_valid.hpp.in diff --git a/Tests/QtAutogen/mocDepends/test2.cpp b/Tests/QtAutogen/mocDepends/test2.cpp deleted file mode 100644 index 3fd845e..0000000 --- a/Tests/QtAutogen/mocDepends/test2.cpp +++ /dev/null @@ -1,9 +0,0 @@ - -#include "moc_test2_object.cpp" -#include "test2_object.hpp" - -int main() -{ - Object obj; - return 0; -} diff --git a/Tests/QtAutogen/mocDepends/testATDFile.cpp b/Tests/QtAutogen/mocDepends/testATDFile.cpp new file mode 100644 index 0000000..6bddfcd --- /dev/null +++ b/Tests/QtAutogen/mocDepends/testATDFile.cpp @@ -0,0 +1,9 @@ + +#include "ATDFile.hpp" +#include "moc_ATDFile.cpp" + +int main() +{ + Object obj; + return 0; +} diff --git a/Tests/QtAutogen/mocDepends/testATDTarget.cpp b/Tests/QtAutogen/mocDepends/testATDTarget.cpp new file mode 100644 index 0000000..831fc26 --- /dev/null +++ b/Tests/QtAutogen/mocDepends/testATDTarget.cpp @@ -0,0 +1,9 @@ + +#include "ATDTarget.hpp" +#include "moc_ATDTarget.cpp" + +int main() +{ + Object obj; + return 0; +} diff --git a/Tests/QtAutogen/mocDepends/test1.cpp b/Tests/QtAutogen/mocDepends/testGenFile.cpp index 002dfd8..7df6e13 100644 --- a/Tests/QtAutogen/mocDepends/test1.cpp +++ b/Tests/QtAutogen/mocDepends/testGenFile.cpp @@ -1,5 +1,5 @@ -#include "test1_object.hpp" +#include "GenFile.hpp" int main() { diff --git a/Tests/QtAutogen/mocDepends/test3.cpp b/Tests/QtAutogen/mocDepends/testGenLib.cpp index a009598..c14e159 100644 --- a/Tests/QtAutogen/mocDepends/test3.cpp +++ b/Tests/QtAutogen/mocDepends/testGenLib.cpp @@ -1,5 +1,5 @@ -#include "test3.hpp" +#include "testGenLib.hpp" int main() { @@ -8,5 +8,5 @@ int main() return 0; } -// AUTOMOC the SimpleLib header simpleLib.hpp +// Depend on and AUTOMOC the SimpleLib header simpleLib.hpp #include "moc_simpleLib.cpp" diff --git a/Tests/QtAutogen/mocDepends/test3.hpp b/Tests/QtAutogen/mocDepends/testGenLib.hpp index 408335b..408335b 100644 --- a/Tests/QtAutogen/mocDepends/test3.hpp +++ b/Tests/QtAutogen/mocDepends/testGenLib.hpp diff --git a/Tests/QtAutogen/mocDepends/testGenTarget.cpp b/Tests/QtAutogen/mocDepends/testGenTarget.cpp new file mode 100644 index 0000000..911076e --- /dev/null +++ b/Tests/QtAutogen/mocDepends/testGenTarget.cpp @@ -0,0 +1,9 @@ + +#include "GenTarget.hpp" +#include "moc_GenTarget.cpp" + +int main() +{ + Object obj; + return 0; +} diff --git a/Tests/QtAutogen/sameName/CMakeLists.txt b/Tests/QtAutogen/sameName/CMakeLists.txt index 4d2dcd9..f695875 100644 --- a/Tests/QtAutogen/sameName/CMakeLists.txt +++ b/Tests/QtAutogen/sameName/CMakeLists.txt @@ -17,7 +17,10 @@ add_executable(sameName main.cpp ) target_link_libraries(sameName ${QT_LIBRARIES}) -set_target_properties(sameName PROPERTIES AUTOMOC TRUE AUTORCC TRUE) +set_target_properties(sameName PROPERTIES + AUTOMOC TRUE + AUTOUIC TRUE + AUTORCC TRUE) # Set different compression levels if (QT_TEST_VERSION STREQUAL 4) diff --git a/Tests/QtAutogen/sameName/aaa/bbb/item.cpp b/Tests/QtAutogen/sameName/aaa/bbb/item.cpp index 20d0044..850206f 100644 --- a/Tests/QtAutogen/sameName/aaa/bbb/item.cpp +++ b/Tests/QtAutogen/sameName/aaa/bbb/item.cpp @@ -3,8 +3,20 @@ namespace aaa { namespace bbb { +class MocLocal : public QObject +{ + Q_OBJECT; + +public: + MocLocal() = default; + ~MocLocal() = default; +}; + void Item::go() { + MocLocal obj; } } } + +#include "aaa/bbb/item.moc" diff --git a/Tests/QtAutogen/sameName/aaa/item.cpp b/Tests/QtAutogen/sameName/aaa/item.cpp index 95dd3b6..e35d3d1 100644 --- a/Tests/QtAutogen/sameName/aaa/item.cpp +++ b/Tests/QtAutogen/sameName/aaa/item.cpp @@ -1,8 +1,22 @@ #include "item.hpp" +// Include ui_view.h only in header namespace aaa { +class MocLocal : public QObject +{ + Q_OBJECT; + +public: + MocLocal() = default; + ~MocLocal() = default; +}; + void Item::go() { + Ui_ViewAAA ui; + MocLocal obj; } } + +#include "aaa/item.moc" diff --git a/Tests/QtAutogen/sameName/aaa/item.hpp b/Tests/QtAutogen/sameName/aaa/item.hpp index b63466f..875f72f 100644 --- a/Tests/QtAutogen/sameName/aaa/item.hpp +++ b/Tests/QtAutogen/sameName/aaa/item.hpp @@ -2,6 +2,8 @@ #define AAA_ITEM_HPP #include <QObject> +// Include ui_view.h only in header +#include <aaa/ui_view.h> namespace aaa { diff --git a/Tests/QtAutogen/sameName/aaa/view.ui b/Tests/QtAutogen/sameName/aaa/view.ui new file mode 100644 index 0000000..0f09980 --- /dev/null +++ b/Tests/QtAutogen/sameName/aaa/view.ui @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>ViewAAA</class> + <widget class="QWidget" name="Base"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>400</width> + <height>300</height> + </rect> + </property> + <property name="windowTitle"> + <string>Form</string> + </property> + <layout class="QHBoxLayout" name="horizontalLayout"> + <item> + <widget class="QTreeView" name="treeView"/> + </item> + </layout> + </widget> + <resources/> + <connections/> +</ui> diff --git a/Tests/QtAutogen/sameName/bbb/aaa/item.cpp b/Tests/QtAutogen/sameName/bbb/aaa/item.cpp index ac4b2c2..7ad01c3 100644 --- a/Tests/QtAutogen/sameName/bbb/aaa/item.cpp +++ b/Tests/QtAutogen/sameName/bbb/aaa/item.cpp @@ -3,8 +3,20 @@ namespace bbb { namespace aaa { +class MocLocal : public QObject +{ + Q_OBJECT; + +public: + MocLocal() = default; + ~MocLocal() = default; +}; + void Item::go() { + MocLocal obj; } } } + +#include "bbb/aaa/item.moc" diff --git a/Tests/QtAutogen/sameName/bbb/item.cpp b/Tests/QtAutogen/sameName/bbb/item.cpp index f97a143..9ef128e 100644 --- a/Tests/QtAutogen/sameName/bbb/item.cpp +++ b/Tests/QtAutogen/sameName/bbb/item.cpp @@ -1,8 +1,23 @@ #include "item.hpp" +// Include ui_view.h only in source +#include <bbb/ui_view.h> namespace bbb { +class MocLocal : public QObject +{ + Q_OBJECT; + +public: + MocLocal() = default; + ~MocLocal() = default; +}; + void Item::go() { + Ui_ViewBBB ui; + MocLocal obj; } } + +#include "bbb/item.moc" diff --git a/Tests/QtAutogen/sameName/bbb/item.hpp b/Tests/QtAutogen/sameName/bbb/item.hpp index 5b7f985..d39a9d7 100644 --- a/Tests/QtAutogen/sameName/bbb/item.hpp +++ b/Tests/QtAutogen/sameName/bbb/item.hpp @@ -2,6 +2,7 @@ #define BBB_ITEM_HPP #include <QObject> +// Include ui_view.h only in source namespace bbb { diff --git a/Tests/QtAutogen/sameName/bbb/view.ui b/Tests/QtAutogen/sameName/bbb/view.ui new file mode 100644 index 0000000..a8f506e --- /dev/null +++ b/Tests/QtAutogen/sameName/bbb/view.ui @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>ViewBBB</class> + <widget class="QWidget" name="Base"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>400</width> + <height>300</height> + </rect> + </property> + <property name="windowTitle"> + <string>Form</string> + </property> + <layout class="QHBoxLayout" name="horizontalLayout"> + <item> + <widget class="QTreeView" name="treeView"/> + </item> + </layout> + </widget> + <resources/> + <connections/> +</ui> diff --git a/Tests/QtAutogen/sameName/ccc/item.cpp b/Tests/QtAutogen/sameName/ccc/item.cpp index d90b2b8..ab8a281 100644 --- a/Tests/QtAutogen/sameName/ccc/item.cpp +++ b/Tests/QtAutogen/sameName/ccc/item.cpp @@ -1,23 +1,25 @@ #include "item.hpp" +// Include ui_view.h in source and header +#include <ccc/ui_view.h> namespace ccc { -void Item::go() -{ -} - -class MocTest : public QObject +class MocLocal : public QObject { Q_OBJECT; - Q_SLOT - void go(); + +public: + MocLocal() = default; + ~MocLocal() = default; }; -void MocTest::go() +void Item::go() { + Ui_ViewCCC ui; + MocLocal obj; } } // Include own moc files -#include "item.moc" +#include "ccc/item.moc" #include "moc_item.cpp" diff --git a/Tests/QtAutogen/sameName/ccc/item.hpp b/Tests/QtAutogen/sameName/ccc/item.hpp index 96fcc24..20d9dd9 100644 --- a/Tests/QtAutogen/sameName/ccc/item.hpp +++ b/Tests/QtAutogen/sameName/ccc/item.hpp @@ -2,6 +2,8 @@ #define CCC_ITEM_HPP #include <QObject> +// Include ui_view.h in source and header +#include <ccc/ui_view.h> namespace ccc { diff --git a/Tests/QtAutogen/sameName/ccc/view.ui b/Tests/QtAutogen/sameName/ccc/view.ui new file mode 100644 index 0000000..7989c69 --- /dev/null +++ b/Tests/QtAutogen/sameName/ccc/view.ui @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>ViewCCC</class> + <widget class="QWidget" name="Base"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>400</width> + <height>300</height> + </rect> + </property> + <property name="windowTitle"> + <string>Form</string> + </property> + <layout class="QHBoxLayout" name="horizontalLayout"> + <item> + <widget class="QTreeView" name="treeView"/> + </item> + </layout> + </widget> + <resources/> + <connections/> +</ui> diff --git a/Tests/QtAutogen/sameName/item.cpp b/Tests/QtAutogen/sameName/item.cpp index e013cf3..3d1fbe7 100644 --- a/Tests/QtAutogen/sameName/item.cpp +++ b/Tests/QtAutogen/sameName/item.cpp @@ -1,5 +1,20 @@ #include "item.hpp" +// Include ui_view.h in source and header +#include <ui_view.h> + +class MocLocal : public QObject +{ + Q_OBJECT; + +public: + MocLocal() = default; + ~MocLocal() = default; +}; void Item::go() { + Ui_View ui; + MocLocal obj; } + +#include "item.moc" diff --git a/Tests/QtAutogen/sameName/item.hpp b/Tests/QtAutogen/sameName/item.hpp index 91bba3b..75e83f4 100644 --- a/Tests/QtAutogen/sameName/item.hpp +++ b/Tests/QtAutogen/sameName/item.hpp @@ -2,6 +2,8 @@ #define ITEM_HPP #include <QObject> +// Include ui_view.h in source and header +#include <ui_view.h> class Item : public QObject { diff --git a/Tests/QtAutogen/sameName/view.ui b/Tests/QtAutogen/sameName/view.ui new file mode 100644 index 0000000..2ffe734 --- /dev/null +++ b/Tests/QtAutogen/sameName/view.ui @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>View</class> + <widget class="QWidget" name="Base"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>400</width> + <height>300</height> + </rect> + </property> + <property name="windowTitle"> + <string>Form</string> + </property> + <layout class="QHBoxLayout" name="horizontalLayout"> + <item> + <widget class="QTreeView" name="treeView"/> + </item> + </layout> + </widget> + <resources/> + <connections/> +</ui> diff --git a/Tests/QtAutogenRerun/CMakeLists.txt b/Tests/QtAutogenRerun/CMakeLists.txt index 088025f..e72c191 100644 --- a/Tests/QtAutogenRerun/CMakeLists.txt +++ b/Tests/QtAutogenRerun/CMakeLists.txt @@ -36,204 +36,17 @@ else() endif() -# -- Test -# Dummy test to generate clean target +# Dummy executable to generate clean target add_executable(dummy dummy.cpp) # -- Test -# When a file listed in a .qrc file changes the target must be rebuilt -set(timeformat "%Y%j%H%M%S") -set(RCC_DEPENDS_SRC "${CMAKE_CURRENT_SOURCE_DIR}/rccDepends") -set(RCC_DEPENDS_BIN "${CMAKE_CURRENT_BINARY_DIR}/rccDepends") -configure_file(${RCC_DEPENDS_SRC}/res1a.qrc.in ${RCC_DEPENDS_BIN}/res1.qrc COPYONLY) -configure_file(${RCC_DEPENDS_SRC}/res2a.qrc.in ${RCC_DEPENDS_BIN}/res2.qrc.in COPYONLY) -try_compile(RCC_DEPENDS - "${RCC_DEPENDS_BIN}" - "${RCC_DEPENDS_SRC}" - rccDepends - CMAKE_FLAGS "-DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}" - "-DQT_TEST_VERSION=${QT_TEST_VERSION}" - "-DCMAKE_PREFIX_PATH=${Qt_PREFIX_DIR}" - OUTPUT_VARIABLE output -) -if (NOT RCC_DEPENDS) - message(SEND_ERROR "Initial build of rccDepends failed. Output: ${output}") -endif() -# Get name and timestamp of the output binary -file(STRINGS "${RCC_DEPENDS_BIN}/target.txt" targetList ENCODING UTF-8) -list(GET targetList 0 rccDependsBin) -file(TIMESTAMP "${rccDependsBin}" timeBegin "${timeformat}") -# Sleep, touch regular qrc input file, rebuild and compare timestamp -execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) # Ensure that the timestamp will change. -execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${RCC_DEPENDS_BIN}/res1/input.txt") -execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${RCC_DEPENDS_BIN}" RESULT_VARIABLE result) -if (result) - message(SEND_ERROR "Second build of rccDepends failed.") -endif() -file(TIMESTAMP "${rccDependsBin}" timeStep1 "${timeformat}") -if (NOT timeStep1 GREATER timeBegin) - message(SEND_ERROR "File (${rccDependsBin}) should have changed in the first step!") -endif() -# Sleep, update regular qrc file, rebuild and compare timestamp -execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) # Ensure that the timestamp will change. -configure_file(${RCC_DEPENDS_SRC}/res1b.qrc.in ${RCC_DEPENDS_BIN}/res1.qrc COPYONLY) -execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${RCC_DEPENDS_BIN}" RESULT_VARIABLE result) -if (result) - message(SEND_ERROR "Third build of rccDepends failed.") -endif() -file(TIMESTAMP "${rccDependsBin}" timeStep2 "${timeformat}") -if (NOT timeStep2 GREATER timeStep1) - message(SEND_ERROR "File (${rccDependsBin}) should have changed in the second step!") -endif() -# Sleep, touch regular qrc newly added input file, rebuild and compare timestamp -execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) # Ensure that the timestamp will change. -execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${RCC_DEPENDS_BIN}/res1/inputAdded.txt") -execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${RCC_DEPENDS_BIN}" RESULT_VARIABLE result) -if (result) - message(SEND_ERROR "Fourth build of rccDepends failed.") -endif() -file(TIMESTAMP "${rccDependsBin}" timeStep3 "${timeformat}") -if (NOT timeStep3 GREATER timeStep2) - message(SEND_ERROR "File (${rccDependsBin}) should have changed in the third step!") -endif() -# Sleep, touch generated qrc input file, rebuild and compare timestamp -execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) # Ensure that the timestamp will change. -execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${RCC_DEPENDS_BIN}/res2/input.txt") -execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${RCC_DEPENDS_BIN}" RESULT_VARIABLE result) -if (result) - message(SEND_ERROR "Fifth build of rccDepends failed.") -endif() -file(TIMESTAMP "${rccDependsBin}" timeStep4 "${timeformat}") -if (NOT timeStep4 GREATER timeStep3) - message(SEND_ERROR "File (${rccDependsBin}) should have changed in the fourth step!") -endif() -# Sleep, update generated qrc file, rebuild and compare timestamp -execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) # Ensure that the timestamp will change. -configure_file(${RCC_DEPENDS_SRC}/res2b.qrc.in ${RCC_DEPENDS_BIN}/res2.qrc.in COPYONLY) -execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${RCC_DEPENDS_BIN}" RESULT_VARIABLE result) -if (result) - message(SEND_ERROR "Sixth build of rccDepends failed.") -endif() -file(TIMESTAMP "${rccDependsBin}" timeStep5 "${timeformat}") -if (NOT timeStep5 GREATER timeStep4) - message(SEND_ERROR "File (${rccDependsBin}) should have changed in the fitfh step!") -endif() -# Sleep, touch generated qrc newly added input file, rebuild and compare timestamp -execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) # Ensure that the timestamp will change. -execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${RCC_DEPENDS_BIN}/res2/inputAdded.txt") -execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${RCC_DEPENDS_BIN}" RESULT_VARIABLE result) -if (result) - message(SEND_ERROR "Seventh build of rccDepends failed.") -endif() -file(TIMESTAMP "${rccDependsBin}" timeStep6 "${timeformat}") -if (NOT timeStep6 GREATER timeStep5) - message(SEND_ERROR "File (${rccDependsBin}) should have changed in the sixth step!") -endif() - - -# -- Test -# Ensure a repeated build succeeds when a header containing a QObject changes -set(timeformat "%Y%j%H%M%S") -configure_file(mocRerun/test1a.h.in mocRerun/test1.h COPYONLY) -try_compile(MOC_RERUN - "${CMAKE_CURRENT_BINARY_DIR}/mocRerun" - "${CMAKE_CURRENT_SOURCE_DIR}/mocRerun" - mocRerun - CMAKE_FLAGS "-DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}" - "-DQT_TEST_VERSION=${QT_TEST_VERSION}" - "-DCMAKE_PREFIX_PATH=${Qt_PREFIX_DIR}" - OUTPUT_VARIABLE output -) -if (NOT MOC_RERUN) - message(SEND_ERROR "Initial build of mocRerun failed. Output: ${output}") -endif() -# Get name and timestamp of the output binary -file(STRINGS "${CMAKE_CURRENT_BINARY_DIR}/mocRerun/target1.txt" target1List ENCODING UTF-8) -list(GET target1List 0 binFile) -file(TIMESTAMP "${binFile}" timeBegin "${timeformat}") -# Change file content and rebuild -execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) -configure_file(mocRerun/test1b.h.in mocRerun/test1.h COPYONLY) -execute_process(COMMAND "${CMAKE_COMMAND}" --build . - WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/mocRerun" - RESULT_VARIABLE mocRerun_result - ) -if (mocRerun_result) - message(SEND_ERROR "Second build of mocRerun failed.") -endif() -# Compare timestamps -file(TIMESTAMP "${binFile}" timeStep1 "${timeformat}") -if (NOT timeStep1 GREATER timeBegin) - message(SEND_ERROR "File (${binFile}) should have changed in the first step!") -endif() - +include("mocRerun.cmake") # -- Test # Tests Q_PLUGIN_METADATA json file change detection if (NOT QT_TEST_VERSION STREQUAL 4) - try_compile(MOC_PLUGIN - "${CMAKE_CURRENT_BINARY_DIR}/mocPlugin" - "${CMAKE_CURRENT_SOURCE_DIR}/mocPlugin" - mocPlugin - CMAKE_FLAGS "-DQT_TEST_VERSION=${QT_TEST_VERSION}" - "-DCMAKE_PREFIX_PATH=${Qt_PREFIX_DIR}" - OUTPUT_VARIABLE output - ) - if (NOT MOC_PLUGIN) - message(SEND_ERROR "Initial build of mocPlugin failed. Output: ${output}") - endif() - - set(timeformat "%Y%j%H%M%S") - set(mocPlugSrcDir "${CMAKE_CURRENT_SOURCE_DIR}/mocPlugin") - set(mocPlugBinDir "${CMAKE_CURRENT_BINARY_DIR}/mocPlugin") - find_library(plAFile "PlugA" PATHS "${mocPlugBinDir}/Debug" "${mocPlugBinDir}" NO_DEFAULT_PATH) - find_library(plBFile "PlugB" PATHS "${mocPlugBinDir}/Debug" "${mocPlugBinDir}" NO_DEFAULT_PATH) - find_library(plCFile "PlugC" PATHS "${mocPlugBinDir}/Debug" "${mocPlugBinDir}" NO_DEFAULT_PATH) - find_library(plDFile "PlugD" PATHS "${mocPlugBinDir}/Debug" "${mocPlugBinDir}" NO_DEFAULT_PATH) - - file(TIMESTAMP "${plAFile}" plABefore "${timeformat}") - file(TIMESTAMP "${plBFile}" plBBefore "${timeformat}") - file(TIMESTAMP "${plCFile}" plCBefore "${timeformat}") - file(TIMESTAMP "${plDFile}" plDBefore "${timeformat}") - - # Ensure that the timestamp will change and change the json files - execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) - configure_file("${mocPlugSrcDir}/jsonIn/StyleD.json" "${mocPlugBinDir}/jsonFiles/StyleC.json") - configure_file("${mocPlugSrcDir}/jsonIn/StyleC.json" "${mocPlugBinDir}/jsonFiles/sub/StyleD.json") - execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${mocPlugBinDir}") - - file(TIMESTAMP "${plAFile}" plAAfter "${timeformat}") - file(TIMESTAMP "${plBFile}" plBAfter "${timeformat}") - file(TIMESTAMP "${plCFile}" plCAfter "${timeformat}") - file(TIMESTAMP "${plDFile}" plDAfter "${timeformat}") - - if (plAAfter GREATER plABefore) - message(SEND_ERROR "file (${plAFile}) should not have changed!") - endif() - if (plBAfter GREATER plBBefore) - message(SEND_ERROR "file (${plBFile}) should not have changed!") - endif() - if (NOT plCAfter GREATER plCBefore) - message(SEND_ERROR "file (${plCFile}) should have changed!") - endif() - if (NOT plDAfter GREATER plDBefore) - message(SEND_ERROR "file (${plDFile}) should have changed!") - endif() - - # Test custom macro - file(TIMESTAMP "${plCFile}" plCBefore "${timeformat}") - file(TIMESTAMP "${plDFile}" plDBefore "${timeformat}") - execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) - configure_file("${mocPlugSrcDir}/jsonIn/StyleD.json" "${mocPlugBinDir}/jsonFiles/StyleC_Custom.json") - configure_file("${mocPlugSrcDir}/jsonIn/StyleC.json" "${mocPlugBinDir}/jsonFiles/sub/StyleD_Custom.json") - execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${mocPlugBinDir}") - file(TIMESTAMP "${plCFile}" plCAfter "${timeformat}") - file(TIMESTAMP "${plDFile}" plDAfter "${timeformat}") - if (NOT plCAfter GREATER plCBefore) - message(SEND_ERROR "file (${plCFile}) should have changed!") - endif() - if (NOT plDAfter GREATER plDBefore) - message(SEND_ERROR "file (${plDFile}) should have changed!") - endif() - + include("mocPlugin.cmake") endif() + +# -- Test +include("rccDepends.cmake") diff --git a/Tests/QtAutogenRerun/mocPlugin.cmake b/Tests/QtAutogenRerun/mocPlugin.cmake new file mode 100644 index 0000000..7ad5ccb --- /dev/null +++ b/Tests/QtAutogenRerun/mocPlugin.cmake @@ -0,0 +1,96 @@ + +# Utility variables +set(timeformat "%Y%j%H%M%S") +set(mocPlugSrcDir "${CMAKE_CURRENT_SOURCE_DIR}/mocPlugin") +set(mocPlugBinDir "${CMAKE_CURRENT_BINARY_DIR}/mocPlugin") + +# Initial buid +try_compile(MOC_PLUGIN + "${mocPlugBinDir}" + "${mocPlugSrcDir}" + mocPlugin + CMAKE_FLAGS "-DQT_TEST_VERSION=${QT_TEST_VERSION}" + "-DCMAKE_PREFIX_PATH=${Qt_PREFIX_DIR}" + OUTPUT_VARIABLE output +) +if (NOT MOC_PLUGIN) + message(SEND_ERROR "Initial build of mocPlugin failed. Output: ${output}") +endif() + +find_library(plAFile "PlugA" PATHS "${mocPlugBinDir}/Debug" "${mocPlugBinDir}" NO_DEFAULT_PATH) +find_library(plBFile "PlugB" PATHS "${mocPlugBinDir}/Debug" "${mocPlugBinDir}" NO_DEFAULT_PATH) +find_library(plCFile "PlugC" PATHS "${mocPlugBinDir}/Debug" "${mocPlugBinDir}" NO_DEFAULT_PATH) +find_library(plDFile "PlugD" PATHS "${mocPlugBinDir}/Debug" "${mocPlugBinDir}" NO_DEFAULT_PATH) +find_library(plEFile "PlugE" PATHS "${mocPlugBinDir}/Debug" "${mocPlugBinDir}" NO_DEFAULT_PATH) + +# - Ensure that the timestamp will change. +# - Change the json files referenced by Q_PLUGIN_METADATA +# - Rebuild +file(TIMESTAMP "${plAFile}" plABefore "${timeformat}") +file(TIMESTAMP "${plBFile}" plBBefore "${timeformat}") +file(TIMESTAMP "${plCFile}" plCBefore "${timeformat}") +file(TIMESTAMP "${plDFile}" plDBefore "${timeformat}") +file(TIMESTAMP "${plEFile}" plEBefore "${timeformat}") + +execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) +configure_file("${mocPlugSrcDir}/jsonIn/StyleD.json" "${mocPlugBinDir}/jsonFiles/StyleC.json") +configure_file("${mocPlugSrcDir}/jsonIn/StyleE.json" "${mocPlugBinDir}/jsonFiles/sub/StyleD.json") +configure_file("${mocPlugSrcDir}/jsonIn/StyleC.json" "${mocPlugBinDir}/jsonFiles/StyleE.json") +execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${mocPlugBinDir}") + +file(TIMESTAMP "${plAFile}" plAAfter "${timeformat}") +file(TIMESTAMP "${plBFile}" plBAfter "${timeformat}") +file(TIMESTAMP "${plCFile}" plCAfter "${timeformat}") +file(TIMESTAMP "${plDFile}" plDAfter "${timeformat}") +file(TIMESTAMP "${plEFile}" plEAfter "${timeformat}") + +if (plAAfter GREATER plABefore) + message(SEND_ERROR "file (${plAFile}) should not have changed!") +endif() +if (plBAfter GREATER plBBefore) + message(SEND_ERROR "file (${plBFile}) should not have changed!") +endif() +if (NOT plCAfter GREATER plCBefore) + message(SEND_ERROR "file (${plCFile}) should have changed!") +endif() +if (NOT plDAfter GREATER plDBefore) + message(SEND_ERROR "file (${plDFile}) should have changed!") +endif() +if (NOT plEAfter GREATER plEBefore) + # There's a bug in Ninja on Windows + # https://gitlab.kitware.com/cmake/cmake/issues/16776 + if(NOT ("${CMAKE_GENERATOR}" MATCHES "Ninja")) + message(SEND_ERROR "file (${plEFile}) should have changed!") + endif() +endif() + +# - Ensure that the timestamp will change. +# - Change the json files referenced by A_CUSTOM_MACRO +# - Rebuild +file(TIMESTAMP "${plCFile}" plCBefore "${timeformat}") +file(TIMESTAMP "${plDFile}" plDBefore "${timeformat}") +file(TIMESTAMP "${plEFile}" plEBefore "${timeformat}") + +execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) +configure_file("${mocPlugSrcDir}/jsonIn/StyleE.json" "${mocPlugBinDir}/jsonFiles/StyleC_Custom.json") +configure_file("${mocPlugSrcDir}/jsonIn/StyleC.json" "${mocPlugBinDir}/jsonFiles/sub/StyleD_Custom.json") +configure_file("${mocPlugSrcDir}/jsonIn/StyleD.json" "${mocPlugBinDir}/jsonFiles/StyleE_Custom.json") +execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${mocPlugBinDir}") + +file(TIMESTAMP "${plCFile}" plCAfter "${timeformat}") +file(TIMESTAMP "${plDFile}" plDAfter "${timeformat}") +file(TIMESTAMP "${plEFile}" plEAfter "${timeformat}") + +if (NOT plCAfter GREATER plCBefore) + message(SEND_ERROR "file (${plCFile}) should have changed!") +endif() +if (NOT plDAfter GREATER plDBefore) + message(SEND_ERROR "file (${plDFile}) should have changed!") +endif() +if (NOT plEAfter GREATER plEBefore) + # There's a bug in Ninja on Windows + # https://gitlab.kitware.com/cmake/cmake/issues/16776 + if(NOT ("${CMAKE_GENERATOR}" MATCHES "Ninja")) + message(SEND_ERROR "file (${plEFile}) should have changed!") + endif() +endif() diff --git a/Tests/QtAutogenRerun/mocPlugin/CMakeLists.txt b/Tests/QtAutogenRerun/mocPlugin/CMakeLists.txt index 9b224fb..b7cc5e9 100644 --- a/Tests/QtAutogenRerun/mocPlugin/CMakeLists.txt +++ b/Tests/QtAutogenRerun/mocPlugin/CMakeLists.txt @@ -16,9 +16,11 @@ if(Qt5_POSITION_INDEPENDENT_CODE AND CMAKE_CXX_COMPILE_OPTIONS_PIC) endif() configure_file(jsonIn/StyleC.json jsonFiles/StyleC.json) -configure_file(jsonIn/StyleD.json jsonFiles/sub/StyleD.json) configure_file(jsonIn/StyleC.json jsonFiles/StyleC_Custom.json) +configure_file(jsonIn/StyleD.json jsonFiles/sub/StyleD.json) configure_file(jsonIn/StyleD.json jsonFiles/sub/StyleD_Custom.json) +configure_file(jsonIn/StyleE.json jsonFiles/StyleE.json) +configure_file(jsonIn/StyleE.json jsonFiles/StyleE_Custom.json) # Enable automoc set(CMAKE_AUTOMOC TRUE) diff --git a/Tests/QtAutogenRerun/mocPlugin/StyleA.hpp b/Tests/QtAutogenRerun/mocPlugin/StyleA.hpp index 1b6154d..35158a4 100644 --- a/Tests/QtAutogenRerun/mocPlugin/StyleA.hpp +++ b/Tests/QtAutogenRerun/mocPlugin/StyleA.hpp @@ -1,13 +1,13 @@ #ifndef STYLEA_HPP #define STYLEA_HPP -#include "StyleCommon.hpp" +#include "UtilityMacros.hpp" #include <QStylePlugin> class StyleA : public QStylePlugin { Q_OBJECT - // Json file in local directory + // Json file in source local directory Q_PLUGIN_METADATA(IID "org.styles.A" FILE "StyleA.json") A_CUSTOM_MACRO(SomeArg, "StyleA_Custom.json", AnotherArg) public: diff --git a/Tests/QtAutogenRerun/mocPlugin/StyleB.hpp b/Tests/QtAutogenRerun/mocPlugin/StyleB.hpp index 163c9b2..15b79c5 100644 --- a/Tests/QtAutogenRerun/mocPlugin/StyleB.hpp +++ b/Tests/QtAutogenRerun/mocPlugin/StyleB.hpp @@ -1,13 +1,13 @@ #ifndef STYLEB_HPP #define STYLEB_HPP -#include "StyleCommon.hpp" +#include "UtilityMacros.hpp" #include <QStylePlugin> class StyleB : public QStylePlugin { Q_OBJECT - // Json file in local subdirectory + // Json file in source local subdirectory Q_PLUGIN_METADATA(IID "org.styles.B" FILE "jsonIn/StyleB.json") A_CUSTOM_MACRO(SomeArg, "jsonIn/StyleB_Custom.json", AnotherArg) public: diff --git a/Tests/QtAutogenRerun/mocPlugin/StyleC.hpp b/Tests/QtAutogenRerun/mocPlugin/StyleC.hpp index 52a887a..b0a4115 100644 --- a/Tests/QtAutogenRerun/mocPlugin/StyleC.hpp +++ b/Tests/QtAutogenRerun/mocPlugin/StyleC.hpp @@ -1,7 +1,7 @@ #ifndef STYLEC_HPP #define STYLEC_HPP -#include "StyleCommon.hpp" +#include "UtilityMacros.hpp" #include <QStylePlugin> class StyleC : public QStylePlugin diff --git a/Tests/QtAutogenRerun/mocPlugin/StyleD.hpp b/Tests/QtAutogenRerun/mocPlugin/StyleD.hpp index df8a439..9696aaa 100644 --- a/Tests/QtAutogenRerun/mocPlugin/StyleD.hpp +++ b/Tests/QtAutogenRerun/mocPlugin/StyleD.hpp @@ -1,7 +1,7 @@ #ifndef STYLED_HPP #define STYLED_HPP -#include "StyleCommon.hpp" +#include "UtilityMacros.hpp" #include <QStylePlugin> class StyleD : public QStylePlugin diff --git a/Tests/QtAutogenRerun/mocPlugin/StyleE.cpp b/Tests/QtAutogenRerun/mocPlugin/StyleE.cpp index 8fc9a7f..3448319 100644 --- a/Tests/QtAutogenRerun/mocPlugin/StyleE.cpp +++ b/Tests/QtAutogenRerun/mocPlugin/StyleE.cpp @@ -4,3 +4,6 @@ QStyle* StyleE::create(const QString& key) { return 0; } + +// AUTOMOC the StyleEInclude.hpp header +#include "moc_StyleEInclude.cpp" diff --git a/Tests/QtAutogenRerun/mocPlugin/StyleE.hpp b/Tests/QtAutogenRerun/mocPlugin/StyleE.hpp index e7915a8..a069034 100644 --- a/Tests/QtAutogenRerun/mocPlugin/StyleE.hpp +++ b/Tests/QtAutogenRerun/mocPlugin/StyleE.hpp @@ -1,17 +1,10 @@ #ifndef STYLEE_HPP #define STYLEE_HPP -#include "StyleCommon.hpp" -#include <QStylePlugin> - -class StyleE : public QStylePlugin -{ - Q_OBJECT - // No Json file - Q_PLUGIN_METADATA(IID "org.styles.E") - A_CUSTOM_MACRO(SomeArg, InvalidFileArg, AnotherArg) -public: - QStyle* create(const QString& key); -}; +// The included file is not in the sources list and won't be detected by +// AUTOMOC source file with the same base name. +// It is registered to AUTOMOCed via a moc_<NAME>.cpp include in StyleE.cpp +// though. +#include "StyleEInclude.hpp" #endif diff --git a/Tests/QtAutogenRerun/mocPlugin/StyleEInclude.hpp b/Tests/QtAutogenRerun/mocPlugin/StyleEInclude.hpp new file mode 100644 index 0000000..f9734db --- /dev/null +++ b/Tests/QtAutogenRerun/mocPlugin/StyleEInclude.hpp @@ -0,0 +1,17 @@ +#ifndef STYLEE_INCLUDE_HPP +#define STYLEE_INCLUDE_HPP + +#include "UtilityMacros.hpp" +#include <QStylePlugin> + +class StyleE : public QStylePlugin +{ + Q_OBJECT + // Json files in global root directory + Q_PLUGIN_METADATA(IID "org.styles.E" FILE "StyleE.json") + A_CUSTOM_MACRO(SomeArg, "StyleE_Custom.json", AnotherArg) +public: + QStyle* create(const QString& key); +}; + +#endif diff --git a/Tests/QtAutogenRerun/mocPlugin/StyleCommon.hpp b/Tests/QtAutogenRerun/mocPlugin/UtilityMacros.hpp index f1a7ec6..53a4284 100644 --- a/Tests/QtAutogenRerun/mocPlugin/StyleCommon.hpp +++ b/Tests/QtAutogenRerun/mocPlugin/UtilityMacros.hpp @@ -1,5 +1,5 @@ -#ifndef STYLECOMMON_HPP -#define STYLECOMMON_HPP +#ifndef UTILITYMACROS_HPP +#define UTILITYMACROS_HPP // Empty test macro definition #define A_CUSTOM_MACRO(name, jsonFile, pluginRegistrations) diff --git a/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleB.json b/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleB.json index 129cac4..cd155dc 100644 --- a/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleB.json +++ b/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleB.json @@ -1 +1 @@ -{ "Keys": [ "Rocket", "StarbusterB" ] } +{ "Keys": [ "Red", "Green" ] } diff --git a/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleE.json b/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleE.json new file mode 100644 index 0000000..5412c94 --- /dev/null +++ b/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleE.json @@ -0,0 +1 @@ +{ "Keys": [ "Floor", "Ceiling" ] } diff --git a/Tests/QtAutogenRerun/mocRerun.cmake b/Tests/QtAutogenRerun/mocRerun.cmake new file mode 100644 index 0000000..a92912b --- /dev/null +++ b/Tests/QtAutogenRerun/mocRerun.cmake @@ -0,0 +1,60 @@ + +set(timeformat "%Y%j%H%M%S") +set(mocRerunSrcDir "${CMAKE_CURRENT_SOURCE_DIR}/mocRerun") +set(mocRerunBinDir "${CMAKE_CURRENT_BINARY_DIR}/mocRerun") + +# Initial build +configure_file("${mocRerunSrcDir}/test1a.h.in" "${mocRerunBinDir}/test1.h" COPYONLY) +try_compile(MOC_RERUN + "${mocRerunBinDir}" + "${mocRerunSrcDir}" + mocRerun + CMAKE_FLAGS "-DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}" + "-DQT_TEST_VERSION=${QT_TEST_VERSION}" + "-DCMAKE_PREFIX_PATH=${Qt_PREFIX_DIR}" + OUTPUT_VARIABLE output +) +if (NOT MOC_RERUN) + message(SEND_ERROR "Initial build of mocRerun failed. Output: ${output}") +endif() +# Get name of the output binary +file(STRINGS "${mocRerunBinDir}/mocRerun.txt" mocRerunList ENCODING UTF-8) +list(GET mocRerunList 0 mocRerunBin) + +message("Changing the header content for a MOC rerun") +# - Acquire binary timestamps before the build +file(TIMESTAMP "${mocRerunBin}" timeBefore "${timeformat}") +# - Ensure that the timestamp will change +# - Change header file content and rebuild +# - Rebuild +execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) +configure_file("${mocRerunSrcDir}/test1b.h.in" "${mocRerunBinDir}/test1.h" COPYONLY) +execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${mocRerunBinDir}" RESULT_VARIABLE result ) +if (result) + message(SEND_ERROR "Second build of mocRerun failed.") +endif() +# - Acquire binary timestamps after the build +file(TIMESTAMP "${mocRerunBin}" timeAfter "${timeformat}") +# - Test if timestamps changed +if (NOT timeAfter GREATER timeBefore) + message(SEND_ERROR "File (${mocRerunBin}) should have changed!") +endif() + + +message("Changing nothing for a MOC rerun") +# - Acquire binary timestamps before the build +file(TIMESTAMP "${mocRerunBin}" timeBefore "${timeformat}") +# - Ensure that the timestamp would change +# - Change nothing +# - Rebuild +execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) +execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${mocRerunBinDir}" RESULT_VARIABLE result ) +if (result) + message(SEND_ERROR "Third build of mocRerun failed.") +endif() +# - Acquire binary timestamps after the build +file(TIMESTAMP "${mocRerunBin}" timeAfter "${timeformat}") +# - Test if timestamps changed +if (timeAfter GREATER timeBefore) + message(SEND_ERROR "File (${mocRerunBin}) should not have changed!") +endif() diff --git a/Tests/QtAutogenRerun/mocRerun/CMakeLists.txt b/Tests/QtAutogenRerun/mocRerun/CMakeLists.txt index 7380bdd..bafd9cf 100644 --- a/Tests/QtAutogenRerun/mocRerun/CMakeLists.txt +++ b/Tests/QtAutogenRerun/mocRerun/CMakeLists.txt @@ -19,17 +19,15 @@ set(CMAKE_AUTORCC ON) # Generated source file add_custom_command(OUTPUT main.cpp - COMMAND ${CMAKE_COMMAND} -E sleep 2 - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp.in ${CMAKE_CURRENT_BINARY_DIR}/main.cpp - ) + COMMAND ${CMAKE_COMMAND} -E sleep 2 + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp.in ${CMAKE_CURRENT_BINARY_DIR}/main.cpp) add_executable(mocRerun ${CMAKE_CURRENT_BINARY_DIR}/test1.h ${CMAKE_CURRENT_BINARY_DIR}/main.cpp - res1.qrc - ) + res1.qrc) target_include_directories(mocRerun PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) target_link_libraries(mocRerun ${QT_CORE_TARGET}) # Write target name to text file add_custom_command(TARGET mocRerun POST_BUILD COMMAND - ${CMAKE_COMMAND} -E echo "$<TARGET_FILE:mocRerun>" > target1.txt) + ${CMAKE_COMMAND} -E echo "$<TARGET_FILE:mocRerun>" > mocRerun.txt) diff --git a/Tests/QtAutogenRerun/rccDepends.cmake b/Tests/QtAutogenRerun/rccDepends.cmake new file mode 100644 index 0000000..68e1482 --- /dev/null +++ b/Tests/QtAutogenRerun/rccDepends.cmake @@ -0,0 +1,131 @@ +# When a .qrc or a file listed in a .qrc file changes, +# the target must be rebuilt +set(timeformat "%Y%j%H%M%S") +set(rccDepSD "${CMAKE_CURRENT_SOURCE_DIR}/rccDepends") +set(rccDepBD "${CMAKE_CURRENT_BINARY_DIR}/rccDepends") + +# Initial build +configure_file(${rccDepSD}/resPlainA.qrc.in ${rccDepBD}/resPlain.qrc COPYONLY) +configure_file(${rccDepSD}/resGenA.qrc.in ${rccDepBD}/resGen.qrc.in COPYONLY) +try_compile(RCC_DEPENDS + "${rccDepBD}" + "${rccDepSD}" + rccDepends + CMAKE_FLAGS "-DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}" + "-DQT_TEST_VERSION=${QT_TEST_VERSION}" + "-DCMAKE_PREFIX_PATH=${Qt_PREFIX_DIR}" + OUTPUT_VARIABLE output +) +if (NOT RCC_DEPENDS) + message(SEND_ERROR "Initial build of rccDepends failed. Output: ${output}") +endif() + +# Get name of the output binaries +file(STRINGS "${rccDepBD}/targetPlain.txt" targetListPlain ENCODING UTF-8) +file(STRINGS "${rccDepBD}/targetGen.txt" targetListGen ENCODING UTF-8) +list(GET targetListPlain 0 rccDepBinPlain) +list(GET targetListGen 0 rccDepBinGen) +message("Target that uses a plain .qrc file is:\n ${rccDepBinPlain}") +message("Target that uses a GENERATED .qrc file is:\n ${rccDepBinGen}") + + +message("Changing a resource files listed in the .qrc file") +# - Acquire binary timestamps before the build +file(TIMESTAMP "${rccDepBinPlain}" rdPlainBefore "${timeformat}") +file(TIMESTAMP "${rccDepBinGen}" rdGenBefore "${timeformat}") +# - Ensure that the timestamp will change +# - Change a resource files listed in the .qrc file +# - Rebuild +execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) +execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${rccDepBD}/resPlain/input.txt") +execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${rccDepBD}/resGen/input.txt") +execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${rccDepBD}" RESULT_VARIABLE result) +if (result) + message(SEND_ERROR "Second build of rccDepends failed.") +endif() +# - Acquire binary timestamps after the build +file(TIMESTAMP "${rccDepBinPlain}" rdPlainAfter "${timeformat}") +file(TIMESTAMP "${rccDepBinGen}" rdGenAfter "${timeformat}") +# - Test if timestamps changed +if (NOT rdPlainAfter GREATER rdPlainBefore) + message(SEND_ERROR "Plain .qrc binary ${rccDepBinPlain}) should have changed!") +endif() +if (NOT rdGenAfter GREATER rdGenBefore) + message(SEND_ERROR "GENERATED .qrc binary ${rccDepBinGen} should have changed!") +endif() + + +message("Changing a the .qrc file") +# - Acquire binary timestamps before the build +file(TIMESTAMP "${rccDepBinPlain}" rdPlainBefore "${timeformat}") +file(TIMESTAMP "${rccDepBinGen}" rdGenBefore "${timeformat}") +# - Ensure that the timestamp will change +# - Change the .qrc file +# - Rebuild +execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) +configure_file(${rccDepSD}/resPlainB.qrc.in ${rccDepBD}/resPlain.qrc COPYONLY) +configure_file(${rccDepSD}/resGenB.qrc.in ${rccDepBD}/resGen.qrc.in COPYONLY) +execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${rccDepBD}" RESULT_VARIABLE result) +if (result) + message(SEND_ERROR "Third build of rccDepends failed.") +endif() +# - Acquire binary timestamps after the build +file(TIMESTAMP "${rccDepBinPlain}" rdPlainAfter "${timeformat}") +file(TIMESTAMP "${rccDepBinGen}" rdGenAfter "${timeformat}") +# - Test if timestamps changed +if (NOT rdPlainAfter GREATER rdPlainBefore) + message(SEND_ERROR "Plain .qrc binary ${rccDepBinPlain}) should have changed!") +endif() +if (NOT rdGenAfter GREATER rdGenBefore) + message(SEND_ERROR "GENERATED .qrc binary ${rccDepBinGen} should have changed!") +endif() + + +message("Changing a newly added resource files listed in the .qrc file") +# - Acquire binary timestamps before the build +file(TIMESTAMP "${rccDepBinPlain}" rdPlainBefore "${timeformat}") +file(TIMESTAMP "${rccDepBinGen}" rdGenBefore "${timeformat}") +# - Ensure that the timestamp will change +# - Change a newly added resource files listed in the .qrc file +# - Rebuild +execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) +execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${rccDepBD}/resPlain/inputAdded.txt") +execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${rccDepBD}/resGen/inputAdded.txt") +execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${rccDepBD}" RESULT_VARIABLE result) +if (result) + message(SEND_ERROR "Fourth build of rccDepends failed.") +endif() +# - Acquire binary timestamps after the build +file(TIMESTAMP "${rccDepBinPlain}" rdPlainAfter "${timeformat}") +file(TIMESTAMP "${rccDepBinGen}" rdGenAfter "${timeformat}") +# - Test if timestamps changed +if (NOT rdPlainAfter GREATER rdPlainBefore) + message(SEND_ERROR "Plain .qrc binary ${rccDepBinPlain}) should have changed!") +endif() +if (NOT rdGenAfter GREATER rdGenBefore) + message(SEND_ERROR "GENERATED .qrc binary ${rccDepBinGen} should have changed!") +endif() + + +message("Changing nothing in the .qrc file") +# - Acquire binary timestamps before the build +file(TIMESTAMP "${rccDepBinPlain}" rdPlainBefore "${timeformat}") +file(TIMESTAMP "${rccDepBinGen}" rdGenBefore "${timeformat}") +# - Ensure that the timestamp will change +# - Change nothing +# - Rebuild +execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) +execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${rccDepBD}" RESULT_VARIABLE result) +if (result) + message(SEND_ERROR "Fifth build of rccDepends failed.") +endif() +# - Acquire binary timestamps after the build +file(TIMESTAMP "${rccDepBinPlain}" rdPlainAfter "${timeformat}") +file(TIMESTAMP "${rccDepBinGen}" rdGenAfter "${timeformat}") +# - Test if timestamps changed +if (rdPlainAfter GREATER rdPlainBefore) + message(SEND_ERROR "Plain .qrc binary ${rccDepBinPlain}) should NOT have changed!") +endif() +if (rdGenAfter GREATER rdGenBefore) + message(SEND_ERROR "GENERATED .qrc binary ${rccDepBinGen} should NOT have changed!") +endif() diff --git a/Tests/QtAutogenRerun/rccDepends/CMakeLists.txt b/Tests/QtAutogenRerun/rccDepends/CMakeLists.txt index edc0ac3..291592e 100644 --- a/Tests/QtAutogenRerun/rccDepends/CMakeLists.txt +++ b/Tests/QtAutogenRerun/rccDepends/CMakeLists.txt @@ -1,8 +1,6 @@ cmake_minimum_required(VERSION 3.9) project(rccDepends CXX) -set(CMAKE_AUTORCC ON) - if (QT_TEST_VERSION STREQUAL 4) find_package(Qt4 REQUIRED) set(QT_CORE_TARGET Qt4::QtCore) @@ -15,21 +13,29 @@ else() set(QT_CORE_TARGET Qt5::Core) endif() -configure_file(res/input1.txt.in res1/input.txt COPYONLY) -configure_file(res/input1.txt.in res1/inputAdded.txt COPYONLY) -configure_file(res/input2.txt.in res2/input.txt COPYONLY) -configure_file(res/input2.txt.in res2/inputAdded.txt COPYONLY) -# Dependency generated qrc file -add_custom_command(OUTPUT res2.qrc - DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/res2.qrc.in - COMMAND ${CMAKE_COMMAND} -E sleep 2 - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/res2.qrc.in ${CMAKE_CURRENT_BINARY_DIR}/res2.qrc - ) +# Enable AUTORCC for all targets +set(CMAKE_AUTORCC ON) + +# Initial resource files setup +configure_file(resPlain/input.txt.in resPlain/input.txt COPYONLY) +configure_file(resPlain/input.txt.in resPlain/inputAdded.txt COPYONLY) +configure_file(resGen/input.txt.in resGen/input.txt COPYONLY) +configure_file(resGen/input.txt.in resGen/inputAdded.txt COPYONLY) + +# Generated qrc file with dependency +add_custom_command(OUTPUT resGen.qrc + DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/resGen.qrc.in + COMMAND ${CMAKE_COMMAND} -E sleep 2 + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/resGen.qrc.in ${CMAKE_CURRENT_BINARY_DIR}/resGen.qrc) + +# Target that uses a plain .qrc file +add_executable(rccDependsPlain main.cpp ${CMAKE_CURRENT_BINARY_DIR}/resPlain.qrc) +target_link_libraries(rccDependsPlain ${QT_CORE_TARGET}) +add_custom_command(TARGET rccDependsPlain POST_BUILD COMMAND + ${CMAKE_COMMAND} -E echo "$<TARGET_FILE:rccDependsPlain>" > targetPlain.txt) -add_executable(rccDepends - main.cpp - ${CMAKE_CURRENT_BINARY_DIR}/res1.qrc - ${CMAKE_CURRENT_BINARY_DIR}/res2.qrc ) -target_link_libraries(rccDepends ${QT_CORE_TARGET}) -add_custom_command(TARGET rccDepends POST_BUILD COMMAND - ${CMAKE_COMMAND} -E echo "$<TARGET_FILE:rccDepends>" > target.txt) +# Target that uses a GENERATED .qrc file +add_executable(rccDependsGen main.cpp ${CMAKE_CURRENT_BINARY_DIR}/resGen.qrc ) +target_link_libraries(rccDependsGen ${QT_CORE_TARGET}) +add_custom_command(TARGET rccDependsGen POST_BUILD COMMAND + ${CMAKE_COMMAND} -E echo "$<TARGET_FILE:rccDependsGen>" > targetGen.txt) diff --git a/Tests/QtAutogenRerun/rccDepends/res/input1.txt.in b/Tests/QtAutogenRerun/rccDepends/res/input1.txt.in deleted file mode 100644 index da62762..0000000 --- a/Tests/QtAutogenRerun/rccDepends/res/input1.txt.in +++ /dev/null @@ -1 +0,0 @@ -Res1 input. diff --git a/Tests/QtAutogenRerun/rccDepends/res/input2.txt.in b/Tests/QtAutogenRerun/rccDepends/res/input2.txt.in deleted file mode 100644 index 08e14b7..0000000 --- a/Tests/QtAutogenRerun/rccDepends/res/input2.txt.in +++ /dev/null @@ -1 +0,0 @@ -Res2 input. diff --git a/Tests/QtAutogenRerun/rccDepends/res1a.qrc.in b/Tests/QtAutogenRerun/rccDepends/res1a.qrc.in deleted file mode 100644 index d111ffb..0000000 --- a/Tests/QtAutogenRerun/rccDepends/res1a.qrc.in +++ /dev/null @@ -1,5 +0,0 @@ -<RCC> - <qresource prefix="/Texts1"> - <file>res1/input.txt</file> - </qresource> -</RCC> diff --git a/Tests/QtAutogenRerun/rccDepends/res1b.qrc.in b/Tests/QtAutogenRerun/rccDepends/res1b.qrc.in deleted file mode 100644 index 4cb3f04..0000000 --- a/Tests/QtAutogenRerun/rccDepends/res1b.qrc.in +++ /dev/null @@ -1,6 +0,0 @@ -<RCC> - <qresource prefix="/Texts1"> - <file>res1/input.txt</file> - <file alias="Added">res1/inputAdded.txt</file> - </qresource> -</RCC> diff --git a/Tests/QtAutogenRerun/rccDepends/res2a.qrc.in b/Tests/QtAutogenRerun/rccDepends/res2a.qrc.in deleted file mode 100644 index 19f34ac..0000000 --- a/Tests/QtAutogenRerun/rccDepends/res2a.qrc.in +++ /dev/null @@ -1,5 +0,0 @@ -<RCC> - <qresource prefix="/Texts2"> - <file>res2/input.txt</file> - </qresource> -</RCC> diff --git a/Tests/QtAutogenRerun/rccDepends/res2b.qrc.in b/Tests/QtAutogenRerun/rccDepends/res2b.qrc.in deleted file mode 100644 index 19e8ba1..0000000 --- a/Tests/QtAutogenRerun/rccDepends/res2b.qrc.in +++ /dev/null @@ -1,6 +0,0 @@ -<RCC> - <qresource prefix="/Texts2"> - <file>res2/input.txt</file> - <file alias="Added">res2/inputAdded.txt</file> - </qresource> -</RCC> diff --git a/Tests/QtAutogenRerun/rccDepends/resGen/input.txt.in b/Tests/QtAutogenRerun/rccDepends/resGen/input.txt.in new file mode 100644 index 0000000..4f24589 --- /dev/null +++ b/Tests/QtAutogenRerun/rccDepends/resGen/input.txt.in @@ -0,0 +1 @@ +Generated resource input. diff --git a/Tests/QtAutogenRerun/rccDepends/resGen/inputAdded.txt.in b/Tests/QtAutogenRerun/rccDepends/resGen/inputAdded.txt.in new file mode 100644 index 0000000..4f24589 --- /dev/null +++ b/Tests/QtAutogenRerun/rccDepends/resGen/inputAdded.txt.in @@ -0,0 +1 @@ +Generated resource input. diff --git a/Tests/QtAutogenRerun/rccDepends/resGenA.qrc.in b/Tests/QtAutogenRerun/rccDepends/resGenA.qrc.in new file mode 100644 index 0000000..c131a34 --- /dev/null +++ b/Tests/QtAutogenRerun/rccDepends/resGenA.qrc.in @@ -0,0 +1,5 @@ +<RCC> + <qresource prefix="/TextsGenerated"> + <file>resGen/input.txt</file> + </qresource> +</RCC> diff --git a/Tests/QtAutogenRerun/rccDepends/resGenB.qrc.in b/Tests/QtAutogenRerun/rccDepends/resGenB.qrc.in new file mode 100644 index 0000000..8c7e643 --- /dev/null +++ b/Tests/QtAutogenRerun/rccDepends/resGenB.qrc.in @@ -0,0 +1,6 @@ +<RCC> + <qresource prefix="/TextsGenerated"> + <file>resGen/input.txt</file> + <file alias="Added">resGen/inputAdded.txt</file> + </qresource> +</RCC> diff --git a/Tests/QtAutogenRerun/rccDepends/resPlain/input.txt.in b/Tests/QtAutogenRerun/rccDepends/resPlain/input.txt.in new file mode 100644 index 0000000..a5e407a --- /dev/null +++ b/Tests/QtAutogenRerun/rccDepends/resPlain/input.txt.in @@ -0,0 +1 @@ +Plaint resource input. diff --git a/Tests/QtAutogenRerun/rccDepends/resPlain/inputAdded.txt.in b/Tests/QtAutogenRerun/rccDepends/resPlain/inputAdded.txt.in new file mode 100644 index 0000000..a5e407a --- /dev/null +++ b/Tests/QtAutogenRerun/rccDepends/resPlain/inputAdded.txt.in @@ -0,0 +1 @@ +Plaint resource input. diff --git a/Tests/QtAutogenRerun/rccDepends/resPlainA.qrc.in b/Tests/QtAutogenRerun/rccDepends/resPlainA.qrc.in new file mode 100644 index 0000000..c135d85 --- /dev/null +++ b/Tests/QtAutogenRerun/rccDepends/resPlainA.qrc.in @@ -0,0 +1,5 @@ +<RCC> + <qresource prefix="/TextsPlain"> + <file>resPlain/input.txt</file> + </qresource> +</RCC> diff --git a/Tests/QtAutogenRerun/rccDepends/resPlainB.qrc.in b/Tests/QtAutogenRerun/rccDepends/resPlainB.qrc.in new file mode 100644 index 0000000..186b653 --- /dev/null +++ b/Tests/QtAutogenRerun/rccDepends/resPlainB.qrc.in @@ -0,0 +1,6 @@ +<RCC> + <qresource prefix="/TextsPlain"> + <file>resPlain/input.txt</file> + <file alias="Added">resPlain/inputAdded.txt</file> + </qresource> +</RCC> diff --git a/Tests/RunCMake/CMakeLists.txt b/Tests/RunCMake/CMakeLists.txt index 88952e1..5622f8e 100644 --- a/Tests/RunCMake/CMakeLists.txt +++ b/Tests/RunCMake/CMakeLists.txt @@ -147,6 +147,7 @@ endif() add_RunCMake_test(GeneratorExpression) add_RunCMake_test(GeneratorPlatform) add_RunCMake_test(GeneratorToolset) +add_RunCMake_test(GetPrerequisites) add_RunCMake_test(GNUInstallDirs -DSYSTEM_NAME=${CMAKE_SYSTEM_NAME}) add_RunCMake_test(GoogleTest) # Note: does not actually depend on Google Test add_RunCMake_test(TargetPropertyGeneratorExpressions) @@ -180,6 +181,8 @@ add_RunCMake_test(Syntax) add_RunCMake_test(add_custom_command) add_RunCMake_test(add_custom_target) add_RunCMake_test(add_dependencies) +add_RunCMake_test(add_executable) +add_RunCMake_test(add_library) add_RunCMake_test(add_subdirectory) add_RunCMake_test(build_command) add_executable(exit_code exit_code.c) @@ -225,20 +228,38 @@ add_RunCMake_test(separate_arguments) add_RunCMake_test(set_property) add_RunCMake_test(string) add_RunCMake_test(test_include_dirs) -foreach(var - CMAKE_C_COMPILER_ID - CMAKE_C_COMPILER_VERSION - CMAKE_C_STANDARD_DEFAULT - CMAKE_CXX_COMPILER_ID - CMAKE_CXX_COMPILER_VERSION - CMAKE_CXX_STANDARD_DEFAULT - CMake_TEST_CUDA - ) - if(DEFINED ${var}) - list(APPEND try_compile_ARGS -D${var}=${${var}}) + +function(add_RunCMake_test_try_compile) + if(CMAKE_VERSION VERSION_LESS 3.9.20170907 AND "x${CMAKE_CXX_COMPILER_ID}" STREQUAL "xMSVC") + # Older CMake versions do not know about MSVC language standards. + # Approximate our logic from MSVC-CXX.cmake. + if ((CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.0.24215.1 AND + CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.10) OR + CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.10.25017) + set(CMAKE_CXX_STANDARD_DEFAULT 14) + elseif (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16.0) + set(CMAKE_CXX_STANDARD_DEFAULT "") + else() + unset(CMAKE_CXX_STANDARD_DEFAULT) + endif() endif() -endforeach() -add_RunCMake_test(try_compile) + foreach(var + CMAKE_C_COMPILER_ID + CMAKE_C_COMPILER_VERSION + CMAKE_C_STANDARD_DEFAULT + CMAKE_CXX_COMPILER_ID + CMAKE_CXX_COMPILER_VERSION + CMAKE_CXX_STANDARD_DEFAULT + CMake_TEST_CUDA + ) + if(DEFINED ${var}) + list(APPEND try_compile_ARGS -D${var}=${${var}}) + endif() + endforeach() + add_RunCMake_test(try_compile) +endfunction() +add_RunCMake_test_try_compile() + add_RunCMake_test(try_run) add_RunCMake_test(set) add_RunCMake_test(variable_watch) diff --git a/Tests/RunCMake/CPack/DEB/Helpers.cmake b/Tests/RunCMake/CPack/DEB/Helpers.cmake index ad1b47b..6d8e84a 100644 --- a/Tests/RunCMake/CPack/DEB/Helpers.cmake +++ b/Tests/RunCMake/CPack/DEB/Helpers.cmake @@ -23,7 +23,7 @@ function(getPackageNameGlobexpr NAME COMPONENT VERSION REVISION FILE_NO RESULT_V endif() if(GENERATOR_SPECIFIC_FORMAT) - set(${RESULT_VAR} "${NAME}${COMPONENT}_${VERSION}-${REVISION}_*.deb" PARENT_SCOPE) + set(${RESULT_VAR} "${NAME}${COMPONENT}_${VERSION}_*.deb" PARENT_SCOPE) else() set(${RESULT_VAR} "${NAME}-${VERSION}-*${COMPONENT}.deb" PARENT_SCOPE) endif() diff --git a/Tests/RunCMake/CPack/RPM/Helpers.cmake b/Tests/RunCMake/CPack/RPM/Helpers.cmake index d8012b1..88fc231 100644 --- a/Tests/RunCMake/CPack/RPM/Helpers.cmake +++ b/Tests/RunCMake/CPack/RPM/Helpers.cmake @@ -23,6 +23,9 @@ function(getPackageNameGlobexpr NAME COMPONENT VERSION REVISION FILE_NO RESULT_V endif() if(GENERATOR_SPECIFIC_FORMAT) + if(NOT REVISION) + set(REVISION "1") + endif() set(${RESULT_VAR} "${NAME}${COMPONENT}-${VERSION}-${REVISION}.*.rpm" PARENT_SCOPE) else() set(${RESULT_VAR} "${NAME}-${VERSION}-*${COMPONENT}.rpm" PARENT_SCOPE) diff --git a/Tests/RunCMake/CPack/RunCMakeTest.cmake b/Tests/RunCMake/CPack/RunCMakeTest.cmake index faf151a..04ac584 100644 --- a/Tests/RunCMake/CPack/RunCMakeTest.cmake +++ b/Tests/RunCMake/CPack/RunCMakeTest.cmake @@ -10,6 +10,7 @@ run_cpack_test(DEBUGINFO "RPM" true "COMPONENT") run_cpack_test(DEPENDENCIES "RPM;DEB" true "COMPONENT") run_cpack_test(DIST "RPM" false "MONOLITHIC") run_cpack_test(EMPTY_DIR "RPM;DEB;TGZ" true "MONOLITHIC;COMPONENT") +run_cpack_test(VERSION "RPM;DEB" false "MONOLITHIC;COMPONENT") run_cpack_test(EXTRA "DEB" false "COMPONENT") run_cpack_test(GENERATE_SHLIBS "DEB" true "COMPONENT") run_cpack_test(GENERATE_SHLIBS_LDCONFIG "DEB" true "COMPONENT") @@ -27,3 +28,4 @@ run_cpack_test(SUGGESTS "RPM" false "MONOLITHIC") run_cpack_test(SYMLINKS "RPM;TGZ" false "MONOLITHIC;COMPONENT") run_cpack_test(USER_FILELIST "RPM" false "MONOLITHIC") run_cpack_test(MD5SUMS "DEB" false "MONOLITHIC;COMPONENT") +run_cpack_test(CPACK_INSTALL_SCRIPT "ZIP" false "MONOLITHIC") diff --git a/Tests/RunCMake/CPack/VerifyResult.cmake b/Tests/RunCMake/CPack/VerifyResult.cmake index 470ebf7..1f5ab87 100644 --- a/Tests/RunCMake/CPack/VerifyResult.cmake +++ b/Tests/RunCMake/CPack/VerifyResult.cmake @@ -8,9 +8,7 @@ function(findExpectedFile FILE_NO RESULT_VAR GLOBING_EXPR_VAR) endif() if(NOT DEFINED EXPECTED_FILE_${FILE_NO}_VERSION) set(EXPECTED_FILE_${FILE_NO}_VERSION "0.1.1") - endif() - if(NOT DEFINED EXPECTED_FILE_${FILE_NO}_REVISION) - set(EXPECTED_FILE_${FILE_NO}_REVISION "1") + set(EXPECTED_FILE_${FILE_NO}_VERSION "0.1.1" PARENT_SCOPE) endif() getPackageNameGlobexpr("${EXPECTED_FILE_${FILE_NO}_NAME}" diff --git a/Tests/RunCMake/CPack/tests/CPACK_INSTALL_SCRIPT/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/CPACK_INSTALL_SCRIPT/ExpectedFiles.cmake new file mode 100644 index 0000000..5cb12c3 --- /dev/null +++ b/Tests/RunCMake/CPack/tests/CPACK_INSTALL_SCRIPT/ExpectedFiles.cmake @@ -0,0 +1,3 @@ +set(EXPECTED_FILES_COUNT "1") + +set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/abc.txt") diff --git a/Tests/RunCMake/CPack/tests/CPACK_INSTALL_SCRIPT/test.cmake b/Tests/RunCMake/CPack/tests/CPACK_INSTALL_SCRIPT/test.cmake new file mode 100644 index 0000000..e3fe0ca --- /dev/null +++ b/Tests/RunCMake/CPack/tests/CPACK_INSTALL_SCRIPT/test.cmake @@ -0,0 +1,11 @@ +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/abc.txt" "test content") +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/user-script.cmake" + "file(INSTALL DESTINATION \"\${CMAKE_INSTALL_PREFIX}/foo\" + TYPE FILE FILES \"${CMAKE_CURRENT_BINARY_DIR}/abc.txt\")") +set(CPACK_INSTALL_SCRIPT "${CMAKE_CURRENT_BINARY_DIR}/user-script.cmake") + +function(run_after_include_cpack) + file(READ "${CPACK_OUTPUT_CONFIG_FILE}" conf_file_) + string(REGEX REPLACE "SET\\(CPACK_INSTALL_CMAKE_PROJECTS [^)]*\\)" "" conf_file_ "${conf_file_}") + file(WRITE "${CPACK_OUTPUT_CONFIG_FILE}" "${conf_file_}") +endfunction() diff --git a/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/VerifyResult.cmake index e4f9618..2bb4d3f 100644 --- a/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/VerifyResult.cmake +++ b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/VerifyResult.cmake @@ -1,8 +1,7 @@ if(NOT ${RunCMake_SUBTEST_SUFFIX} MATCHES "invalid") - string(TOLOWER ${RunCMake_SUBTEST_SUFFIX} EXTENSION) + string(TOLOWER ${RunCMake_SUBTEST_SUFFIX} CHECKSUM_EXTENSION) file(GLOB PACKAGE RELATIVE ${bin_dir} "*.tar.gz") - file(GLOB CSUMFILE RELATIVE ${bin_dir} "*.${EXTENSION}") - file(STRINGS ${CSUMFILE} CHSUM_VALUE) + file(STRINGS ${PACKAGE}.${CHECKSUM_EXTENSION} CHSUM_VALUE) file(${RunCMake_SUBTEST_SUFFIX} ${PACKAGE} expected_value ) set(expected_value "${expected_value} ${PACKAGE}") diff --git a/Tests/RunCMake/CPack/tests/VERSION/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/VERSION/ExpectedFiles.cmake new file mode 100644 index 0000000..85c571c --- /dev/null +++ b/Tests/RunCMake/CPack/tests/VERSION/ExpectedFiles.cmake @@ -0,0 +1,3 @@ +set(EXPECTED_FILES_COUNT "1") +set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt") +set(EXPECTED_FILE_1_REVISION "1") diff --git a/Tests/RunCMake/CPack/tests/VERSION/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/VERSION/VerifyResult.cmake new file mode 100644 index 0000000..eed9696 --- /dev/null +++ b/Tests/RunCMake/CPack/tests/VERSION/VerifyResult.cmake @@ -0,0 +1,17 @@ +function(checkPackageInfo_ TYPE FILE REGEX) + getPackageInfo("${FILE}" "FILE_INFO_") + if(NOT FILE_INFO_ MATCHES "${REGEX}") + message(FATAL_ERROR "Unexpected ${TYPE} in '${FILE}' ${EXPECTED_FILE_1_VERSION} ${EXPECTED_FILE_1_REVISION}; file info: '${FILE_INFO_}'") + endif() +endfunction() + +set(whitespaces_ "[\t\n\r ]*") + +if(GENERATOR_TYPE STREQUAL "RPM") + checkPackageInfo_("package version" "${FOUND_FILE_1}" "Version${whitespaces_}:${whitespaces_}${EXPECTED_FILE_1_VERSION}") + checkPackageInfo_("package revision" "${FOUND_FILE_1}" "Release${whitespaces_}:${whitespaces_}${EXPECTED_FILE_1_REVISION}") + checkPackageInfo_("epoch version" "${FOUND_FILE_1}" "Epoch${whitespaces_}:${whitespaces_}3") +else() # DEB + checkPackageInfo_("version" "${FOUND_FILE_1}" + ".*Version${whitespaces_}:${whitespaces_}3:${EXPECTED_FILE_1_VERSION}-${EXPECTED_FILE_1_REVISION}") +endif() diff --git a/Tests/RunCMake/CPack/tests/VERSION/test.cmake b/Tests/RunCMake/CPack/tests/VERSION/test.cmake new file mode 100644 index 0000000..301ab61 --- /dev/null +++ b/Tests/RunCMake/CPack/tests/VERSION/test.cmake @@ -0,0 +1,14 @@ +install(FILES CMakeLists.txt DESTINATION foo COMPONENT test) + +if(GENERATOR_TYPE STREQUAL "DEB") + set(package_type_ "DEBIAN") + set(CPACK_DEBIAN_PACKAGE_RELEASE "1") +else() + set(package_type_ "${GENERATOR_TYPE}") +endif() + +set(CPACK_${package_type_}_PACKAGE_EPOCH "3") + +if(PACKAGING_TYPE STREQUAL "COMPONENT") + set(CPACK_COMPONENTS_ALL test) +endif() diff --git a/Tests/RunCMake/CTestCommandLine/LabelCount-stdout.txt b/Tests/RunCMake/CTestCommandLine/LabelCount-stdout.txt index 7fe04eb..9cfe41c 100644 --- a/Tests/RunCMake/CTestCommandLine/LabelCount-stdout.txt +++ b/Tests/RunCMake/CTestCommandLine/LabelCount-stdout.txt @@ -1,7 +1,7 @@ 100% tests passed, 0 tests failed out of 4 + +Label Time Summary: -+'bar' = +[0-9.]+ sec \(3 tests\) -+'foo' = +[0-9.]+ sec \(1 test\) ++'bar' = +[0-9.]+ sec\*proc \(3 tests\) ++'foo' = +[0-9.]+ sec\*proc \(1 test\) + Total Test time \(real\) = +[0-9.]+ sec diff --git a/Tests/RunCMake/CommandLine/E___run_iwyu-no-iwyu-result.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-bad-iwyu-result.txt index d00491f..d00491f 100644 --- a/Tests/RunCMake/CommandLine/E___run_iwyu-no-iwyu-result.txt +++ b/Tests/RunCMake/CommandLine/E___run_co_compile-bad-iwyu-result.txt diff --git a/Tests/RunCMake/CommandLine/E___run_iwyu-bad-iwyu-stderr.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-bad-iwyu-stderr.txt index 338f7c4..338f7c4 100644 --- a/Tests/RunCMake/CommandLine/E___run_iwyu-bad-iwyu-stderr.txt +++ b/Tests/RunCMake/CommandLine/E___run_co_compile-bad-iwyu-stderr.txt diff --git a/Tests/RunCMake/CommandLine/E___run_iwyu-no-cc-result.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-no----result.txt index d00491f..d00491f 100644 --- a/Tests/RunCMake/CommandLine/E___run_iwyu-no-cc-result.txt +++ b/Tests/RunCMake/CommandLine/E___run_co_compile-no----result.txt diff --git a/Tests/RunCMake/CommandLine/E___run_co_compile-no----stderr.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-no----stderr.txt new file mode 100644 index 0000000..f0597d2 --- /dev/null +++ b/Tests/RunCMake/CommandLine/E___run_co_compile-no----stderr.txt @@ -0,0 +1 @@ +^__run_co_compile given unknown argument: command-does-not-exist$ diff --git a/Tests/RunCMake/CommandLine/E___run_iwyu-no----result.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-no-cc-result.txt index d00491f..d00491f 100644 --- a/Tests/RunCMake/CommandLine/E___run_iwyu-no----result.txt +++ b/Tests/RunCMake/CommandLine/E___run_co_compile-no-cc-result.txt diff --git a/Tests/RunCMake/CommandLine/E___run_co_compile-no-cc-stderr.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-no-cc-stderr.txt new file mode 100644 index 0000000..bba846e --- /dev/null +++ b/Tests/RunCMake/CommandLine/E___run_co_compile-no-cc-stderr.txt @@ -0,0 +1 @@ +^__run_co_compile missing compile command after --$ diff --git a/Tests/RunCMake/CommandLine/E___run_iwyu-bad-iwyu-result.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-no-iwyu-result.txt index d00491f..d00491f 100644 --- a/Tests/RunCMake/CommandLine/E___run_iwyu-bad-iwyu-result.txt +++ b/Tests/RunCMake/CommandLine/E___run_co_compile-no-iwyu-result.txt diff --git a/Tests/RunCMake/CommandLine/E___run_co_compile-no-iwyu-stderr.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-no-iwyu-stderr.txt new file mode 100644 index 0000000..ffa1da8 --- /dev/null +++ b/Tests/RunCMake/CommandLine/E___run_co_compile-no-iwyu-stderr.txt @@ -0,0 +1,5 @@ +^__run_co_compile missing command to run. Looking for one of the following: +.*--cppcheck= +.*--cpplint= +.*--iwyu= +.*--tidy= diff --git a/Tests/RunCMake/CommandLine/E___run_iwyu-no----stderr.txt b/Tests/RunCMake/CommandLine/E___run_iwyu-no----stderr.txt deleted file mode 100644 index c251adf..0000000 --- a/Tests/RunCMake/CommandLine/E___run_iwyu-no----stderr.txt +++ /dev/null @@ -1 +0,0 @@ -^__run_iwyu given unknown argument: command-does-not-exist$ diff --git a/Tests/RunCMake/CommandLine/E___run_iwyu-no-cc-stderr.txt b/Tests/RunCMake/CommandLine/E___run_iwyu-no-cc-stderr.txt deleted file mode 100644 index 1998abb..0000000 --- a/Tests/RunCMake/CommandLine/E___run_iwyu-no-cc-stderr.txt +++ /dev/null @@ -1 +0,0 @@ -^__run_iwyu missing compile command after --$ diff --git a/Tests/RunCMake/CommandLine/E___run_iwyu-no-iwyu-stderr.txt b/Tests/RunCMake/CommandLine/E___run_iwyu-no-iwyu-stderr.txt deleted file mode 100644 index 9db95f8..0000000 --- a/Tests/RunCMake/CommandLine/E___run_iwyu-no-iwyu-stderr.txt +++ /dev/null @@ -1 +0,0 @@ -^__run_iwyu missing --cpplint=, --iwyu=, --lwyu=, --cppcheck= and/or --tidy=$ diff --git a/Tests/RunCMake/CommandLine/RunCMakeTest.cmake b/Tests/RunCMake/CommandLine/RunCMakeTest.cmake index 6efcc12..55eac5e 100644 --- a/Tests/RunCMake/CommandLine/RunCMakeTest.cmake +++ b/Tests/RunCMake/CommandLine/RunCMakeTest.cmake @@ -21,10 +21,10 @@ run_cmake_command(E_touch_nocreate-no-arg ${CMAKE_COMMAND} -E touch_nocreate) run_cmake_command(E_time ${CMAKE_COMMAND} -E time ${CMAKE_COMMAND} -E echo "hello world") run_cmake_command(E_time-no-arg ${CMAKE_COMMAND} -E time) -run_cmake_command(E___run_iwyu-no-iwyu ${CMAKE_COMMAND} -E __run_iwyu -- command-does-not-exist) -run_cmake_command(E___run_iwyu-bad-iwyu ${CMAKE_COMMAND} -E __run_iwyu --iwyu=iwyu-does-not-exist -- command-does-not-exist) -run_cmake_command(E___run_iwyu-no--- ${CMAKE_COMMAND} -E __run_iwyu --iwyu=iwyu-does-not-exist command-does-not-exist) -run_cmake_command(E___run_iwyu-no-cc ${CMAKE_COMMAND} -E __run_iwyu --iwyu=iwyu-does-not-exist --) +run_cmake_command(E___run_co_compile-no-iwyu ${CMAKE_COMMAND} -E __run_co_compile -- command-does-not-exist) +run_cmake_command(E___run_co_compile-bad-iwyu ${CMAKE_COMMAND} -E __run_co_compile --iwyu=iwyu-does-not-exist -- command-does-not-exist) +run_cmake_command(E___run_co_compile-no--- ${CMAKE_COMMAND} -E __run_co_compile --iwyu=iwyu-does-not-exist command-does-not-exist) +run_cmake_command(E___run_co_compile-no-cc ${CMAKE_COMMAND} -E __run_co_compile --iwyu=iwyu-does-not-exist --) run_cmake_command(G_no-arg ${CMAKE_COMMAND} -G) run_cmake_command(G_bad-arg ${CMAKE_COMMAND} -G NoSuchGenerator) diff --git a/Tests/RunCMake/Cppcheck/C-bad-Build-result.txt b/Tests/RunCMake/Cppcheck/C-bad-Build-result.txt new file mode 100644 index 0000000..573541a --- /dev/null +++ b/Tests/RunCMake/Cppcheck/C-bad-Build-result.txt @@ -0,0 +1 @@ +0 diff --git a/Tests/RunCMake/Cppcheck/C-bad-Build-stdout.txt b/Tests/RunCMake/Cppcheck/C-bad-Build-stdout.txt new file mode 100644 index 0000000..2370ce1 --- /dev/null +++ b/Tests/RunCMake/Cppcheck/C-bad-Build-stdout.txt @@ -0,0 +1,2 @@ +stdout from bad command line arg '-bad' +stderr from bad command line arg '-bad' diff --git a/Tests/RunCMake/Cppcheck/C-bad.cmake b/Tests/RunCMake/Cppcheck/C-bad.cmake new file mode 100644 index 0000000..920e4b4 --- /dev/null +++ b/Tests/RunCMake/Cppcheck/C-bad.cmake @@ -0,0 +1,3 @@ +enable_language(C) +set(CMAKE_C_CPPCHECK "${PSEUDO_CPPCHECK}" -bad) +add_executable(main main.c) diff --git a/Tests/RunCMake/Cppcheck/RunCMakeTest.cmake b/Tests/RunCMake/Cppcheck/RunCMakeTest.cmake index ae14f8c..5fd4ead 100644 --- a/Tests/RunCMake/Cppcheck/RunCMakeTest.cmake +++ b/Tests/RunCMake/Cppcheck/RunCMakeTest.cmake @@ -15,6 +15,7 @@ endfunction() run_cppcheck(C) run_cppcheck(CXX) +run_cppcheck(C-bad) if(NOT RunCMake_GENERATOR STREQUAL "Watcom WMake") run_cppcheck(C-launch) diff --git a/Tests/RunCMake/ExternalProject/MultiCommand-build-stdout.txt b/Tests/RunCMake/ExternalProject/MultiCommand-build-stdout.txt new file mode 100644 index 0000000..30ebc7d --- /dev/null +++ b/Tests/RunCMake/ExternalProject/MultiCommand-build-stdout.txt @@ -0,0 +1,15 @@ +.* *download 1 +.* *download 2 +.* *update 1 +.* *update 2 +.* *patch 1 +.* *patch 2 +.* *configure 1 +.* *configure 2 +.* *build 1 +.* *build 2 +.* *install 1 +.* *install 2 +.* *test 1 +.* *test 2 +.* diff --git a/Tests/RunCMake/ExternalProject/MultiCommand.cmake b/Tests/RunCMake/ExternalProject/MultiCommand.cmake new file mode 100644 index 0000000..a8dbfea --- /dev/null +++ b/Tests/RunCMake/ExternalProject/MultiCommand.cmake @@ -0,0 +1,30 @@ +cmake_minimum_required(VERSION 3.9) + +include(ExternalProject) + +# Verify COMMAND keyword is recognised after various *_COMMAND options +ExternalProject_Add(multiCommand + DOWNLOAD_COMMAND "${CMAKE_COMMAND}" -E echo "download 1" + COMMAND "${CMAKE_COMMAND}" -E echo "download 2" + UPDATE_COMMAND "${CMAKE_COMMAND}" -E echo "update 1" + COMMAND "${CMAKE_COMMAND}" -E echo "update 2" + PATCH_COMMAND "${CMAKE_COMMAND}" -E echo "patch 1" + COMMAND "${CMAKE_COMMAND}" -E echo "patch 2" + CONFIGURE_COMMAND "${CMAKE_COMMAND}" -E echo "configure 1" + COMMAND "${CMAKE_COMMAND}" -E echo "configure 2" + BUILD_COMMAND "${CMAKE_COMMAND}" -E echo "build 1" + COMMAND "${CMAKE_COMMAND}" -E echo "build 2" + TEST_COMMAND "${CMAKE_COMMAND}" -E echo "test 1" + COMMAND "${CMAKE_COMMAND}" -E echo "test 2" + INSTALL_COMMAND "${CMAKE_COMMAND}" -E echo "install 1" + COMMAND "${CMAKE_COMMAND}" -E echo "install 2" +) + +# Workaround for issue 17229 (missing dependency between update and patch steps) +ExternalProject_Add_StepTargets(multiCommand NO_DEPENDS update) +ExternalProject_Add_StepDependencies(multiCommand patch multiCommand-update) + +# Force all steps to be re-run by removing timestamps from any previous run +ExternalProject_Get_Property(multiCommand STAMP_DIR) +file(REMOVE_RECURSE "${STAMP_DIR}") +file(MAKE_DIRECTORY "${STAMP_DIR}") diff --git a/Tests/RunCMake/ExternalProject/RunCMakeTest.cmake b/Tests/RunCMake/ExternalProject/RunCMakeTest.cmake index 47d6129..994e2aa 100644 --- a/Tests/RunCMake/ExternalProject/RunCMakeTest.cmake +++ b/Tests/RunCMake/ExternalProject/RunCMakeTest.cmake @@ -12,3 +12,13 @@ run_cmake(Add_StepDependencies_iface) run_cmake(Add_StepDependencies_iface_step) run_cmake(Add_StepDependencies_no_target) run_cmake(UsesTerminal) + +# Run both cmake and build steps. We always do a clean before the +# build to ensure that the download step re-runs each time. +set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/MultiCommand-build) +set(RunCMake_TEST_NO_CLEAN 1) +file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}") +file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}") +run_cmake(MultiCommand) +run_cmake_command(MultiCommand-clean ${CMAKE_COMMAND} --build . --target clean) +run_cmake_command(MultiCommand-build ${CMAKE_COMMAND} --build .) diff --git a/Tests/RunCMake/FPHSA/FindPseudoNoVersionVar.cmake b/Tests/RunCMake/FPHSA/FindPseudoNoVersionVar.cmake new file mode 100644 index 0000000..d961c64 --- /dev/null +++ b/Tests/RunCMake/FPHSA/FindPseudoNoVersionVar.cmake @@ -0,0 +1,6 @@ +# pseudo find_module without specifying VERSION_VAR + +set(FOOBAR TRUE) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(PseudoNoVersionVar REQUIRED_VARS FOOBAR) diff --git a/Tests/RunCMake/FPHSA/RunCMakeTest.cmake b/Tests/RunCMake/FPHSA/RunCMakeTest.cmake index e9b2a7a..dd73cd4 100644 --- a/Tests/RunCMake/FPHSA/RunCMakeTest.cmake +++ b/Tests/RunCMake/FPHSA/RunCMakeTest.cmake @@ -4,7 +4,18 @@ run_cmake(BadFoundVar) # The pseudo module will "find" a package with the given version. Check if the # version selection code in FPHSA works correctly. -set(RunCMake_TEST_OPTIONS "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" "-DPseudo_VERSION=1.2.3.4.5") + +# Find a package with version 0. +set(RunCMake_TEST_OPTIONS "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" "-DPseudo_VERSION=0") +run_cmake(any_version_find_0) + +# Find a package with more customary version number, without requesting a specific version and in +# the presence of a cache variable VERSION. +set(RunCMake_TEST_OPTIONS "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" "-DPseudoNoVersionVar_VERSION=1.2.3.4_SHOULD_BE_IGNORED" "-DVERSION=BAD_VERSION") +run_cmake(any_version_VERSION_cache_variable) + +# Find a package with a more customary version number, without requesting a specific version. +set(RunCMake_TEST_OPTIONS "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" "-DPseudo_VERSION=1.2.3.4") run_cmake(any_version) # test EXACT mode with every subcomponent diff --git a/Tests/RunCMake/FPHSA/any_version_VERSION_cache_variable-stdout.txt b/Tests/RunCMake/FPHSA/any_version_VERSION_cache_variable-stdout.txt new file mode 100644 index 0000000..f9acece --- /dev/null +++ b/Tests/RunCMake/FPHSA/any_version_VERSION_cache_variable-stdout.txt @@ -0,0 +1,2 @@ +Found PseudoNoVersionVar: TRUE * ++ diff --git a/Tests/RunCMake/FPHSA/any_version_VERSION_cache_variable.cmake b/Tests/RunCMake/FPHSA/any_version_VERSION_cache_variable.cmake new file mode 100644 index 0000000..9f27897 --- /dev/null +++ b/Tests/RunCMake/FPHSA/any_version_VERSION_cache_variable.cmake @@ -0,0 +1 @@ +find_package(PseudoNoVersionVar REQUIRED) diff --git a/Tests/RunCMake/FPHSA/any_version_find_0-stdout.txt b/Tests/RunCMake/FPHSA/any_version_find_0-stdout.txt new file mode 100644 index 0000000..861a339 --- /dev/null +++ b/Tests/RunCMake/FPHSA/any_version_find_0-stdout.txt @@ -0,0 +1,2 @@ +Found Pseudo: [^ +]*\(found version "0\"\) diff --git a/Tests/RunCMake/FPHSA/any_version_find_0.cmake b/Tests/RunCMake/FPHSA/any_version_find_0.cmake new file mode 100644 index 0000000..b34a540 --- /dev/null +++ b/Tests/RunCMake/FPHSA/any_version_find_0.cmake @@ -0,0 +1 @@ +find_package(Pseudo REQUIRED) diff --git a/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake b/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake index 63cd2da..2486259 100644 --- a/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake +++ b/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake @@ -32,6 +32,7 @@ run_cmake(COMPILE_LANGUAGE-unknown-lang) run_cmake(TARGET_FILE-recursion) run_cmake(OUTPUT_NAME-recursion) run_cmake(TARGET_PROPERTY-LOCATION) +run_cmake(TARGET_PROPERTY-SOURCES) run_cmake(LINK_ONLY-not-linking) run_cmake(ImportedTarget-TARGET_BUNDLE_DIR) diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-SOURCES-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-SOURCES-check.cmake new file mode 100644 index 0000000..f1452b5 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-SOURCES-check.cmake @@ -0,0 +1,9 @@ +file(READ ${RunCMake_TEST_BINARY_DIR}/foo.txt foo_sources) + +# VS generators inject CMakeLists.txt as a source. Remove it. +string(REGEX REPLACE ";[^;]*CMakeLists.txt$" "" foo_sources "${foo_sources}") + +set(foo_expected "empty.c;empty2.c;empty3.c") +if(NOT foo_sources STREQUAL foo_expected) + set(RunCMake_TEST_FAILED "foo SOURCES was:\n [[${foo_sources}]]\nbut expected:\n [[${foo_expected}]]") +endif() diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-SOURCES.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-SOURCES.cmake new file mode 100644 index 0000000..dee7ead --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-SOURCES.cmake @@ -0,0 +1,5 @@ +cmake_policy(SET CMP0070 NEW) +enable_language(C) +add_library(foo empty.c empty2.c) +target_sources(foo PRIVATE empty3.c) +file(GENERATE OUTPUT foo.txt CONTENT "$<TARGET_PROPERTY:foo,SOURCES>") diff --git a/Tests/RunCMake/GeneratorExpression/empty2.c b/Tests/RunCMake/GeneratorExpression/empty2.c new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/empty2.c diff --git a/Tests/RunCMake/GeneratorExpression/empty3.c b/Tests/RunCMake/GeneratorExpression/empty3.c new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/empty3.c diff --git a/Tests/RunCMake/GetPrerequisites/RunCMakeTest.cmake b/Tests/RunCMake/GetPrerequisites/RunCMakeTest.cmake new file mode 100644 index 0000000..3856c54 --- /dev/null +++ b/Tests/RunCMake/GetPrerequisites/RunCMakeTest.cmake @@ -0,0 +1,3 @@ +include(RunCMake) + +run_cmake_command(TargetMissing ${CMAKE_COMMAND} -P ${RunCMake_SOURCE_DIR}/TargetMissing.cmake) diff --git a/Tests/RunCMake/GetPrerequisites/TargetMissing-stderr.txt b/Tests/RunCMake/GetPrerequisites/TargetMissing-stderr.txt new file mode 100644 index 0000000..cffe5f8 --- /dev/null +++ b/Tests/RunCMake/GetPrerequisites/TargetMissing-stderr.txt @@ -0,0 +1,3 @@ +^warning: target 'does_not_exist' is not absolute\.\.\. +warning: target 'does_not_exist' does not exist\.\.\. +result_var='value;before;call'$ diff --git a/Tests/RunCMake/GetPrerequisites/TargetMissing.cmake b/Tests/RunCMake/GetPrerequisites/TargetMissing.cmake new file mode 100644 index 0000000..84fd32c --- /dev/null +++ b/Tests/RunCMake/GetPrerequisites/TargetMissing.cmake @@ -0,0 +1,4 @@ +include(GetPrerequisites) +set(result_var value before call) +get_prerequisites(does_not_exist result_var 0 0 "" "") +message("result_var='${result_var}'") diff --git a/Tests/RunCMake/README.rst b/Tests/RunCMake/README.rst index 4aae4ae..08b51d9 100644 --- a/Tests/RunCMake/README.rst +++ b/Tests/RunCMake/README.rst @@ -47,11 +47,11 @@ but do not actually build anything. To add a test: containing expected test results: ``<SubTest>-result.txt`` - Process result expected if not "0" + Regex matching expected process result, if not ``0`` ``<SubTest>-stdout.txt`` Regex matching expected stdout content ``<SubTest>-stderr.txt`` - Regex matching expected stderr content, if not "^$" + Regex matching expected stderr content, if not ``^$`` ``<SubTest>-check.cmake`` Custom result check. diff --git a/Tests/RunCMake/Syntax/NullTerminatedArgument-result.txt b/Tests/RunCMake/Syntax/NullTerminatedArgument-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/Syntax/NullTerminatedArgument-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/Syntax/NullTerminatedArgument-stderr.txt b/Tests/RunCMake/Syntax/NullTerminatedArgument-stderr.txt new file mode 100644 index 0000000..f26754e --- /dev/null +++ b/Tests/RunCMake/Syntax/NullTerminatedArgument-stderr.txt @@ -0,0 +1,5 @@ +CMake Error at NullTerminatedArgument.cmake:1: + Parse error. Function missing ending "\)". Instead found bad character + with text "". +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/Syntax/NullTerminatedArgument.cmake b/Tests/RunCMake/Syntax/NullTerminatedArgument.cmake Binary files differnew file mode 100644 index 0000000..c82aceb --- /dev/null +++ b/Tests/RunCMake/Syntax/NullTerminatedArgument.cmake diff --git a/Tests/RunCMake/Syntax/RunCMakeTest.cmake b/Tests/RunCMake/Syntax/RunCMakeTest.cmake index d1fbb16..628df91 100644 --- a/Tests/RunCMake/Syntax/RunCMakeTest.cmake +++ b/Tests/RunCMake/Syntax/RunCMakeTest.cmake @@ -55,6 +55,7 @@ run_cmake(BracketNoSpace5) run_cmake(Escape1) run_cmake(Escape2) run_cmake(EscapeCharsAllowed) +run_cmake(NullTerminatedArgument) include("${RunCMake_SOURCE_DIR}/EscapeCharsDisallowed.cmake") run_cmake(ParenNoSpace0) run_cmake(ParenNoSpace1) diff --git a/Tests/RunCMake/add_custom_command/RemoveEmptyCommands-check.cmake b/Tests/RunCMake/add_custom_command/RemoveEmptyCommands-check.cmake new file mode 100644 index 0000000..b297044 --- /dev/null +++ b/Tests/RunCMake/add_custom_command/RemoveEmptyCommands-check.cmake @@ -0,0 +1,63 @@ +set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/exe.vcxproj") +if(NOT EXISTS "${vcProjectFile}") + set(RunCMake_TEST_FAILED "Project file ${vcProjectFile} does not exist.") + return() +endif() + +set(inGroup FALSE) +set(inCommand FALSE) + +set(expected_Debug + "cmd_1 cmd_1_arg" + "cmd_1_dbg cmd_1_dbg_arg" + "cmd_2_dbg cmd_2_dbg_arg" + "cmd_3_dbg cmd_3_dbg_arg") + +set(expected_Release + "cmd_1 cmd_1_arg" + "cmd_3_rel cmd_3_rel_arg") + +# extract build events +file(STRINGS "${vcProjectFile}" lines) +foreach(line IN LISTS lines) + if(line MATCHES "^ *<ItemDefinitionGroup Condition=.*Configuration.*Platform.*>$") + set(inGroup TRUE) + string(REGEX MATCH "=='(.*)\\|(.*)'" out ${line}) + set(config ${CMAKE_MATCH_1}) + elseif(line MATCHES "^ *</ItemDefinitionGroup>$") + set(inGroup FALSE) + elseif(inGroup) + if(line MATCHES "^ *<Command>.*$") + set(inCommand TRUE) + string(REGEX MATCH "<Command>(.*)" cmd ${line}) + set(currentCommand ${CMAKE_MATCH_1}) + elseif(line MATCHES "^(.*)</Command>$") + string(REGEX MATCH "(.*)</Command>" cmd ${line}) + list(APPEND currentCommand ${CMAKE_MATCH_1}) + set(command_${config} ${currentCommand}) + set(inCommand FALSE) + elseif(inCommand) + list(APPEND currentCommand ${line}) + endif() + endif() +endforeach() + +foreach(config "Debug" "Release") + set(currentName command_${config}) + set(expectedName expected_${config}) + set(strippedCommand "") + if(DEFINED ${currentName}) + foreach(v ${${currentName}}) + if(${v} MATCHES "cmd_") + list(APPEND strippedCommand ${v}) + endif() + endforeach() + if(NOT "${strippedCommand}" STREQUAL + "${${expectedName}}") + message(" - ${strippedCommand}") + message(" + ${${expectedName}}") + set(RunCMake_TEST_FAILED "build event command does not match") + return() + endif() + endif() +endforeach() diff --git a/Tests/RunCMake/add_custom_command/RemoveEmptyCommands.cmake b/Tests/RunCMake/add_custom_command/RemoveEmptyCommands.cmake new file mode 100644 index 0000000..eb190cc --- /dev/null +++ b/Tests/RunCMake/add_custom_command/RemoveEmptyCommands.cmake @@ -0,0 +1,22 @@ +enable_language(CXX) + +# reduce number of configuration types +set(CMAKE_CONFIGURATION_TYPES "Debug" "Release") + +set(main_file "${CMAKE_BINARY_DIR}/main.cpp") +file(WRITE "${main_file}" "test") +add_executable(exe "${main_file}") + +# add one command for all and one for debug only +add_custom_command(TARGET exe + COMMAND "cmd_1" "cmd_1_arg" + COMMAND $<$<CONFIG:Debug>:cmd_1_dbg> $<$<CONFIG:Debug>:cmd_1_dbg_arg>) + +# add command for debug only +add_custom_command(TARGET exe + COMMAND $<$<CONFIG:Debug>:cmd_2_dbg> $<$<CONFIG:Debug>:cmd_2_dbg_arg>) + +# add separate commands for configurations +add_custom_command(TARGET exe + COMMAND $<$<CONFIG:Debug>:cmd_3_dbg> $<$<CONFIG:Debug>:cmd_3_dbg_arg> + COMMAND $<$<CONFIG:Release>:cmd_3_rel> $<$<CONFIG:Release>:cmd_3_rel_arg>) diff --git a/Tests/RunCMake/add_custom_command/RunCMakeTest.cmake b/Tests/RunCMake/add_custom_command/RunCMakeTest.cmake index 397c63d..c12e5aa 100644 --- a/Tests/RunCMake/add_custom_command/RunCMakeTest.cmake +++ b/Tests/RunCMake/add_custom_command/RunCMakeTest.cmake @@ -10,3 +10,7 @@ run_cmake(SourceByproducts) run_cmake(SourceUsesTerminal) run_cmake(TargetImported) run_cmake(TargetNotInDir) + +if(${RunCMake_GENERATOR} MATCHES "Visual Studio ([^89]|[89][0-9])") + run_cmake(RemoveEmptyCommands) +endif() diff --git a/Tests/RunCMake/add_executable/CMakeLists.txt b/Tests/RunCMake/add_executable/CMakeLists.txt new file mode 100644 index 0000000..ef2163c --- /dev/null +++ b/Tests/RunCMake/add_executable/CMakeLists.txt @@ -0,0 +1,3 @@ +cmake_minimum_required(VERSION 3.1) +project(${RunCMake_TEST} NONE) +include(${RunCMake_TEST}.cmake) diff --git a/Tests/RunCMake/add_executable/NoSources-result.txt b/Tests/RunCMake/add_executable/NoSources-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/add_executable/NoSources-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/add_executable/NoSources-stderr.txt b/Tests/RunCMake/add_executable/NoSources-stderr.txt new file mode 100644 index 0000000..5985905 --- /dev/null +++ b/Tests/RunCMake/add_executable/NoSources-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at NoSources.cmake:[0-9]+ \(add_executable\): + add_executable called with incorrect number of arguments +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\)$ diff --git a/Tests/RunCMake/add_executable/NoSources.cmake b/Tests/RunCMake/add_executable/NoSources.cmake new file mode 100644 index 0000000..563564a --- /dev/null +++ b/Tests/RunCMake/add_executable/NoSources.cmake @@ -0,0 +1 @@ +add_executable(TestExeWithoutSources) diff --git a/Tests/RunCMake/add_executable/NoSourcesButLinkObjects-result.txt b/Tests/RunCMake/add_executable/NoSourcesButLinkObjects-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/add_executable/NoSourcesButLinkObjects-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/add_executable/NoSourcesButLinkObjects-stderr.txt b/Tests/RunCMake/add_executable/NoSourcesButLinkObjects-stderr.txt new file mode 100644 index 0000000..c8afadb --- /dev/null +++ b/Tests/RunCMake/add_executable/NoSourcesButLinkObjects-stderr.txt @@ -0,0 +1,11 @@ +^CMake Error at NoSourcesButLinkObjects.cmake:[0-9]+ \(add_executable\): + add_executable called with incorrect number of arguments +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\) + + +CMake Error at NoSourcesButLinkObjects.cmake:[0-9]+ \(target_link_libraries\): + Cannot specify link libraries for target \"TestExeWithoutSources\" which is + not built by this project. +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\)$ diff --git a/Tests/RunCMake/add_executable/NoSourcesButLinkObjects.cmake b/Tests/RunCMake/add_executable/NoSourcesButLinkObjects.cmake new file mode 100644 index 0000000..d0f2093 --- /dev/null +++ b/Tests/RunCMake/add_executable/NoSourcesButLinkObjects.cmake @@ -0,0 +1,5 @@ +enable_language(CXX) +add_library(ObjectLibDependency OBJECT test.cpp) + +add_executable(TestExeWithoutSources) +target_link_libraries(TestExeWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>) diff --git a/Tests/RunCMake/add_executable/OnlyObjectSources-result.txt b/Tests/RunCMake/add_executable/OnlyObjectSources-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/add_executable/OnlyObjectSources-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/add_executable/OnlyObjectSources-stderr.txt b/Tests/RunCMake/add_executable/OnlyObjectSources-stderr.txt new file mode 100644 index 0000000..ea72d5d --- /dev/null +++ b/Tests/RunCMake/add_executable/OnlyObjectSources-stderr.txt @@ -0,0 +1,11 @@ +^CMake Error at OnlyObjectSources.cmake:[0-9]+ \(add_executable\): + add_executable called with incorrect number of arguments +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\) + + +CMake Error at OnlyObjectSources.cmake:[0-9]+ \(target_sources\): + Cannot specify sources for target \"TestExeWithoutSources\" which is not + built by this project. +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\)$ diff --git a/Tests/RunCMake/add_executable/OnlyObjectSources.cmake b/Tests/RunCMake/add_executable/OnlyObjectSources.cmake new file mode 100644 index 0000000..1c90e9a --- /dev/null +++ b/Tests/RunCMake/add_executable/OnlyObjectSources.cmake @@ -0,0 +1,5 @@ +enable_language(CXX) +add_library(ObjectLibDependency OBJECT test.cpp) + +add_executable(TestExeWithoutSources) +target_sources(TestExeWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>) diff --git a/Tests/RunCMake/add_executable/RunCMakeTest.cmake b/Tests/RunCMake/add_executable/RunCMakeTest.cmake new file mode 100644 index 0000000..70a68f2 --- /dev/null +++ b/Tests/RunCMake/add_executable/RunCMakeTest.cmake @@ -0,0 +1,5 @@ +include(RunCMake) + +run_cmake(NoSources) +run_cmake(OnlyObjectSources) +run_cmake(NoSourcesButLinkObjects) diff --git a/Tests/RunCMake/add_executable/test.cpp b/Tests/RunCMake/add_executable/test.cpp new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/Tests/RunCMake/add_executable/test.cpp diff --git a/Tests/RunCMake/add_library/CMakeLists.txt b/Tests/RunCMake/add_library/CMakeLists.txt new file mode 100644 index 0000000..ef2163c --- /dev/null +++ b/Tests/RunCMake/add_library/CMakeLists.txt @@ -0,0 +1,3 @@ +cmake_minimum_required(VERSION 3.1) +project(${RunCMake_TEST} NONE) +include(${RunCMake_TEST}.cmake) diff --git a/Tests/RunCMake/add_library/INTERFACEwithNoSources.cmake b/Tests/RunCMake/add_library/INTERFACEwithNoSources.cmake new file mode 100644 index 0000000..79188f3 --- /dev/null +++ b/Tests/RunCMake/add_library/INTERFACEwithNoSources.cmake @@ -0,0 +1 @@ +add_library(TestInterfaceLibWithoutSources INTERFACE) diff --git a/Tests/RunCMake/add_library/INTERFACEwithNoSourcesButLinkObjects.cmake b/Tests/RunCMake/add_library/INTERFACEwithNoSourcesButLinkObjects.cmake new file mode 100644 index 0000000..53a48f0 --- /dev/null +++ b/Tests/RunCMake/add_library/INTERFACEwithNoSourcesButLinkObjects.cmake @@ -0,0 +1,5 @@ +enable_language(CXX) +add_library(ObjectLibDependency OBJECT test.cpp) + +add_library(TestInterfaceLibWithoutSources INTERFACE) +target_link_libraries(TestInterfaceLibWithoutSources INTERFACE $<TARGET_OBJECTS:ObjectLibDependency>) diff --git a/Tests/RunCMake/add_library/INTERFACEwithOnlyObjectSources.cmake b/Tests/RunCMake/add_library/INTERFACEwithOnlyObjectSources.cmake new file mode 100644 index 0000000..86fab1d --- /dev/null +++ b/Tests/RunCMake/add_library/INTERFACEwithOnlyObjectSources.cmake @@ -0,0 +1,5 @@ +enable_language(CXX) +add_library(ObjectLibDependency OBJECT test.cpp) + +add_library(TestInterfaceLibWithoutSources INTERFACE) +target_sources(TestInterfaceLibWithoutSources INTERFACE $<TARGET_OBJECTS:ObjectLibDependency>) diff --git a/Tests/RunCMake/add_library/MODULEwithNoSources-result.txt b/Tests/RunCMake/add_library/MODULEwithNoSources-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/add_library/MODULEwithNoSources-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/add_library/MODULEwithNoSources-stderr.txt b/Tests/RunCMake/add_library/MODULEwithNoSources-stderr.txt new file mode 100644 index 0000000..5cf0b1e --- /dev/null +++ b/Tests/RunCMake/add_library/MODULEwithNoSources-stderr.txt @@ -0,0 +1,3 @@ +^You have called ADD_LIBRARY for library TestModuleLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file( +CMake Error: CMake can not determine linker language for target: TestModuleLibWithoutSources)+( +CMake Error: Cannot determine link language for target \"TestModuleLibWithoutSources\".)?$ diff --git a/Tests/RunCMake/add_library/MODULEwithNoSources.cmake b/Tests/RunCMake/add_library/MODULEwithNoSources.cmake new file mode 100644 index 0000000..5df5033 --- /dev/null +++ b/Tests/RunCMake/add_library/MODULEwithNoSources.cmake @@ -0,0 +1 @@ +add_library(TestModuleLibWithoutSources MODULE) diff --git a/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects-result.txt b/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects-stderr.txt b/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects-stderr.txt new file mode 100644 index 0000000..951594a --- /dev/null +++ b/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects-stderr.txt @@ -0,0 +1,3 @@ +^You have called ADD_LIBRARY for library TestModuleLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file( +CMake Error: CMake can not determine linker language for target: TestModuleLibWithoutSources)+( +CMake Error: Cannot determine link language for target \"TestModuleLibWithoutSources\".)*$ diff --git a/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects.cmake b/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects.cmake new file mode 100644 index 0000000..f9d00de --- /dev/null +++ b/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects.cmake @@ -0,0 +1,5 @@ +enable_language(CXX) +add_library(ObjectLibDependency OBJECT test.cpp) + +add_library(TestModuleLibWithoutSources MODULE) +target_link_libraries(TestModuleLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>) diff --git a/Tests/RunCMake/add_library/MODULEwithOnlyObjectSources-stderr.txt b/Tests/RunCMake/add_library/MODULEwithOnlyObjectSources-stderr.txt new file mode 100644 index 0000000..de83755 --- /dev/null +++ b/Tests/RunCMake/add_library/MODULEwithOnlyObjectSources-stderr.txt @@ -0,0 +1 @@ +^You have called ADD_LIBRARY for library TestModuleLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file$ diff --git a/Tests/RunCMake/add_library/MODULEwithOnlyObjectSources.cmake b/Tests/RunCMake/add_library/MODULEwithOnlyObjectSources.cmake new file mode 100644 index 0000000..187481a --- /dev/null +++ b/Tests/RunCMake/add_library/MODULEwithOnlyObjectSources.cmake @@ -0,0 +1,5 @@ +enable_language(CXX) +add_library(ObjectLibDependency OBJECT test.cpp) + +add_library(TestModuleLibWithoutSources MODULE) +target_sources(TestModuleLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>) diff --git a/Tests/RunCMake/add_library/OBJECTwithNoSources-result.txt b/Tests/RunCMake/add_library/OBJECTwithNoSources-result.txt new file mode 100644 index 0000000..9c558e3 --- /dev/null +++ b/Tests/RunCMake/add_library/OBJECTwithNoSources-result.txt @@ -0,0 +1 @@ +. diff --git a/Tests/RunCMake/add_library/OBJECTwithNoSources-stderr.txt b/Tests/RunCMake/add_library/OBJECTwithNoSources-stderr.txt new file mode 100644 index 0000000..099ec4f --- /dev/null +++ b/Tests/RunCMake/add_library/OBJECTwithNoSources-stderr.txt @@ -0,0 +1,2 @@ +^You have called ADD_LIBRARY for library TestObjectLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file( +CMake Error: CMake can not determine linker language for target: TestObjectLibWithoutSources)*$ diff --git a/Tests/RunCMake/add_library/OBJECTwithNoSources.cmake b/Tests/RunCMake/add_library/OBJECTwithNoSources.cmake new file mode 100644 index 0000000..742e829 --- /dev/null +++ b/Tests/RunCMake/add_library/OBJECTwithNoSources.cmake @@ -0,0 +1 @@ +add_library(TestObjectLibWithoutSources OBJECT) diff --git a/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-result.txt b/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-stderr.txt b/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-stderr.txt new file mode 100644 index 0000000..8f20096 --- /dev/null +++ b/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-stderr.txt @@ -0,0 +1,6 @@ +^You have called ADD_LIBRARY for library TestObjectLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file +CMake Error at OBJECTwithNoSourcesButLinkObjects.cmake:[0-9]+ \(target_link_libraries\): + Object library target \"TestObjectLibWithoutSources\" may not link to + anything. +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\)$ diff --git a/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects.cmake b/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects.cmake new file mode 100644 index 0000000..6b4b55f --- /dev/null +++ b/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects.cmake @@ -0,0 +1,5 @@ +enable_language(CXX) +add_library(ObjectLibDependency OBJECT test.cpp) + +add_library(TestObjectLibWithoutSources OBJECT) +target_link_libraries(TestObjectLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>) diff --git a/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-result.txt b/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-stderr.txt b/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-stderr.txt new file mode 100644 index 0000000..f9cbf6b --- /dev/null +++ b/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-stderr.txt @@ -0,0 +1,17 @@ +^You have called ADD_LIBRARY for library TestObjectLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file +CMake Error at OBJECTwithOnlyObjectSources.cmake:[0-9]+ \(add_library\): + OBJECT library \"TestObjectLibWithoutSources\" contains: + + [^ +]*test(\.cpp)?\.o(bj)? + + but may contain only sources that compile, header files, and other files + that would not affect linking of a normal library. +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\) + + +CMake Error at OBJECTwithOnlyObjectSources.cmake:[0-9]+ \(add_library\): + Only executables and non-OBJECT libraries may reference target objects. +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\)$ diff --git a/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources.cmake b/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources.cmake new file mode 100644 index 0000000..ff75a8c --- /dev/null +++ b/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources.cmake @@ -0,0 +1,5 @@ +enable_language(CXX) +add_library(ObjectLibDependency OBJECT test.cpp) + +add_library(TestObjectLibWithoutSources OBJECT) +target_sources(TestObjectLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>) diff --git a/Tests/RunCMake/add_library/RunCMakeTest.cmake b/Tests/RunCMake/add_library/RunCMakeTest.cmake new file mode 100644 index 0000000..0ba6216 --- /dev/null +++ b/Tests/RunCMake/add_library/RunCMakeTest.cmake @@ -0,0 +1,24 @@ +include(RunCMake) + +run_cmake(INTERFACEwithNoSources) +run_cmake(OBJECTwithNoSources) +run_cmake(STATICwithNoSources) +run_cmake(SHAREDwithNoSources) +run_cmake(MODULEwithNoSources) +run_cmake(UNKNOWNwithNoSources) + +run_cmake(INTERFACEwithOnlyObjectSources) +run_cmake(OBJECTwithOnlyObjectSources) +run_cmake(STATICwithOnlyObjectSources) +run_cmake(SHAREDwithOnlyObjectSources) +run_cmake(MODULEwithOnlyObjectSources) +run_cmake(UNKNOWNwithOnlyObjectSources) + +if(NOT RunCMake_GENERATOR STREQUAL "Xcode" OR NOT "$ENV{CMAKE_OSX_ARCHITECTURES}" MATCHES "[;$]") + run_cmake(INTERFACEwithNoSourcesButLinkObjects) + run_cmake(OBJECTwithNoSourcesButLinkObjects) + run_cmake(STATICwithNoSourcesButLinkObjects) + run_cmake(SHAREDwithNoSourcesButLinkObjects) + run_cmake(MODULEwithNoSourcesButLinkObjects) + run_cmake(UNKNOWNwithNoSourcesButLinkObjects) +endif() diff --git a/Tests/RunCMake/add_library/SHAREDwithNoSources-result.txt b/Tests/RunCMake/add_library/SHAREDwithNoSources-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/add_library/SHAREDwithNoSources-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/add_library/SHAREDwithNoSources-stderr.txt b/Tests/RunCMake/add_library/SHAREDwithNoSources-stderr.txt new file mode 100644 index 0000000..228d1cc --- /dev/null +++ b/Tests/RunCMake/add_library/SHAREDwithNoSources-stderr.txt @@ -0,0 +1,3 @@ +^You have called ADD_LIBRARY for library TestSharedLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file( +CMake Error: CMake can not determine linker language for target: TestSharedLibWithoutSources)+( +CMake Error: Cannot determine link language for target \"TestSharedLibWithoutSources\".)*$ diff --git a/Tests/RunCMake/add_library/SHAREDwithNoSources.cmake b/Tests/RunCMake/add_library/SHAREDwithNoSources.cmake new file mode 100644 index 0000000..e147b44 --- /dev/null +++ b/Tests/RunCMake/add_library/SHAREDwithNoSources.cmake @@ -0,0 +1 @@ +add_library(TestSharedLibWithoutSources SHARED) diff --git a/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects-result.txt b/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects-stderr.txt b/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects-stderr.txt new file mode 100644 index 0000000..228d1cc --- /dev/null +++ b/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects-stderr.txt @@ -0,0 +1,3 @@ +^You have called ADD_LIBRARY for library TestSharedLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file( +CMake Error: CMake can not determine linker language for target: TestSharedLibWithoutSources)+( +CMake Error: Cannot determine link language for target \"TestSharedLibWithoutSources\".)*$ diff --git a/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects.cmake b/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects.cmake new file mode 100644 index 0000000..5e3c270 --- /dev/null +++ b/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects.cmake @@ -0,0 +1,5 @@ +enable_language(CXX) +add_library(ObjectLibDependency OBJECT test.cpp) + +add_library(TestSharedLibWithoutSources SHARED) +target_link_libraries(TestSharedLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>) diff --git a/Tests/RunCMake/add_library/SHAREDwithOnlyObjectSources-stderr.txt b/Tests/RunCMake/add_library/SHAREDwithOnlyObjectSources-stderr.txt new file mode 100644 index 0000000..ec350cd --- /dev/null +++ b/Tests/RunCMake/add_library/SHAREDwithOnlyObjectSources-stderr.txt @@ -0,0 +1 @@ +^You have called ADD_LIBRARY for library TestSharedLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file$ diff --git a/Tests/RunCMake/add_library/SHAREDwithOnlyObjectSources.cmake b/Tests/RunCMake/add_library/SHAREDwithOnlyObjectSources.cmake new file mode 100644 index 0000000..09281b0 --- /dev/null +++ b/Tests/RunCMake/add_library/SHAREDwithOnlyObjectSources.cmake @@ -0,0 +1,5 @@ +enable_language(CXX) +add_library(ObjectLibDependency OBJECT test.cpp) + +add_library(TestSharedLibWithoutSources SHARED) +target_sources(TestSharedLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>) diff --git a/Tests/RunCMake/add_library/STATICwithNoSources-result.txt b/Tests/RunCMake/add_library/STATICwithNoSources-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/add_library/STATICwithNoSources-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/add_library/STATICwithNoSources-stderr.txt b/Tests/RunCMake/add_library/STATICwithNoSources-stderr.txt new file mode 100644 index 0000000..830eb22 --- /dev/null +++ b/Tests/RunCMake/add_library/STATICwithNoSources-stderr.txt @@ -0,0 +1,3 @@ +^You have called ADD_LIBRARY for library TestStaticLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file( +CMake Error: Cannot determine link language for target \"TestStaticLibWithoutSources\".)?( +CMake Error: CMake can not determine linker language for target: TestStaticLibWithoutSources)+$ diff --git a/Tests/RunCMake/add_library/STATICwithNoSources.cmake b/Tests/RunCMake/add_library/STATICwithNoSources.cmake new file mode 100644 index 0000000..94a2d9a --- /dev/null +++ b/Tests/RunCMake/add_library/STATICwithNoSources.cmake @@ -0,0 +1 @@ +add_library(TestStaticLibWithoutSources STATIC) diff --git a/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects-result.txt b/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects-stderr.txt b/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects-stderr.txt new file mode 100644 index 0000000..830eb22 --- /dev/null +++ b/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects-stderr.txt @@ -0,0 +1,3 @@ +^You have called ADD_LIBRARY for library TestStaticLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file( +CMake Error: Cannot determine link language for target \"TestStaticLibWithoutSources\".)?( +CMake Error: CMake can not determine linker language for target: TestStaticLibWithoutSources)+$ diff --git a/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects.cmake b/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects.cmake new file mode 100644 index 0000000..b6e137f --- /dev/null +++ b/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects.cmake @@ -0,0 +1,5 @@ +enable_language(CXX) +add_library(ObjectLibDependency OBJECT test.cpp) + +add_library(TestStaticLibWithoutSources STATIC) +target_link_libraries(TestStaticLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>) diff --git a/Tests/RunCMake/add_library/STATICwithOnlyObjectSources-stderr.txt b/Tests/RunCMake/add_library/STATICwithOnlyObjectSources-stderr.txt new file mode 100644 index 0000000..5cd10d4 --- /dev/null +++ b/Tests/RunCMake/add_library/STATICwithOnlyObjectSources-stderr.txt @@ -0,0 +1 @@ +^You have called ADD_LIBRARY for library TestStaticLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file$ diff --git a/Tests/RunCMake/add_library/STATICwithOnlyObjectSources.cmake b/Tests/RunCMake/add_library/STATICwithOnlyObjectSources.cmake new file mode 100644 index 0000000..74a8947 --- /dev/null +++ b/Tests/RunCMake/add_library/STATICwithOnlyObjectSources.cmake @@ -0,0 +1,5 @@ +enable_language(CXX) +add_library(ObjectLibDependency OBJECT test.cpp) + +add_library(TestStaticLibWithoutSources STATIC) +target_sources(TestStaticLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>) diff --git a/Tests/RunCMake/add_library/UNKNOWNwithNoSources.cmake b/Tests/RunCMake/add_library/UNKNOWNwithNoSources.cmake new file mode 100644 index 0000000..dc5d777 --- /dev/null +++ b/Tests/RunCMake/add_library/UNKNOWNwithNoSources.cmake @@ -0,0 +1 @@ +add_library(TestUnknownLibWithoutSources UNKNOWN IMPORTED) diff --git a/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects-result.txt b/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects-stderr.txt b/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects-stderr.txt new file mode 100644 index 0000000..adcd3a2 --- /dev/null +++ b/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects-stderr.txt @@ -0,0 +1,5 @@ +^CMake Error at UNKNOWNwithNoSourcesButLinkObjects.cmake:[0-9]+ \(target_link_libraries\): + Cannot specify link libraries for target \"TestUnknownLibWithoutSources\" + which is not built by this project. +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\)$ diff --git a/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects.cmake b/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects.cmake new file mode 100644 index 0000000..8e014c2 --- /dev/null +++ b/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects.cmake @@ -0,0 +1,5 @@ +enable_language(CXX) +add_library(ObjectLibDependency OBJECT test.cpp) + +add_library(TestUnknownLibWithoutSources UNKNOWN IMPORTED) +target_link_libraries(TestUnknownLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>) diff --git a/Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources-result.txt b/Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources-stderr.txt b/Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources-stderr.txt new file mode 100644 index 0000000..e332281 --- /dev/null +++ b/Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at UNKNOWNwithOnlyObjectSources.cmake:[0-9]+ \(target_sources\): + target_sources called with non-compilable target type +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\)$ diff --git a/Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources.cmake b/Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources.cmake new file mode 100644 index 0000000..604e339 --- /dev/null +++ b/Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources.cmake @@ -0,0 +1,5 @@ +enable_language(CXX) +add_library(ObjectLibDependency OBJECT test.cpp) + +add_library(TestUnknownLibWithoutSources UNKNOWN IMPORTED) +target_sources(TestUnknownLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>) diff --git a/Tests/RunCMake/add_library/test.cpp b/Tests/RunCMake/add_library/test.cpp new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/Tests/RunCMake/add_library/test.cpp diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/CTestConfigCTestScript-stdout.txt b/Tests/RunCMake/ctest_labels_for_subprojects/CTestConfigCTestScript-stdout.txt index ae00e51..05b484d 100644 --- a/Tests/RunCMake/ctest_labels_for_subprojects/CTestConfigCTestScript-stdout.txt +++ b/Tests/RunCMake/ctest_labels_for_subprojects/CTestConfigCTestScript-stdout.txt @@ -1,7 +1,10 @@ 17% tests passed, 5 tests failed out of 6 + Subproject Time Summary: -MyExperimentalFeature += +[0-9.]+ sec \(5 tests\) -MyProductionCode += +[0-9.]+ sec \(1 test\) +MyExperimentalFeature += +[0-9.]+ sec\*proc \(5 tests\) +MyProductionCode += +[0-9.]+ sec\*proc \(1 test\) ++ +Label Time Summary: +NotASubproject += +[0-9.]+ sec\*proc \(6 tests\) + Total Test time \(real\) = +[0-9.]+ sec diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariable-stdout.txt b/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariable-stdout.txt index ae00e51..05b484d 100644 --- a/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariable-stdout.txt +++ b/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariable-stdout.txt @@ -1,7 +1,10 @@ 17% tests passed, 5 tests failed out of 6 + Subproject Time Summary: -MyExperimentalFeature += +[0-9.]+ sec \(5 tests\) -MyProductionCode += +[0-9.]+ sec \(1 test\) +MyExperimentalFeature += +[0-9.]+ sec\*proc \(5 tests\) +MyProductionCode += +[0-9.]+ sec\*proc \(1 test\) ++ +Label Time Summary: +NotASubproject += +[0-9.]+ sec\*proc \(6 tests\) + Total Test time \(real\) = +[0-9.]+ sec diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-stdout.txt b/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-stdout.txt index a78a99a..c2c1bc7 100644 --- a/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-stdout.txt +++ b/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-stdout.txt @@ -1,6 +1,9 @@ 0% tests passed, 1 tests failed out of 1 + Subproject Time Summary: -MyThirdPartyDependency += +[0-9.]+ sec \(1 test\) +MyThirdPartyDependency += +[0-9.]+ sec\*proc \(1 test\) ++ +Label Time Summary: +NotASubproject += +[0-9.]+ sec\*proc \(1 test\) + Total Test time \(real\) = +[0-9.]+ sec diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCMakeLists-stdout.txt b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCMakeLists-stdout.txt index b5d76a9..3567a92 100644 --- a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCMakeLists-stdout.txt +++ b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCMakeLists-stdout.txt @@ -1,6 +1,6 @@ 50% tests passed, 1 tests failed out of 2 + Subproject Time Summary: -MySubproject += +[0-9.]+ sec \(2 tests\) +MySubproject += +[0-9.]+ sec\*proc \(2 tests\) + Total Test time \(real\) = +[0-9.]+ sec diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfig-stdout.txt b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfig-stdout.txt index 01851fd..3a71022 100644 --- a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfig-stdout.txt +++ b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfig-stdout.txt @@ -1,6 +1,9 @@ 67% tests passed, 1 tests failed out of 3 + Subproject Time Summary: -MySubproject += +[0-9.]+ sec \(2 tests\) +MySubproject += +[0-9.]+ sec\*proc \(2 tests\) ++ +Label Time Summary: +NotASubproject += +[0-9.]+ sec\*proc \(1 test\) + Total Test time \(real\) = +[0-9.]+ sec diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfigNoSummary-stdout.txt b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfigNoSummary-stdout.txt index 0209bfe..1146bfe 100644 --- a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfigNoSummary-stdout.txt +++ b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfigNoSummary-stdout.txt @@ -1,7 +1,6 @@ 67% tests passed, 1 tests failed out of 3 + Label Time Summary: -MySubproject += +[0-9.]+ sec \(2 tests\) -NotASubproject += +[0-9.]+ sec \(1 test\) +NotASubproject += +[0-9.]+ sec\*proc \(1 test\) + Total Test time \(real\) = +[0-9.]+ sec diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCommandLine-stdout.txt b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCommandLine-stdout.txt index b5d76a9..3567a92 100644 --- a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCommandLine-stdout.txt +++ b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCommandLine-stdout.txt @@ -1,6 +1,6 @@ 50% tests passed, 1 tests failed out of 2 + Subproject Time Summary: -MySubproject += +[0-9.]+ sec \(2 tests\) +MySubproject += +[0-9.]+ sec\*proc \(2 tests\) + Total Test time \(real\) = +[0-9.]+ sec diff --git a/Tests/RunCMake/get_filename_component/KnownComponents.cmake b/Tests/RunCMake/get_filename_component/KnownComponents.cmake index 7dfb55d..ac77ac3 100644 --- a/Tests/RunCMake/get_filename_component/KnownComponents.cmake +++ b/Tests/RunCMake/get_filename_component/KnownComponents.cmake @@ -80,6 +80,17 @@ get_filename_component(test_program_name "/ arg1 arg2" PROGRAM check("PROGRAM with args output: name" "${test_program_name}" "/") check("PROGRAM with args output: args" "${test_program_args}" " arg1 arg2") +get_filename_component(test_program_name " " PROGRAM) +check("PROGRAM with just a space" "${test_program_name}" "") + +get_filename_component(test_program_name "${CMAKE_CURRENT_LIST_FILE}" PROGRAM) +check("PROGRAM specified explicitly without quoting" "${test_program_name}" "${CMAKE_CURRENT_LIST_FILE}") + +get_filename_component(test_program_name "\"${CMAKE_CURRENT_LIST_FILE}\" arg1 arg2" PROGRAM + PROGRAM_ARGS test_program_args) +check("PROGRAM specified explicitly with arguments: name" "${test_program_name}" "${CMAKE_CURRENT_LIST_FILE}") +check("PROGRAM specified explicitly with arguments: args" "${test_program_args}" " arg1 arg2") + list(APPEND non_cache_vars test_program_name) list(APPEND non_cache_vars test_program_args) diff --git a/Tests/RunCMake/get_property/source_properties-stderr.txt b/Tests/RunCMake/get_property/source_properties-stderr.txt index 0a46f96..00a9b82 100644 --- a/Tests/RunCMake/get_property/source_properties-stderr.txt +++ b/Tests/RunCMake/get_property/source_properties-stderr.txt @@ -3,4 +3,10 @@ get_property: --><-- get_source_file_property: -->value<-- get_property: -->value<-- get_source_file_property: -->NOTFOUND<-- -get_property: --><--$ +get_property: --><-- +get_source_file_property: -->value<-- +get_property: -->value<-- +get_source_file_property: -->NOTFOUND<-- +get_property: --><-- +get_source_file_property: -->value<-- +get_property: -->value<--$ diff --git a/Tests/RunCMake/get_property/source_properties.cmake b/Tests/RunCMake/get_property/source_properties.cmake index 263ffe1..12d2d07 100644 --- a/Tests/RunCMake/get_property/source_properties.cmake +++ b/Tests/RunCMake/get_property/source_properties.cmake @@ -13,3 +13,13 @@ set_source_files_properties(file.c PROPERTIES empty "" custom value) check_source_file_property(file.c empty) check_source_file_property(file.c custom) check_source_file_property(file.c noexist) + +# Test strange legacy behavior in which the order in which source files are +# first accessed affects how properties are applied without an extension. +# See also issue #15208. +get_property(lang SOURCE ${CMAKE_CURRENT_BINARY_DIR}/file2.c PROPERTY LANGUAGE) +get_property(lang SOURCE ${CMAKE_CURRENT_BINARY_DIR}/file2.h PROPERTY LANGUAGE) +set_property(SOURCE file2 PROPERTY custom value) # set property without extension +check_source_file_property(file2 custom) # should have property +check_source_file_property(file2.h custom) # should not have property +check_source_file_property(file2.c custom) # should have property diff --git a/Tests/RunCMake/pseudo_cppcheck.c b/Tests/RunCMake/pseudo_cppcheck.c index 32e6e28..8667e5e 100644 --- a/Tests/RunCMake/pseudo_cppcheck.c +++ b/Tests/RunCMake/pseudo_cppcheck.c @@ -1,7 +1,18 @@ #include <stdio.h> +#include <stdlib.h> +#include <string.h> -int main(void) +int main(int argc, char* argv[]) { + int i; + for (i = 1; i < argc; ++i) { + if (strcmp(argv[i], "-bad") == 0) + if (strcmp(argv[i], "-bad") == 0) { + fprintf(stdout, "stdout from bad command line arg '-bad'\n"); + fprintf(stderr, "stderr from bad command line arg '-bad'\n"); + return 1; + } + } fprintf(stderr, "[/foo/bar.c:2]: (error) Array 'abc[10]' accessed at index 12," " which is out of bounds.\n"); diff --git a/Tests/RunCMake/string/Timestamp-stderr.txt b/Tests/RunCMake/string/Timestamp-stderr.txt index 653974c..cd4dcb3 100644 --- a/Tests/RunCMake/string/Timestamp-stderr.txt +++ b/Tests/RunCMake/string/Timestamp-stderr.txt @@ -1 +1 @@ -RESULT=2005-08-07 23:19:49 Sun Aug 05 day=219 wd=0 week=32 %I=11 epoch=1123456789 +RESULT=2005-08-07 23:19:49 Sunday=Sun August=Aug 05 day=219 wd=0 week=32 %I=11 epoch=1123456789 diff --git a/Tests/RunCMake/string/Timestamp.cmake b/Tests/RunCMake/string/Timestamp.cmake index d242039..cba258d 100644 --- a/Tests/RunCMake/string/Timestamp.cmake +++ b/Tests/RunCMake/string/Timestamp.cmake @@ -1,3 +1,3 @@ set(ENV{SOURCE_DATE_EPOCH} "1123456789") -string(TIMESTAMP RESULT "%Y-%m-%d %H:%M:%S %a %b %y day=%j wd=%w week=%U %%I=%I epoch=%s" UTC) +string(TIMESTAMP RESULT "%Y-%m-%d %H:%M:%S %A=%a %B=%b %y day=%j wd=%w week=%U %%I=%I epoch=%s" UTC) message("RESULT=${RESULT}") diff --git a/Tests/RunCMake/target_link_libraries/RunCMakeTest.cmake b/Tests/RunCMake/target_link_libraries/RunCMakeTest.cmake index 1466fbf..b1c9435 100644 --- a/Tests/RunCMake/target_link_libraries/RunCMakeTest.cmake +++ b/Tests/RunCMake/target_link_libraries/RunCMakeTest.cmake @@ -10,3 +10,4 @@ run_cmake(SubDirTarget) run_cmake(SharedDepNotTarget) run_cmake(StaticPrivateDepNotExported) run_cmake(StaticPrivateDepNotTarget) +run_cmake(UNKNOWN-IMPORTED-GLOBAL) diff --git a/Tests/RunCMake/target_link_libraries/UNKNOWN-IMPORTED-GLOBAL.cmake b/Tests/RunCMake/target_link_libraries/UNKNOWN-IMPORTED-GLOBAL.cmake new file mode 100644 index 0000000..f52fa30 --- /dev/null +++ b/Tests/RunCMake/target_link_libraries/UNKNOWN-IMPORTED-GLOBAL.cmake @@ -0,0 +1,4 @@ +enable_language(C) +add_library(UnknownImportedGlobal UNKNOWN IMPORTED GLOBAL) +add_library(mylib empty.c) +target_link_libraries(mylib UnknownImportedGlobal) diff --git a/Tests/RunCMake/variable_watch/ModifyWatchInCallback.cmake b/Tests/RunCMake/variable_watch/ModifyWatchInCallback.cmake new file mode 100644 index 0000000..1dee837 --- /dev/null +++ b/Tests/RunCMake/variable_watch/ModifyWatchInCallback.cmake @@ -0,0 +1,17 @@ +function (watch2) + +endfunction () + +function (watch1) + variable_watch(watched watch2) + variable_watch(watched watch2) + variable_watch(watched watch2) + variable_watch(watched watch2) + variable_watch(watched watch2) + variable_watch(watched watch2) +endfunction () + +variable_watch(watched watch1) +variable_watch(watched watch2) + +set(access "${watched}") diff --git a/Tests/RunCMake/variable_watch/RunCMakeTest.cmake b/Tests/RunCMake/variable_watch/RunCMakeTest.cmake index 9becb4c..2fa6275 100644 --- a/Tests/RunCMake/variable_watch/RunCMakeTest.cmake +++ b/Tests/RunCMake/variable_watch/RunCMakeTest.cmake @@ -3,3 +3,4 @@ include(RunCMake) run_cmake(ModifiedAccess) run_cmake(NoWatcher) run_cmake(WatchTwice) +run_cmake(ModifyWatchInCallback) diff --git a/Tests/SameName/CMakeLists.txt b/Tests/SameName/CMakeLists.txt deleted file mode 100644 index d78879d..0000000 --- a/Tests/SameName/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required (VERSION 2.6) -project(SameName C) - -add_subdirectory(Lib1) - -include_directories(${PROJECT_SOURCE_DIR}/Lib1) -add_subdirectory(Exe1) diff --git a/Tests/SameName/Exe1/CMakeLists.txt b/Tests/SameName/Exe1/CMakeLists.txt deleted file mode 100644 index b9182f2..0000000 --- a/Tests/SameName/Exe1/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -# a target with the same name as a target in a different dir -add_executable(mytest_exe conly.c) -set_target_properties(mytest_exe PROPERTIES OUTPUT_NAME mytest) -target_link_libraries(mytest_exe mytest) - -# and two targets in the same dir with the same name -add_library(mytest2 ../Lib1/libc1.c) - -add_executable(mytest2_exe conly.c) -set_target_properties(mytest2_exe PROPERTIES OUTPUT_NAME mytest2) -target_link_libraries(mytest2_exe mytest2) diff --git a/Tests/SameName/Exe1/conly.c b/Tests/SameName/Exe1/conly.c deleted file mode 100644 index 8f2ce05..0000000 --- a/Tests/SameName/Exe1/conly.c +++ /dev/null @@ -1,11 +0,0 @@ -#include "libc1.h" -#include <stdio.h> - -int main() -{ - if (LibC1Func() != 2.0) { - printf("Problem with libc1\n"); - return 1; - } - return 0; -} diff --git a/Tests/SameName/Lib1/CMakeLists.txt b/Tests/SameName/Lib1/CMakeLists.txt deleted file mode 100644 index 40fa154..0000000 --- a/Tests/SameName/Lib1/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -add_library(mytest libc1.c) diff --git a/Tests/SameName/Lib1/libc1.c b/Tests/SameName/Lib1/libc1.c deleted file mode 100644 index b01e1e1..0000000 --- a/Tests/SameName/Lib1/libc1.c +++ /dev/null @@ -1,4 +0,0 @@ -float LibC1Func() -{ - return 2.0; -} diff --git a/Tests/SameName/Lib1/libc1.h b/Tests/SameName/Lib1/libc1.h deleted file mode 100644 index 84c94a9..0000000 --- a/Tests/SameName/Lib1/libc1.h +++ /dev/null @@ -1 +0,0 @@ -extern float LibC1Func(); diff --git a/Tests/Server/CMakeLists.txt b/Tests/Server/CMakeLists.txt index 2ad05c3..08bef0c 100644 --- a/Tests/Server/CMakeLists.txt +++ b/Tests/Server/CMakeLists.txt @@ -16,7 +16,7 @@ macro(do_test bsname file) ) if (NOT test_result EQUAL 0) - message(SEND_ERROR "TEST FAILED") + message(SEND_ERROR "TEST FAILED: ${test_result}") endif() endmacro() diff --git a/Tests/Server/server-test.py b/Tests/Server/server-test.py index f5a3f28..9380910 100644 --- a/Tests/Server/server-test.py +++ b/Tests/Server/server-test.py @@ -111,4 +111,5 @@ for obj in testData: print("Completed") cmakelib.exitProc(proc) +print('cmake-server exited: %d' % proc.returncode) sys.exit(proc.returncode) diff --git a/Tests/SimpleExclude/CMakeLists.txt b/Tests/SimpleExclude/CMakeLists.txt deleted file mode 100644 index baca23e..0000000 --- a/Tests/SimpleExclude/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -cmake_minimum_required (VERSION 2.6) -project(SimpleExclude C) - -set(EXECUTABLE_OUTPUT_PATH "${SimpleExclude_BINARY_DIR}" CACHE INTERNAL "" FORCE) -set(LIBRARY_OUTPUT_PATH "${SimpleExclude_BINARY_DIR}" CACHE INTERNAL "" FORCE) - -add_subdirectory(dirC EXCLUDE_FROM_ALL) -add_subdirectory(dirD) - -configure_file("${CMAKE_CURRENT_SOURCE_DIR}/run.cmake.in" - "${CMAKE_CURRENT_BINARY_DIR}/run.cmake" @ONLY) diff --git a/Tests/SimpleExclude/dirC/CMakeLists.txt b/Tests/SimpleExclude/dirC/CMakeLists.txt deleted file mode 100644 index 9b59fda..0000000 --- a/Tests/SimpleExclude/dirC/CMakeLists.txt +++ /dev/null @@ -1,3 +0,0 @@ -add_subdirectory(dirA EXCLUDE_FROM_ALL) -add_subdirectory(dirB) - diff --git a/Tests/SimpleExclude/dirC/dirA/CMakeLists.txt b/Tests/SimpleExclude/dirC/dirA/CMakeLists.txt deleted file mode 100644 index 52fac81..0000000 --- a/Tests/SimpleExclude/dirC/dirA/CMakeLists.txt +++ /dev/null @@ -1,10 +0,0 @@ -add_library(t1 STATIC t1.c) - -add_library(t2 STATIC t2.c) - -add_executable(t3 t3.c) - -add_executable(t4 t4.c) - -add_executable(t5 t5.c) -target_link_libraries(t5 t1) diff --git a/Tests/SimpleExclude/dirC/dirA/t1.c b/Tests/SimpleExclude/dirC/dirA/t1.c deleted file mode 100644 index 67fe06f..0000000 --- a/Tests/SimpleExclude/dirC/dirA/t1.c +++ /dev/null @@ -1,8 +0,0 @@ -#include <stdio.h> - -int tlib1func() -{ - Should not be build unless target directory A, B, or C are build; - printf("This is T1\n"); - return 5; -} diff --git a/Tests/SimpleExclude/dirC/dirA/t2.c b/Tests/SimpleExclude/dirC/dirA/t2.c deleted file mode 100644 index 6aaf406..0000000 --- a/Tests/SimpleExclude/dirC/dirA/t2.c +++ /dev/null @@ -1,7 +0,0 @@ -#include <stdio.h> - -int tlib2func() -{ - printf("This is T2\n"); - return 2; -} diff --git a/Tests/SimpleExclude/dirC/dirA/t3.c b/Tests/SimpleExclude/dirC/dirA/t3.c deleted file mode 100644 index 1366dc0..0000000 --- a/Tests/SimpleExclude/dirC/dirA/t3.c +++ /dev/null @@ -1,7 +0,0 @@ -#include <stdio.h> - -int main(int argc, char* argv[]) -{ - Should not be build unless target directory A, B, or C are build; - return 0; -} diff --git a/Tests/SimpleExclude/dirC/dirA/t4.c b/Tests/SimpleExclude/dirC/dirA/t4.c deleted file mode 100644 index b0e4000..0000000 --- a/Tests/SimpleExclude/dirC/dirA/t4.c +++ /dev/null @@ -1,17 +0,0 @@ -#include <stdio.h> - -#ifdef __CLASSIC_C__ -int main() -{ - int ac; - char* av[]; -#else -int main(int ac, char* av[]) -{ -#endif - if (ac > 1000) { - return *av[0]; - } - printf("This is T4. This one should work.\n"); - return 0; -} diff --git a/Tests/SimpleExclude/dirC/dirA/t5.c b/Tests/SimpleExclude/dirC/dirA/t5.c deleted file mode 100644 index 1fba212..0000000 --- a/Tests/SimpleExclude/dirC/dirA/t5.c +++ /dev/null @@ -1,7 +0,0 @@ -#include <stdio.h> - -int main(int argc, char* argv[]) -{ - Should not be build unless target directory A, B, or C are build; - return 5; -} diff --git a/Tests/SimpleExclude/dirC/dirB/CMakeLists.txt b/Tests/SimpleExclude/dirC/dirB/CMakeLists.txt deleted file mode 100644 index ea4650c..0000000 --- a/Tests/SimpleExclude/dirC/dirB/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -add_library(t6 STATIC t6.c) - -add_library(t7 STATIC t7.c) -target_link_libraries(t7 t2) - diff --git a/Tests/SimpleExclude/dirC/dirB/t6.c b/Tests/SimpleExclude/dirC/dirB/t6.c deleted file mode 100644 index e8877df..0000000 --- a/Tests/SimpleExclude/dirC/dirB/t6.c +++ /dev/null @@ -1,8 +0,0 @@ -#include <stdio.h> - -int tlib6func() -{ - Should not be build unless target directory B, or C are build; - printf("This is T6\n"); - return 6; -} diff --git a/Tests/SimpleExclude/dirC/dirB/t7.c b/Tests/SimpleExclude/dirC/dirB/t7.c deleted file mode 100644 index b613e91..0000000 --- a/Tests/SimpleExclude/dirC/dirB/t7.c +++ /dev/null @@ -1,15 +0,0 @@ -#include <stdio.h> - -extern int tlib2func(); - -int tlib7func() -{ - printf("This is T7\n"); - - if (tlib2func() != 2) { - fprintf(stderr, "Something wrong with T2\n"); - return 1; - } - - return 7; -} diff --git a/Tests/SimpleExclude/dirD/CMakeLists.txt b/Tests/SimpleExclude/dirD/CMakeLists.txt deleted file mode 100644 index 44b8c27..0000000 --- a/Tests/SimpleExclude/dirD/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -add_library(t8 STATIC t8.c) - -add_executable(t9 t9.c) -target_link_libraries(t9 t7) - -add_custom_target(t4_custom ALL) -add_dependencies(t4_custom t4) diff --git a/Tests/SimpleExclude/dirD/t8.c b/Tests/SimpleExclude/dirD/t8.c deleted file mode 100644 index bddec6f..0000000 --- a/Tests/SimpleExclude/dirD/t8.c +++ /dev/null @@ -1,7 +0,0 @@ -#include <stdio.h> - -int tlib8func() -{ - printf("This is T8\n"); - return 8; -} diff --git a/Tests/SimpleExclude/dirD/t9.c b/Tests/SimpleExclude/dirD/t9.c deleted file mode 100644 index 9954ea5..0000000 --- a/Tests/SimpleExclude/dirD/t9.c +++ /dev/null @@ -1,24 +0,0 @@ -#include <stdio.h> - -extern int tlib7func(); - -#ifdef __CLASSIC_C__ -int main() -{ - int ac; - char* av[]; -#else -int main(int ac, char* av[]) -{ -#endif - if (ac > 1000) { - return *av[0]; - } - printf("This is T9. This one should work.\n"); - - if (tlib7func() != 7) { - fprintf(stderr, "Something wrong with T7\n"); - return 1; - } - return 0; -} diff --git a/Tests/SimpleExclude/run.cmake.in b/Tests/SimpleExclude/run.cmake.in deleted file mode 100644 index d31d2e5..0000000 --- a/Tests/SimpleExclude/run.cmake.in +++ /dev/null @@ -1,13 +0,0 @@ -set(t4_name "\"@CMAKE_CURRENT_BINARY_DIR@${CFG_DIR}/t4\"") -exec_program("${t4_name}" RETURN_VALUE "t4_var") -message("T4 ${t4_name} resulted ${t4_var}") - -set(t9_name "\"@CMAKE_CURRENT_BINARY_DIR@${CFG_DIR}/t9\"") -exec_program("${t9_name}" RETURN_VALUE "t9_var") -message("T9 ${t9_name} resulted ${t9_var}") - -if ( "${t4_var}" EQUAL "0" AND "${t9_var}" EQUAL "0" ) - message("Everything is good, Yoshimi won...") -else () - message(FATAL_ERROR "Yoshimi lost... The evil pink robots will take over the world") -endif () diff --git a/Tests/VSGNUFortran/runtest.cmake.in b/Tests/VSGNUFortran/runtest.cmake.in index 987207b..fc05715 100644 --- a/Tests/VSGNUFortran/runtest.cmake.in +++ b/Tests/VSGNUFortran/runtest.cmake.in @@ -14,7 +14,7 @@ file(TO_NATIVE_PATH "${MINGW_PATH}" MINGW_PATH) string(REPLACE "\\" "\\\\" MINGW_PATH "${MINGW_PATH}") message("${MINGW_PATH}") set(test_exe "@VSGNUFortran_BINARY_DIR@/bin/c_using_fortran.exe") -set(ENV{PATH} "${MINGW_PATH}";$ENV{PATH}) +set(ENV{PATH} "${MINGW_PATH};$ENV{PATH}") message("run ${test_exe}") execute_process(COMMAND "${test_exe}" RESULT_VARIABLE res) diff --git a/Tests/VSResource/CMakeLists.txt b/Tests/VSResource/CMakeLists.txt index 718e624..fb47c7e 100644 --- a/Tests/VSResource/CMakeLists.txt +++ b/Tests/VSResource/CMakeLists.txt @@ -56,3 +56,10 @@ endif() set_property(TARGET VSResource PROPERTY VS_GLOBAL_CMakeTestVsGlobalVariable "test val") + +if(CMAKE_GENERATOR MATCHES "Ninja|Visual Studio") + cmake_policy(PUSH) + cmake_policy(SET CMP0037 OLD) + add_library("My ResourceLib" lib.cpp lib.rc) + cmake_policy(POP) +endif() diff --git a/Utilities/IWYU/mapping.imp b/Utilities/IWYU/mapping.imp index 349945a..3240edf 100644 --- a/Utilities/IWYU/mapping.imp +++ b/Utilities/IWYU/mapping.imp @@ -49,12 +49,6 @@ #{ symbol: [ "std::pair", private, "<map>", public ] }, #{ symbol: [ "std::pair", private, "<set>", public ] }, - # IWYU wrongly suggests to include "cm_auto_ptr.hxx" in some places. This - # might be a misinterpretation of a template specialization in <utility>. - # As a workaround, map the symbol auto_ptr to "cmConfigure.h". - # This will still correctly require "cm_auto_ptr.hxx" for CM_AUTO_PTR. - { symbol: [ "cm::auto_ptr", private, "\"cmConfigure.h\"", public ] }, - # __decay_and_strip is used internally in the C++11 standard library. # IWYU does not classify it as internal and suggests to add <type_traits>. # To ignore it, we simply map it to a file that is included anyway. diff --git a/Utilities/cmlibarchive/libarchive/archive_platform.h b/Utilities/cmlibarchive/libarchive/archive_platform.h index 4cb8f81..f33208c 100644 --- a/Utilities/cmlibarchive/libarchive/archive_platform.h +++ b/Utilities/cmlibarchive/libarchive/archive_platform.h @@ -52,6 +52,17 @@ #error Oops: No config.h and no pre-built configuration in archive_platform.h. #endif +/* On macOS check for some symbols based on the deployment target version. */ +#if defined(__APPLE__) +# undef HAVE_FUTIMENS +# undef HAVE_UTIMENSAT +# include <AvailabilityMacros.h> +# if MAC_OS_X_VERSION_MIN_REQUIRED >= 101300 +# define HAVE_FUTIMENS 1 +# define HAVE_UTIMENSAT 1 +# endif +#endif + /* It should be possible to get rid of this by extending the feature-test * macros to cover Windows API functions, probably along with non-trivial * refactoring of code to find structures that sit more cleanly on top of diff --git a/Utilities/cmlibuv/include/uv-unix.h b/Utilities/cmlibuv/include/uv-unix.h index d775450..ff59bcb 100644 --- a/Utilities/cmlibuv/include/uv-unix.h +++ b/Utilities/cmlibuv/include/uv-unix.h @@ -44,7 +44,9 @@ #include "uv-threadpool.h" -#if defined(__linux__) +#ifdef CMAKE_BOOTSTRAP +# include "uv-posix.h" +#elif defined(__linux__) # include "uv-linux.h" #elif defined (__MVS__) # include "uv-os390.h" @@ -124,6 +126,17 @@ typedef int uv_file; typedef int uv_os_sock_t; typedef int uv_os_fd_t; +#ifdef CMAKE_BOOTSTRAP +#define UV_ONCE_INIT 0 +typedef int uv_once_t; +typedef int uv_thread_t; +typedef int uv_mutex_t; +typedef int uv_rwlock_t; +typedef int uv_sem_t; +typedef int uv_cond_t; +typedef int uv_key_t; +typedef int uv_barrier_t; +#else #define UV_ONCE_INIT PTHREAD_ONCE_INIT typedef pthread_once_t uv_once_t; @@ -134,6 +147,7 @@ typedef UV_PLATFORM_SEM_T uv_sem_t; typedef pthread_cond_t uv_cond_t; typedef pthread_key_t uv_key_t; typedef pthread_barrier_t uv_barrier_t; +#endif /* Platform-specific definitions for uv_spawn support. */ diff --git a/Utilities/cmlibuv/src/unix/cmake-bootstrap.c b/Utilities/cmlibuv/src/unix/cmake-bootstrap.c new file mode 100644 index 0000000..4f32d03 --- /dev/null +++ b/Utilities/cmlibuv/src/unix/cmake-bootstrap.c @@ -0,0 +1,139 @@ +#include "uv.h" +#include "internal.h" + +int uv__tcp_nodelay(int fd, int on) { + errno = EINVAL; + return -1; +} + +int uv__tcp_keepalive(int fd, int on, unsigned int delay) { + errno = EINVAL; + return -1; +} + +int uv_tcp_listen(uv_tcp_t* tcp, int backlog, uv_connection_cb cb) { + return -EINVAL; +} + +int uv_udp_open(uv_udp_t* handle, uv_os_sock_t sock) { + return -EINVAL; +} + +void uv__tcp_close(uv_tcp_t* handle) { +} + +void uv__udp_close(uv_udp_t* handle) { +} + +void uv__udp_finish_close(uv_udp_t* handle) { +} + +void uv__fs_poll_close(uv_fs_poll_t* handle) { +} + +int uv_async_init(uv_loop_t* loop, uv_async_t* handle, uv_async_cb async_cb) { + return 0; +} + +void uv__async_close(uv_async_t* handle) { +} + +int uv__async_fork(uv_loop_t* loop) { + return 0; +} + +void uv__async_stop(uv_loop_t* loop) { +} + +void uv__work_submit(uv_loop_t* loop, struct uv__work* w, + void (*work)(struct uv__work* w), + void (*done)(struct uv__work* w, int status)) { + abort(); +} + +void uv__work_done(uv_async_t* handle) { +} + +int uv__pthread_atfork(void (*prepare)(void), void (*parent)(void), + void (*child)(void)) { + return 0; +} + +int uv__pthread_sigmask(int how, const sigset_t* set, sigset_t* oset) { + return 0; +} + +int uv_mutex_init(uv_mutex_t* mutex) { + return 0; +} + +void uv_mutex_destroy(uv_mutex_t* mutex) { +} + +void uv_mutex_lock(uv_mutex_t* mutex) { +} + +void uv_mutex_unlock(uv_mutex_t* mutex) { +} + +int uv_rwlock_init(uv_rwlock_t* rwlock) { + return 0; +} + +void uv_rwlock_destroy(uv_rwlock_t* rwlock) { +} + +void uv_rwlock_wrlock(uv_rwlock_t* rwlock) { +} + +void uv_rwlock_wrunlock(uv_rwlock_t* rwlock) { +} + +void uv_rwlock_rdlock(uv_rwlock_t* rwlock) { +} + +void uv_rwlock_rdunlock(uv_rwlock_t* rwlock) { +} + +void uv_once(uv_once_t* guard, void (*callback)(void)) { + if (*guard) { + return; + } + *guard = 1; + callback(); +} + +#if defined(__linux__) +int uv__accept4(int fd, struct sockaddr* addr, socklen_t* addrlen, int flags) { + errno = ENOSYS; + return -1; +} + +int uv__dup3(int oldfd, int newfd, int flags) { + errno = ENOSYS; + return -1; +} + +int uv__pipe2(int pipefd[2], int flags) { + errno = ENOSYS; + return -1; +} + +ssize_t uv__preadv(int fd, const struct iovec *iov, int iovcnt, + int64_t offset) { + errno = ENOSYS; + return -1; +} + +ssize_t uv__pwritev(int fd, const struct iovec *iov, int iovcnt, + int64_t offset) { + errno = ENOSYS; + return -1; +} + +int uv__utimesat(int dirfd, const char* path, const struct timespec times[2], + int flags) { + errno = ENOSYS; + return -1; +} +#endif diff --git a/Utilities/cmlibuv/src/unix/fs.c b/Utilities/cmlibuv/src/unix/fs.c index 8a4ba7a..82c91ef 100644 --- a/Utilities/cmlibuv/src/unix/fs.c +++ b/Utilities/cmlibuv/src/unix/fs.c @@ -244,7 +244,7 @@ skip: #endif } -#if defined(__sun) && _XOPEN_SOURCE < 600 +#if defined(__sun) && (_XOPEN_SOURCE < 600 || defined(CMAKE_BOOTSTRAP)) static char* uv__mkdtemp(char *template) { if (!mktemp(template) || mkdir(template, 0700)) diff --git a/Utilities/cmlibuv/src/unix/internal.h b/Utilities/cmlibuv/src/unix/internal.h index 2e3afa6..e9f7908 100644 --- a/Utilities/cmlibuv/src/unix/internal.h +++ b/Utilities/cmlibuv/src/unix/internal.h @@ -59,7 +59,17 @@ # include <AvailabilityMacros.h> #endif -#if defined(__ANDROID__) +#if defined(CMAKE_BOOTSTRAP) +# undef pthread_atfork +# define pthread_atfork(prepare, parent, child) \ + uv__pthread_atfork(prepare, parent, child) +int uv__pthread_atfork(void (*prepare)(void), void (*parent)(void), + void (*child)(void)); +# undef pthread_sigmask +# define pthread_sigmask(how, set, oldset) \ + uv__pthread_sigmask(how, set, oldset) +int uv__pthread_sigmask(int how, const sigset_t* set, sigset_t* oset); +#elif defined(__ANDROID__) int uv__pthread_sigmask(int how, const sigset_t* set, sigset_t* oset); # ifdef pthread_sigmask # undef pthread_sigmask @@ -261,7 +271,7 @@ FILE* uv__open_file(const char* path); int uv__getpwuid_r(uv_passwd_t* pwd); -#if defined(__APPLE__) +#if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP) int uv___stream_fd(const uv_stream_t* handle); #define uv__stream_fd(handle) (uv___stream_fd((const uv_stream_t*) (handle))) #else diff --git a/Utilities/cmlibuv/src/unix/pipe.c b/Utilities/cmlibuv/src/unix/pipe.c index 7ba1bf8..e3d436d 100644 --- a/Utilities/cmlibuv/src/unix/pipe.c +++ b/Utilities/cmlibuv/src/unix/pipe.c @@ -136,7 +136,7 @@ int uv_pipe_open(uv_pipe_t* handle, uv_file fd) { if (err) return err; -#if defined(__APPLE__) +#if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP) err = uv__stream_try_select((uv_stream_t*) handle, &fd); if (err) return err; diff --git a/Utilities/cmlibuv/src/unix/posix-hrtime.c b/Utilities/cmlibuv/src/unix/posix-hrtime.c index 323dfc2..a264250 100644 --- a/Utilities/cmlibuv/src/unix/posix-hrtime.c +++ b/Utilities/cmlibuv/src/unix/posix-hrtime.c @@ -22,6 +22,29 @@ #include "uv.h" #include "internal.h" +#if defined(__APPLE__) +/* Special case for CMake bootstrap: no clock_gettime on macOS < 10.12 */ + +#ifndef CMAKE_BOOTSTRAP +#error "This code path meant only for use during CMake bootstrap." +#endif + +#include <mach/mach.h> +#include <mach/mach_time.h> + +uint64_t uv__hrtime(uv_clocktype_t type) { + static mach_timebase_info_data_t info; + + if ((ACCESS_ONCE(uint32_t, info.numer) == 0 || + ACCESS_ONCE(uint32_t, info.denom) == 0) && + mach_timebase_info(&info) != KERN_SUCCESS) + abort(); + + return mach_absolute_time() * info.numer / info.denom; +} + +#else + #include <stdint.h> #include <time.h> @@ -33,3 +56,5 @@ uint64_t uv__hrtime(uv_clocktype_t type) { clock_gettime(CLOCK_MONOTONIC, &ts); return (((uint64_t) ts.tv_sec) * NANOSEC + ts.tv_nsec); } + +#endif diff --git a/Utilities/cmlibuv/src/unix/stream.c b/Utilities/cmlibuv/src/unix/stream.c index 7b23d16..3857bc8 100644 --- a/Utilities/cmlibuv/src/unix/stream.c +++ b/Utilities/cmlibuv/src/unix/stream.c @@ -98,7 +98,7 @@ void uv__stream_init(uv_loop_t* loop, loop->emfile_fd = err; } -#if defined(__APPLE__) +#if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP) stream->select = NULL; #endif /* defined(__APPLE_) */ @@ -107,7 +107,7 @@ void uv__stream_init(uv_loop_t* loop, static void uv__stream_osx_interrupt_select(uv_stream_t* stream) { -#if defined(__APPLE__) +#if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP) /* Notify select() thread about state change */ uv__stream_select_t* s; int r; @@ -131,7 +131,7 @@ static void uv__stream_osx_interrupt_select(uv_stream_t* stream) { } -#if defined(__APPLE__) +#if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP) static void uv__stream_osx_select(void* arg) { uv_stream_t* stream; uv__stream_select_t* s; @@ -1598,7 +1598,7 @@ int uv_is_writable(const uv_stream_t* stream) { } -#if defined(__APPLE__) +#if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP) int uv___stream_fd(const uv_stream_t* handle) { const uv__stream_select_t* s; @@ -1619,7 +1619,7 @@ void uv__stream_close(uv_stream_t* handle) { unsigned int i; uv__stream_queued_fds_t* queued_fds; -#if defined(__APPLE__) +#if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP) /* Terminate select loop first */ if (handle->select != NULL) { uv__stream_select_t* s; diff --git a/Utilities/cmlibuv/src/uv-common.c b/Utilities/cmlibuv/src/uv-common.c index bc7d137..fcb910f 100644 --- a/Utilities/cmlibuv/src/uv-common.c +++ b/Utilities/cmlibuv/src/uv-common.c @@ -175,6 +175,7 @@ const char* uv_strerror(int err) { } #undef UV_STRERROR_GEN +#if !defined(CMAKE_BOOTSTRAP) || defined(_WIN32) int uv_ip4_addr(const char* ip, int port, struct sockaddr_in* addr) { memset(addr, 0, sizeof(*addr)); @@ -343,6 +344,7 @@ int uv_udp_recv_stop(uv_udp_t* handle) { return uv__udp_recv_stop(handle); } +#endif void uv_walk(uv_loop_t* loop, uv_walk_cb walk_cb, void* arg) { QUEUE queue; @@ -480,6 +480,59 @@ KWSYS_FILES="\ SystemTools.hxx \ Terminal.h" +if ${cmake_system_mingw}; then + LIBUV_C_SOURCES="\ + src/fs-poll.c \ + src/inet.c \ + src/threadpool.c \ + src/uv-common.c \ + src/win/async.c \ + src/win/core.c \ + src/win/detect-wakeup.c \ + src/win/dl.c \ + src/win/error.c \ + src/win/fs-event.c \ + src/win/fs.c \ + src/win/getaddrinfo.c \ + src/win/getnameinfo.c \ + src/win/handle.c \ + src/win/loop-watcher.c \ + src/win/pipe.c \ + src/win/poll.c \ + src/win/process-stdio.c \ + src/win/process.c \ + src/win/req.c \ + src/win/signal.c \ + src/win/stream.c \ + src/win/tcp.c \ + src/win/thread.c \ + src/win/timer.c \ + src/win/tty.c \ + src/win/udp.c \ + src/win/util.c \ + src/win/winapi.c \ + src/win/winsock.c \ + " +else + LIBUV_C_SOURCES="\ + src/uv-common.c \ + src/unix/cmake-bootstrap.c \ + src/unix/core.c \ + src/unix/fs.c \ + src/unix/loop.c \ + src/unix/loop-watcher.c \ + src/unix/no-fsevents.c \ + src/unix/pipe.c \ + src/unix/poll.c \ + src/unix/posix-hrtime.c \ + src/unix/posix-poll.c \ + src/unix/process.c \ + src/unix/signal.c \ + src/unix/stream.c \ + src/unix/timer.c \ + " +fi + # Display CMake bootstrap usage cmake_usage() { @@ -641,6 +694,12 @@ cmake_escape () echo $1 | sed "s/ /\\\\ /g" } +# Encode object file names. +cmake_obj () +{ + echo $1 | sed 's/\//-/g' | sed 's/$/\.o/' +} + # Strip prefix from argument cmake_arg () { @@ -830,6 +889,12 @@ rm -f "${cmake_bootstrap_dir}/cmake_bootstrap.log" rm -f "${cmake_bootstrap_dir}/cmConfigure.h${_tmp}" rm -f "${cmake_bootstrap_dir}/cmVersionConfig.h${_tmp}" +# If building in-source, remove any cmConfigure.h that may +# have been created by a previous run of the bootstrap cmake. +if [ -n "${cmake_in_source_build}" ]; then + rm -f "${cmake_source_dir}/Source/cmConfigure.h" +fi + # If exist compiler flags, set them cmake_c_flags=${CFLAGS} cmake_cxx_flags=${CXXFLAGS} @@ -935,6 +1000,10 @@ echo ' # error "The CMAKE_C_COMPILER is set to a C++ compiler" #endif +#if defined(__sun) && __STDC_VERSION__ < 199901L +#error "On Solaris we need C99." +#endif + #include <stdio.h> int main(int argc, char* argv[]) @@ -1174,6 +1243,8 @@ cmake_compiler_settings_comment="/* * ${LexerParser_CXX_SOURCES} ${LexerParser_C_SOURCES} * kwSys Sources: * ${KWSYS_CXX_SOURCES} ${KWSYS_C_SOURCES} + * libuv Sources: + * ${LIBUV_C_SOURCES} */ " @@ -1201,7 +1272,6 @@ cmake_report cmConfigure.h${_tmp} "#define CMAKE_DATA_DIR \"/bootstrap-not-insal cmake_report cmConfigure.h${_tmp} "#define CMAKE_BOOTSTRAP" cmake_report cmConfigure.h${_tmp} "#define CM_EQ_DELETE" cmake_report cmConfigure.h${_tmp} "#define CM_FALLTHROUGH" -cmake_report cmConfigure.h${_tmp} "#define CM_OVERRIDE" cmake_report cmConfigure.h${_tmp} "#define CM_DISABLE_COPY(Class)" # Regenerate configured headers @@ -1236,6 +1306,48 @@ objs="" for a in ${CMAKE_CXX_SOURCES} ${CMAKE_C_SOURCES} ${LexerParser_CXX_SOURCES} ${LexerParser_C_SOURCES} ${KWSYS_CXX_SOURCES} ${KWSYS_C_SOURCES}; do objs="${objs} ${a}.o" done +for a in ${LIBUV_C_SOURCES}; do + objs="${objs} uv-`cmake_obj ${a}`" +done + +libs="" + +uv_c_flags="" +if ${cmake_system_mingw}; then + uv_c_flags="${uv_c_flags} -DWIN32_LEAN_AND_MEAN -D_WIN32_WINNT=0x0600" + libs="${libs} -lws2_32 -lpsapi -liphlpapi -lshell32 -luserenv" +else + uv_c_flags="${uv_c_flags} -DCMAKE_BOOTSTRAP" + case "${cmake_system}" in + *AIX*) + uv_c_flags="${uv_c_flags} -D_ALL_SOURCE -D_XOPEN_SOURCE=500 -D_LINUX_SOURCE_COMPAT -D_THREAD_SAFE" + libs="${libs} -lperfstat" + ;; + *Darwin*) + uv_c_flags="${uv_c_flags} -D_DARWIN_USE_64_BIT_INODE=1 -D_DARWIN_UNLIMITED_SELECT=1" + ;; + *Linux*) + uv_c_flags="${uv_c_flags} -D_GNU_SOURCE" + libs="${libs} -ldl -lrt" + ;; + *BSD*) + libs="${libs} -lkvm" + ;; + *SunOS*) + # Normally libuv uses '-D_XOPEN_SOURCE=500 -std=c90' on Solaris 5.10, + # but we do not need to do that because we bootstrap using POSIX APIs. + uv_c_flags="${uv_c_flags} -D__EXTENSIONS__ -D_XOPEN_SOURCE=600" + libs="${libs} -lkstat -lnsl -lsendfile -lsocket -lrt" + ;; + esac +fi +uv_c_flags="${uv_c_flags} `cmake_escape "-I${cmake_source_dir}/Utilities/cmlibuv/include"`" +if ${cmake_system_mingw}; then + uv_c_flags="${uv_c_flags} `cmake_escape "-I${cmake_source_dir}/Utilities/cmlibuv/src/win"`" +else + uv_c_flags="${uv_c_flags} `cmake_escape "-I${cmake_source_dir}/Utilities/cmlibuv/src/unix"`" +fi +uv_c_flags="${uv_c_flags} `cmake_escape "-I${cmake_source_dir}/Utilities/cmlibuv/src"`" if [ "x${cmake_ansi_cxx_flags}" != "x" ]; then cmake_cxx_flags="${cmake_ansi_cxx_flags} ${cmake_cxx_flags}" @@ -1273,7 +1385,7 @@ cmake_cxx_flags="${cmake_cxx_flags} \ -I`cmake_escape \"${cmake_source_dir}/Source/LexerParser\"` \ -I`cmake_escape \"${cmake_source_dir}/Utilities\"`" echo "cmake: ${objs}" > "${cmake_bootstrap_dir}/Makefile" -echo " ${cmake_cxx_compiler} ${cmake_ld_flags} ${cmake_cxx_flags} ${objs} -o cmake" >> "${cmake_bootstrap_dir}/Makefile" +echo " ${cmake_cxx_compiler} ${cmake_ld_flags} ${cmake_cxx_flags} ${objs} ${libs} -o cmake" >> "${cmake_bootstrap_dir}/Makefile" for a in ${CMAKE_CXX_SOURCES}; do src=`cmake_escape "${cmake_source_dir}/Source/${a}.cxx"` src_flags=`eval echo \\${cmake_cxx_flags_\${a}}` @@ -1308,6 +1420,11 @@ for a in ${KWSYS_CXX_SOURCES}; do echo "${a}.o : ${src} ${dep}" >> "${cmake_bootstrap_dir}/Makefile" echo " ${cmake_cxx_compiler} ${cmake_cxx_flags} -DKWSYS_NAMESPACE=cmsys ${src_flags} -c ${src} -o ${a}.o" >> "${cmake_bootstrap_dir}/Makefile" done +for a in ${LIBUV_C_SOURCES}; do + src=`cmake_escape "${cmake_source_dir}/Utilities/cmlibuv/${a}"` + echo "uv-`cmake_obj ${a}` : ${src} ${dep}" >> "${cmake_bootstrap_dir}/Makefile" + echo " ${cmake_c_compiler} ${cmake_c_flags} ${uv_c_flags} -c ${src} -o uv-`cmake_obj ${a}`" >> "${cmake_bootstrap_dir}/Makefile" +done echo ' rebuild_cache: cd "${cmake_binary_dir}" && "${cmake_source_dir}/bootstrap" |