cmGhsMultiTargetGenerator.cxx 19.1 KB
Newer Older
1 2
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing for details.  */
3
#include "cmGhsMultiTargetGenerator.h"
4

5
#include "cmComputeLinkInformation.h"
6
#include "cmGeneratedFileStream.h"
7
#include "cmGeneratorTarget.h"
8
#include "cmGlobalGhsMultiGenerator.h"
9
#include "cmLinkLineComputer.h"
10 11 12
#include "cmLocalGhsMultiGenerator.h"
#include "cmMakefile.h"
#include "cmSourceFile.h"
13
#include "cmSourceGroup.h"
14
#include "cmTarget.h"
15

16
cmGhsMultiTargetGenerator::cmGhsMultiTargetGenerator(cmGeneratorTarget* target)
17
  : GeneratorTarget(target)
18 19
  , LocalGenerator(
      static_cast<cmLocalGhsMultiGenerator*>(target->GetLocalGenerator()))
20
  , Makefile(target->Target->GetMakefile())
21
  , Name(target->GetName())
22
{
23 24 25 26 27 28 29 30
  // Store the configuration name that is being used
  if (const char* config = this->Makefile->GetDefinition("CMAKE_BUILD_TYPE")) {
    // Use the build type given by the user.
    this->ConfigName = config;
  } else {
    // No configuration type given.
    this->ConfigName.clear();
  }
31 32 33 34 35 36 37 38
}

cmGhsMultiTargetGenerator::~cmGhsMultiTargetGenerator()
{
}

void cmGhsMultiTargetGenerator::Generate()
{
39 40 41
  // Determine type of target for this project
  switch (this->GeneratorTarget->GetType()) {
    case cmStateEnums::EXECUTABLE: {
42
      // Get the name of the executable to generate.
43 44
      this->TargetNameReal =
        this->GeneratorTarget->GetExecutableNames(this->ConfigName).Real;
45
      if (cmGhsMultiTargetGenerator::DetermineIfIntegrityApp()) {
46 47 48 49 50 51 52
        this->TagType = GhsMultiGpj::INTERGRITY_APPLICATION;
      } else {
        this->TagType = GhsMultiGpj::PROGRAM;
      }
      break;
    }
    case cmStateEnums::STATIC_LIBRARY: {
53 54
      this->TargetNameReal =
        this->GeneratorTarget->GetLibraryNames(this->ConfigName).Real;
55 56 57 58 59 60
      this->TagType = GhsMultiGpj::LIBRARY;
      break;
    }
    case cmStateEnums::SHARED_LIBRARY: {
      std::string msg = "add_library(<name> SHARED ...) not supported: ";
      msg += this->Name;
61
      cmSystemTools::Message(msg);
62 63 64
      return;
    }
    case cmStateEnums::OBJECT_LIBRARY: {
65 66
      this->TargetNameReal =
        this->GeneratorTarget->GetLibraryNames(this->ConfigName).Real;
67 68
      this->TagType = GhsMultiGpj::SUBPROJECT;
      break;
69 70 71 72
    }
    case cmStateEnums::MODULE_LIBRARY: {
      std::string msg = "add_library(<name> MODULE ...) not supported: ";
      msg += this->Name;
73
      cmSystemTools::Message(msg);
74 75 76 77 78
      return;
    }
    case cmStateEnums::UTILITY: {
      std::string msg = "add_custom_target(<name> ...) not supported: ";
      msg += this->Name;
79
      cmSystemTools::Message(msg);
80 81 82 83 84
      return;
    }
    default:
      return;
  }
85

86 87 88
  // Tell the global generator the name of the project file
  this->GeneratorTarget->Target->SetProperty("GENERATOR_FILE_NAME",
                                             this->Name.c_str());
89 90
  this->GeneratorTarget->Target->SetProperty(
    "GENERATOR_FILE_NAME_EXT", GhsMultiGpj::GetGpjTag(this->TagType));
91

92 93 94 95 96
  this->GenerateTarget();
}

void cmGhsMultiTargetGenerator::GenerateTarget()
{
97 98 99 100 101 102 103 104 105 106 107 108 109
  // Open the filestream in copy-if-different mode.
  std::string fname = this->LocalGenerator->GetCurrentBinaryDirectory();
  fname += "/";
  fname += this->Name;
  fname += cmGlobalGhsMultiGenerator::FILE_EXTENSION;
  cmGeneratedFileStream fout(fname.c_str());
  fout.SetCopyIfDifferent(true);

  this->GetGlobalGenerator()->WriteFileHeader(fout);
  GhsMultiGpj::WriteGpjTag(this->TagType, fout);

  const std::string language(
    this->GeneratorTarget->GetLinkerLanguage(this->ConfigName));
110

111 112 113 114 115 116 117 118
  this->WriteTargetSpecifics(fout, this->ConfigName);
  this->SetCompilerFlags(this->ConfigName, language);
  this->WriteCompilerFlags(fout, this->ConfigName, language);
  this->WriteCompilerDefinitions(fout, this->ConfigName, language);
  this->WriteIncludes(fout, this->ConfigName, language);
  this->WriteTargetLinkLine(fout, this->ConfigName);
  this->WriteCustomCommands(fout);
  this->WriteSources(fout);
119
  this->WriteReferences(fout);
120
  fout.Close();
121 122
}

123 124
cmGlobalGhsMultiGenerator* cmGhsMultiTargetGenerator::GetGlobalGenerator()
  const
125
{
126
  return static_cast<cmGlobalGhsMultiGenerator*>(
127 128 129
    this->LocalGenerator->GetGlobalGenerator());
}

130
void cmGhsMultiTargetGenerator::WriteTargetSpecifics(std::ostream& fout,
131
                                                     const std::string& config)
132
{
133 134 135
  std::string outpath;
  std::string rootpath = this->LocalGenerator->GetCurrentBinaryDirectory();

136 137 138
  if (this->TagType != GhsMultiGpj::SUBPROJECT) {
    // set target binary file destination
    outpath = this->GeneratorTarget->GetDirectory(config);
139 140
    outpath =
      this->LocalGenerator->MaybeConvertToRelativePath(rootpath, outpath);
141 142 143
    fout << "    :binDirRelative=\"" << outpath << "\"" << std::endl;
    fout << "    -o \"" << this->TargetNameReal << "\"" << std::endl;
  }
144 145 146 147

  // set target object file destination
  outpath = this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  fout << "    :outputDirRelative=\"" << outpath << "\"" << std::endl;
148 149
}

150
void cmGhsMultiTargetGenerator::SetCompilerFlags(std::string const& config,
151
                                                 const std::string& language)
152 153 154
{
  std::map<std::string, std::string>::iterator i =
    this->FlagsByLanguage.find(language);
155
  if (i == this->FlagsByLanguage.end()) {
156
    std::string flags;
157
    const char* lang = language.c_str();
158

159 160 161
    this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget, lang,
                                           config);

162 163 164 165
    this->LocalGenerator->AddCMP0018Flags(flags, this->GeneratorTarget, lang,
                                          config);
    this->LocalGenerator->AddVisibilityPresetFlags(
      flags, this->GeneratorTarget, lang);
166 167

    // Append old-style preprocessor definition flags.
168
    if (this->Makefile->GetDefineFlags() != " ") {
169
      this->LocalGenerator->AppendFlags(flags,
170 171
                                        this->Makefile->GetDefineFlags());
    }
172 173

    // Add target-specific flags.
174 175
    this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget, lang,
                                            config);
176 177 178

    std::map<std::string, std::string>::value_type entry(language, flags);
    i = this->FlagsByLanguage.insert(entry).first;
179
  }
180 181
}

182 183
std::string cmGhsMultiTargetGenerator::GetDefines(const std::string& language,
                                                  std::string const& config)
184 185 186
{
  std::map<std::string, std::string>::iterator i =
    this->DefinesByLanguage.find(language);
187
  if (i == this->DefinesByLanguage.end()) {
188
    std::set<std::string> defines;
189
    const char* lang = language.c_str();
190
    // Add preprocessor definitions for this target and configuration.
191 192
    this->LocalGenerator->GetTargetDefines(this->GeneratorTarget, config,
                                           language, defines);
193 194 195 196 197

    std::string definesString;
    this->LocalGenerator->JoinDefines(defines, definesString, lang);

    std::map<std::string, std::string>::value_type entry(language,
198
                                                         definesString);
199
    i = this->DefinesByLanguage.insert(entry).first;
200
  }
201 202 203
  return i->second;
}

204 205
void cmGhsMultiTargetGenerator::WriteCompilerFlags(std::ostream& fout,
                                                   std::string const&,
206
                                                   const std::string& language)
207 208
{
  std::map<std::string, std::string>::iterator flagsByLangI =
209 210 211
    this->FlagsByLanguage.find(language);
  if (flagsByLangI != this->FlagsByLanguage.end()) {
    if (!flagsByLangI->second.empty()) {
212 213 214 215 216
      std::vector<std::string> ghsCompFlags =
        cmSystemTools::ParseArguments(flagsByLangI->second.c_str());
      for (auto& f : ghsCompFlags) {
        fout << "    " << f << std::endl;
      }
217
    }
218
  }
219 220 221
}

void cmGhsMultiTargetGenerator::WriteCompilerDefinitions(
222
  std::ostream& fout, const std::string& config, const std::string& language)
223 224
{
  std::vector<std::string> compileDefinitions;
225 226
  this->GeneratorTarget->GetCompileDefinitions(compileDefinitions, config,
                                               language);
227 228
  for (std::string const& compileDefinition : compileDefinitions) {
    fout << "    -D" << compileDefinition << std::endl;
229
  }
230 231
}

232 233
void cmGhsMultiTargetGenerator::WriteIncludes(std::ostream& fout,
                                              const std::string& config,
234
                                              const std::string& language)
235
{
236 237 238 239
  std::vector<std::string> includes;
  this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
                                              language, config);

240 241
  for (std::string const& include : includes) {
    fout << "    -I\"" << include << "\"" << std::endl;
242
  }
243 244
}

245 246
void cmGhsMultiTargetGenerator::WriteTargetLinkLine(std::ostream& fout,
                                                    std::string const& config)
247
{
248 249
  if (this->TagType == GhsMultiGpj::INTERGRITY_APPLICATION) {
    return;
250
  }
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271

  std::string linkLibraries;
  std::string flags;
  std::string linkFlags;
  std::string frameworkPath;
  std::string linkPath;

  std::unique_ptr<cmLinkLineComputer> linkLineComputer(
    this->GetGlobalGenerator()->CreateLinkLineComputer(
      this->LocalGenerator,
      this->LocalGenerator->GetStateSnapshot().GetDirectory()));

  this->LocalGenerator->GetTargetFlags(
    linkLineComputer.get(), config, linkLibraries, flags, linkFlags,
    frameworkPath, linkPath, this->GeneratorTarget);

  // write out link options
  std::vector<std::string> lopts =
    cmSystemTools::ParseArguments(linkFlags.c_str());
  for (auto& l : lopts) {
    fout << "    " << l << std::endl;
272
  }
273

274 275 276 277 278 279 280
  // write out link search paths
  // must be quoted for paths that contain spaces
  std::vector<std::string> lpath =
    cmSystemTools::ParseArguments(linkPath.c_str());
  for (auto& l : lpath) {
    fout << "    -L\"" << l << "\"" << std::endl;
  }
281

282 283 284 285 286 287 288 289 290 291 292 293
  // write out link libs
  // must be quoted for filepaths that contains spaces
  std::string cbd = this->LocalGenerator->GetCurrentBinaryDirectory();

  std::vector<std::string> llibs =
    cmSystemTools::ParseArguments(linkLibraries.c_str());
  for (auto& l : llibs) {
    if (l.compare(0, 2, "-l") == 0) {
      fout << "    \"" << l << "\"" << std::endl;
    } else {
      std::string rl = cmSystemTools::CollapseCombinedPath(cbd, l);
      fout << "    -l\"" << rl << "\"" << std::endl;
294
    }
295
  }
296 297
}

298
void cmGhsMultiTargetGenerator::WriteCustomCommands(std::ostream& fout)
299
{
300
  WriteCustomCommandsHelper(fout, this->GeneratorTarget->GetPreBuildCommands(),
301
                            cmTarget::PRE_BUILD);
302 303
  WriteCustomCommandsHelper(
    fout, this->GeneratorTarget->GetPostBuildCommands(), cmTarget::POST_BUILD);
304 305 306
}

void cmGhsMultiTargetGenerator::WriteCustomCommandsHelper(
307
  std::ostream& fout, std::vector<cmCustomCommand> const& commandsSet,
308 309
  cmTarget::CustomCommandType const commandType)
{
310 311 312
  for (cmCustomCommand const& customCommand : commandsSet) {
    cmCustomCommandLines const& commandLines = customCommand.GetCommandLines();
    for (cmCustomCommandLine const& command : commandLines) {
313
      switch (commandType) {
314
        case cmTarget::PRE_BUILD:
315
          fout << "    :preexecShellSafe=";
316 317
          break;
        case cmTarget::POST_BUILD:
318
          fout << "    :postexecShellSafe=";
319 320 321
          break;
        default:
          assert("Only pre and post are supported");
322
      }
323 324 325

      bool firstIteration = true;
      for (std::string const& commandLine : command) {
326
        std::string subCommandE =
327 328 329 330
          this->LocalGenerator->EscapeForShell(commandLine, true);
        fout << (firstIteration ? "'" : " ");
        // Need to double escape backslashes
        cmSystemTools::ReplaceString(subCommandE, "\\", "\\\\");
331
        fout << subCommandE;
332
        firstIteration = false;
333 334
      }
      if (!command.empty()) {
335
        fout << "'" << std::endl;
336 337
      }
    }
338
  }
339 340
}

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
void cmGhsMultiTargetGenerator::WriteSourceProperty(std::ostream& fout,
                                                    const cmSourceFile* sf,
                                                    std::string propName,
                                                    std::string propFlag)
{
  const char* prop = sf->GetProperty(propName);
  if (prop) {
    std::vector<std::string> list;
    cmSystemTools::ExpandListArgument(prop, list);
    for (auto& p : list) {
      fout << "    " << propFlag << p << std::endl;
    }
  }
}

356
void cmGhsMultiTargetGenerator::WriteSources(std::ostream& fout_proj)
357
{
358
  /* vector of all sources for this target */
359 360
  std::vector<cmSourceFile*> sources;
  this->GeneratorTarget->GetSourceFiles(sources, this->ConfigName);
361 362 363 364 365 366 367 368 369 370

  /* vector of all groups defined for this target
   * -- but the vector is not expanded with sub groups or in any useful order
   */
  std::vector<cmSourceGroup> sourceGroups = this->Makefile->GetSourceGroups();

  /* for each source file assign it to its group */
  std::map<std::string, std::vector<cmSourceFile*>> groupFiles;
  std::set<std::string> groupNames;
  for (auto& sf : sources) {
371
    cmSourceGroup* sourceGroup =
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
      this->Makefile->FindSourceGroup(sf->GetFullPath(), sourceGroups);
    std::string gn = sourceGroup->GetFullName();
    groupFiles[gn].push_back(sf);
    groupNames.insert(gn);
  }

  /* list of known groups and the order they are displayed in a project file */
  const std::vector<std::string> standardGroups = {
    "Header Files", "Source Files",     "CMake Rules",
    "Object Files", "Object Libraries", "Resources"
  };

  /* list of groups in the order they are displayed in a project file*/
  std::vector<std::string> groupFilesList(groupFiles.size());

  /* put the groups in the order they should be listed
   * - standard groups first, and then everything else
   *   in the order used by std::map.
   */
  int i = 0;
  for (const std::string& gn : standardGroups) {
    auto n = groupNames.find(gn);
    if (n != groupNames.end()) {
      groupFilesList[i] = *n;
      i += 1;
      groupNames.erase(gn);
    }
  }

  { /* catch-all group - is last item */
    std::string gn = "";
    auto n = groupNames.find(gn);
    if (n != groupNames.end()) {
      groupFilesList.back() = *n;
      groupNames.erase(gn);
    }
  }

  for (auto& n : groupNames) {
    groupFilesList[i] = n;
    i += 1;
  }

  /* sort the files within each group */
  for (auto& n : groupFilesList) {
    std::sort(groupFiles[n].begin(), groupFiles[n].end(),
              [](cmSourceFile* l, cmSourceFile* r) {
                return l->GetFullPath() < r->GetFullPath();
              });
  }

  /* list of open project files */
  std::vector<cmGeneratedFileStream*> gfiles;

  /* write files into the proper project file
   * -- groups go into main project file
   *    unless FOLDER property or variable is set.
   */
  for (auto& sg : groupFilesList) {
    std::ostream* fout;
    bool useProjectFile =
      cmSystemTools::IsOn(
        this->GeneratorTarget->GetProperty("GHS_NO_SOURCE_GROUP_FILE")) ||
      cmSystemTools::IsOn(
436
        this->Makefile->GetDefinition("CMAKE_GHS_NO_SOURCE_GROUP_FILE"));
437 438
    if (useProjectFile || sg.empty()) {
      fout = &fout_proj;
439
    } else {
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
      // Open the filestream in copy-if-different mode.
      std::string gname = sg;
      cmsys::SystemTools::ReplaceString(gname, "\\", "_");
      std::string lpath =
        this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
      lpath += "/";
      lpath += gname;
      lpath += cmGlobalGhsMultiGenerator::FILE_EXTENSION;
      std::string fpath = this->LocalGenerator->GetCurrentBinaryDirectory();
      fpath += "/";
      fpath += lpath;
      cmGeneratedFileStream* f = new cmGeneratedFileStream(fpath.c_str());
      f->SetCopyIfDifferent(true);
      gfiles.push_back(f);
      fout = f;
455 456
      this->GetGlobalGenerator()->WriteFileHeader(*f);
      GhsMultiGpj::WriteGpjTag(GhsMultiGpj::SUBPROJECT, *f);
457
      fout_proj << lpath << " ";
458
      GhsMultiGpj::WriteGpjTag(GhsMultiGpj::SUBPROJECT, fout_proj);
459 460 461 462 463 464 465 466
    }

    if (useProjectFile) {
      if (sg.empty()) {
        *fout << "{comment} Others" << std::endl;
      } else {
        *fout << "{comment} " << sg << std::endl;
      }
467
    }
468

469 470 471
    /* output rule for each source file */
    for (const cmSourceFile* si : groupFiles[sg]) {

472 473 474 475 476 477
      // Convert filename to native system
      // WORKAROUND: GHS MULTI 6.1.4 and 6.1.6 are known to need backslash on
      // windows when opening some files from the search window.
      std::string fname(si->GetFullPath());
      cmSystemTools::ConvertToOutputSlashes(fname);
      *fout << fname << std::endl;
478

479 480
      if ("ld" != si->GetExtension() && "int" != si->GetExtension() &&
          "bsp" != si->GetExtension()) {
481
        this->WriteObjectLangOverride(*fout, si);
482
      }
483 484 485 486 487

      this->WriteSourceProperty(*fout, si, "INCLUDE_DIRECTORIES", "-I");
      this->WriteSourceProperty(*fout, si, "COMPILE_DEFINITIONS", "-D");
      this->WriteSourceProperty(*fout, si, "COMPILE_OPTIONS", "");

488 489 490 491 492 493
      /* to avoid clutter in the gui only print out the objectName if it has
       * been renamed */
      std::string objectName = this->GeneratorTarget->GetObjectName(si);
      if (!objectName.empty() &&
          this->GeneratorTarget->HasExplicitObjectName(si)) {
        *fout << "    -o " << objectName << std::endl;
494
      }
495
    }
496
  }
497 498 499 500

  for (cmGeneratedFileStream* f : gfiles) {
    f->Close();
  }
501 502 503
}

void cmGhsMultiTargetGenerator::WriteObjectLangOverride(
504
  std::ostream& fout, const cmSourceFile* sourceFile)
505
{
506 507
  const char* rawLangProp = sourceFile->GetProperty("LANGUAGE");
  if (NULL != rawLangProp) {
508 509
    std::string sourceLangProp(rawLangProp);
    std::string extension(sourceFile->GetExtension());
510
    if ("CXX" == sourceLangProp && ("c" == extension || "C" == extension)) {
511
      fout << "    -dotciscxx" << std::endl;
512
    }
513
  }
514
}
Fred Baksik's avatar
Fred Baksik committed
515

516
void cmGhsMultiTargetGenerator::WriteReferences(std::ostream& fout)
517
{
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
  // This only applies to INTEGRITY Applications
  if (this->TagType != GhsMultiGpj::INTERGRITY_APPLICATION) {
    return;
  }

  // Get the targets that this one depends upon
  cmTargetDependSet unordered =
    this->GetGlobalGenerator()->GetTargetDirectDepends(this->GeneratorTarget);
  cmGlobalGhsMultiGenerator::OrderedTargetDependSet ordered(unordered,
                                                            this->Name);
  for (auto& t : ordered) {
    std::string tname = t->GetName();
    std::string tpath = t->LocalGenerator->GetCurrentBinaryDirectory();
    std::string rootpath = this->LocalGenerator->GetCurrentBinaryDirectory();
    std::string outpath =
533
      this->LocalGenerator->MaybeConvertToRelativePath(rootpath, tpath) + "/" +
534 535 536 537 538 539 540 541
      tname + "REF" + cmGlobalGhsMultiGenerator::FILE_EXTENSION;

    fout << outpath;
    fout << "    ";
    GhsMultiGpj::WriteGpjTag(GhsMultiGpj::REFERENCE, fout);

    // Tell the global generator that a refernce project needs to be created
    t->Target->SetProperty("GHS_REFERENCE_PROJECT", "ON");
542
  }
543 544
}

545
bool cmGhsMultiTargetGenerator::DetermineIfIntegrityApp(void)
546
{
547 548 549 550 551 552 553 554 555 556 557
  const char* p = this->GeneratorTarget->GetProperty("ghs_integrity_app");
  if (p) {
    return cmSystemTools::IsOn(
      this->GeneratorTarget->GetProperty("ghs_integrity_app"));
  } else {
    std::vector<cmSourceFile*> sources;
    this->GeneratorTarget->GetSourceFiles(sources, this->ConfigName);
    for (auto& sf : sources) {
      if ("int" == sf->GetExtension()) {
        return true;
      }
558
    }
559
    return false;
560
  }
561
}