1 /*============================================================================
2 CMake - Cross Platform Makefile Generator
3 Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
5 Distributed under the OSI-approved BSD License (the "License");
6 see accompanying file Copyright.txt for details.
8 This software is distributed WITHOUT ANY WARRANTY; without even the
9 implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the License for more information.
11 ============================================================================*/
12 #include "cmDependsC.h"
14 #include "cmFileTimeComparison.h"
15 #include "cmLocalGenerator.h"
16 #include "cmMakefile.h"
17 #include "cmSystemTools.h"
19 #include <ctype.h> // isspace
22 #define INCLUDE_REGEX_LINE \
23 "^[ \t]*#[ \t]*(include|import)[ \t]*[<\"]([^\">]+)([\">])"
25 #define INCLUDE_REGEX_LINE_MARKER "#IncludeRegexLine: "
26 #define INCLUDE_REGEX_SCAN_MARKER "#IncludeRegexScan: "
27 #define INCLUDE_REGEX_COMPLAIN_MARKER "#IncludeRegexComplain: "
28 #define INCLUDE_REGEX_TRANSFORM_MARKER "#IncludeRegexTransform: "
30 //----------------------------------------------------------------------------
31 cmDependsC::cmDependsC()
36 //----------------------------------------------------------------------------
37 cmDependsC::cmDependsC(cmLocalGenerator* lg,
38 const char* targetDir,
40 const std::map<std::string, DependencyVector>* validDeps)
41 : cmDepends(lg, targetDir)
42 , ValidDeps(validDeps)
44 cmMakefile* mf = lg->GetMakefile();
46 // Configure the include file search path.
47 this->SetIncludePathFromLanguage(lang);
49 // Configure regular expressions.
50 std::string scanRegex = "^.*$";
51 std::string complainRegex = "^$";
53 std::string scanRegexVar = "CMAKE_";
55 scanRegexVar += "_INCLUDE_REGEX_SCAN";
56 if(const char* sr = mf->GetDefinition(scanRegexVar.c_str()))
60 std::string complainRegexVar = "CMAKE_";
61 complainRegexVar += lang;
62 complainRegexVar += "_INCLUDE_REGEX_COMPLAIN";
63 if(const char* cr = mf->GetDefinition(complainRegexVar.c_str()))
69 this->IncludeRegexLine.compile(INCLUDE_REGEX_LINE);
70 this->IncludeRegexScan.compile(scanRegex.c_str());
71 this->IncludeRegexComplain.compile(complainRegex.c_str());
72 this->IncludeRegexLineString = INCLUDE_REGEX_LINE_MARKER INCLUDE_REGEX_LINE;
73 this->IncludeRegexScanString = INCLUDE_REGEX_SCAN_MARKER;
74 this->IncludeRegexScanString += scanRegex;
75 this->IncludeRegexComplainString = INCLUDE_REGEX_COMPLAIN_MARKER;
76 this->IncludeRegexComplainString += complainRegex;
78 this->SetupTransforms();
80 this->CacheFileName = this->TargetDirectory;
81 this->CacheFileName += "/";
82 this->CacheFileName += lang;
83 this->CacheFileName += ".includecache";
85 this->ReadCacheFile();
88 //----------------------------------------------------------------------------
89 cmDependsC::~cmDependsC()
91 this->WriteCacheFile();
93 for (std::map<cmStdString, cmIncludeLines*>::iterator it=
94 this->FileCache.begin(); it!=this->FileCache.end(); ++it)
100 //----------------------------------------------------------------------------
101 bool cmDependsC::WriteDependencies(const char *src, const char *obj,
102 std::ostream& makeDepends, std::ostream& internalDepends)
104 // Make sure this is a scanning instance.
105 if(!src || src[0] == '\0')
107 cmSystemTools::Error("Cannot scan dependencies without a source file.");
110 if(!obj || obj[0] == '\0')
112 cmSystemTools::Error("Cannot scan dependencies without an object file.");
116 if (this->ValidDeps != 0)
118 std::map<std::string, DependencyVector>::const_iterator tmpIt =
119 this->ValidDeps->find(obj);
120 if (tmpIt!= this->ValidDeps->end())
122 // Write the dependencies to the output stream. Makefile rules
123 // written by the original local generator for this directory
124 // convert the dependencies to paths relative to the home output
125 // directory. We must do the same here.
126 internalDepends << obj << std::endl;
127 for(DependencyVector::const_iterator i=tmpIt->second.begin();
128 i != tmpIt->second.end(); ++i)
130 makeDepends << obj << ": " <<
131 this->LocalGenerator->Convert(i->c_str(),
132 cmLocalGenerator::HOME_OUTPUT,
133 cmLocalGenerator::MAKEFILE)
135 internalDepends << " " << i->c_str() << std::endl;
137 makeDepends << std::endl;
142 // Walk the dependency graph starting with the source file.
146 this->Unscanned.push(root);
147 this->Encountered.clear();
148 this->Encountered.insert(src);
149 std::set<cmStdString> dependencies;
150 std::set<cmStdString> scanned;
152 // Use reserve to allocate enough memory for tempPathStr
153 // so that during the loops no memory is allocated or freed
154 std::string tempPathStr;
155 tempPathStr.reserve(4*1024);
157 while(!this->Unscanned.empty())
159 // Get the next file to scan.
160 UnscannedEntry current = this->Unscanned.front();
161 this->Unscanned.pop();
163 // If not a full path, find the file in the include path.
164 std::string fullName;
165 if(first || cmSystemTools::FileIsFullPath(current.FileName.c_str()))
167 if(cmSystemTools::FileExists(current.FileName.c_str(), true))
169 fullName = current.FileName;
172 else if(!current.QuotedLocation.empty() &&
173 cmSystemTools::FileExists(current.QuotedLocation.c_str(), true))
175 // The include statement producing this entry was a double-quote
176 // include and the included file is present in the directory of
177 // the source containing the include statement.
178 fullName = current.QuotedLocation;
182 std::map<cmStdString, cmStdString>::iterator
183 headerLocationIt=this->HeaderLocationCache.find(current.FileName);
184 if (headerLocationIt!=this->HeaderLocationCache.end())
186 fullName=headerLocationIt->second;
188 else for(std::vector<std::string>::const_iterator i =
189 this->IncludePath.begin(); i != this->IncludePath.end(); ++i)
191 // Construct the name of the file as if it were in the current
192 // include directory. Avoid using a leading "./".
197 tempPathStr += current.FileName;
203 tempPathStr+=current.FileName;
206 // Look for the file in this location.
207 if(cmSystemTools::FileExists(tempPathStr.c_str(), true))
209 fullName = tempPathStr;
210 HeaderLocationCache[current.FileName]=fullName;
216 // Complain if the file cannot be found and matches the complain
218 if(fullName.empty() &&
219 this->IncludeRegexComplain.find(current.FileName.c_str()))
221 cmSystemTools::Error("Cannot find file \"",
222 current.FileName.c_str(), "\".");
226 // Scan the file if it was found and has not been scanned already.
227 if(!fullName.empty() && (scanned.find(fullName) == scanned.end()))
229 // Record scanned files.
230 scanned.insert(fullName);
232 // Check whether this file is already in the cache
233 std::map<cmStdString, cmIncludeLines*>::iterator fileIt=
234 this->FileCache.find(fullName);
235 if (fileIt!=this->FileCache.end())
237 fileIt->second->Used=true;
238 dependencies.insert(fullName);
239 for (std::vector<UnscannedEntry>::const_iterator incIt=
240 fileIt->second->UnscannedEntries.begin();
241 incIt!=fileIt->second->UnscannedEntries.end(); ++incIt)
243 if (this->Encountered.find(incIt->FileName) ==
244 this->Encountered.end())
246 this->Encountered.insert(incIt->FileName);
247 this->Unscanned.push(*incIt);
254 // Try to scan the file. Just leave it out if we cannot find
256 std::ifstream fin(fullName.c_str());
259 // Add this file as a dependency.
260 dependencies.insert(fullName);
262 // Scan this file for new dependencies. Pass the directory
263 // containing the file to handle double-quote includes.
264 std::string dir = cmSystemTools::GetFilenamePath(fullName);
265 this->Scan(fin, dir.c_str(), fullName);
273 // Write the dependencies to the output stream. Makefile rules
274 // written by the original local generator for this directory
275 // convert the dependencies to paths relative to the home output
276 // directory. We must do the same here.
277 internalDepends << obj << std::endl;
278 for(std::set<cmStdString>::iterator i=dependencies.begin();
279 i != dependencies.end(); ++i)
281 makeDepends << obj << ": " <<
282 this->LocalGenerator->Convert(i->c_str(),
283 cmLocalGenerator::HOME_OUTPUT,
284 cmLocalGenerator::MAKEFILE)
286 internalDepends << " " << i->c_str() << std::endl;
288 makeDepends << std::endl;
293 //----------------------------------------------------------------------------
294 void cmDependsC::ReadCacheFile()
296 if(this->CacheFileName.size() == 0)
300 std::ifstream fin(this->CacheFileName.c_str());
307 cmIncludeLines* cacheEntry=0;
308 bool haveFileName=false;
310 while(cmSystemTools::GetLineFromStream(fin, line))
318 //the first line after an empty line is the name of the parsed file
319 if (haveFileName==false)
323 cmFileTimeComparison comp;
324 bool res=comp.FileTimeCompare(this->CacheFileName.c_str(),
325 line.c_str(), &newer);
327 if ((res==true) && (newer==1)) //cache is newer than the parsed file
329 cacheEntry=new cmIncludeLines;
330 this->FileCache[line]=cacheEntry;
332 // file doesn't exist, check that the regular expressions
336 if (line.find(INCLUDE_REGEX_LINE_MARKER) == 0)
338 if (line != this->IncludeRegexLineString)
343 else if (line.find(INCLUDE_REGEX_SCAN_MARKER) == 0)
345 if (line != this->IncludeRegexScanString)
350 else if (line.find(INCLUDE_REGEX_COMPLAIN_MARKER) == 0)
352 if (line != this->IncludeRegexComplainString)
357 else if (line.find(INCLUDE_REGEX_TRANSFORM_MARKER) == 0)
359 if (line != this->IncludeRegexTransformString)
366 else if (cacheEntry!=0)
368 UnscannedEntry entry;
369 entry.FileName = line;
370 if (cmSystemTools::GetLineFromStream(fin, line))
374 entry.QuotedLocation=line;
376 cacheEntry->UnscannedEntries.push_back(entry);
382 //----------------------------------------------------------------------------
383 void cmDependsC::WriteCacheFile() const
385 if(this->CacheFileName.size() == 0)
389 std::ofstream cacheOut(this->CacheFileName.c_str());
395 cacheOut << this->IncludeRegexLineString << "\n\n";
396 cacheOut << this->IncludeRegexScanString << "\n\n";
397 cacheOut << this->IncludeRegexComplainString << "\n\n";
398 cacheOut << this->IncludeRegexTransformString << "\n\n";
400 for (std::map<cmStdString, cmIncludeLines*>::const_iterator fileIt=
401 this->FileCache.begin();
402 fileIt!=this->FileCache.end(); ++fileIt)
404 if (fileIt->second->Used)
406 cacheOut<<fileIt->first.c_str()<<std::endl;
408 for (std::vector<UnscannedEntry>::const_iterator
409 incIt=fileIt->second->UnscannedEntries.begin();
410 incIt!=fileIt->second->UnscannedEntries.end(); ++incIt)
412 cacheOut<<incIt->FileName.c_str()<<std::endl;
413 if (incIt->QuotedLocation.empty())
415 cacheOut<<"-"<<std::endl;
419 cacheOut<<incIt->QuotedLocation.c_str()<<std::endl;
427 //----------------------------------------------------------------------------
428 void cmDependsC::Scan(std::istream& is, const char* directory,
429 const cmStdString& fullName)
431 cmIncludeLines* newCacheEntry=new cmIncludeLines;
432 newCacheEntry->Used=true;
433 this->FileCache[fullName]=newCacheEntry;
435 // Read one line at a time.
437 while(cmSystemTools::GetLineFromStream(is, line))
439 // Transform the line content first.
440 if(!this->TransformRules.empty())
442 this->TransformLine(line);
445 // Match include directives.
446 if(this->IncludeRegexLine.find(line.c_str()))
448 // Get the file being included.
449 UnscannedEntry entry;
450 entry.FileName = this->IncludeRegexLine.match(2);
451 cmSystemTools::ConvertToUnixSlashes(entry.FileName);
452 if(this->IncludeRegexLine.match(3) == "\"" &&
453 !cmSystemTools::FileIsFullPath(entry.FileName.c_str()))
455 // This was a double-quoted include with a relative path. We
456 // must check for the file in the directory containing the
457 // file we are scanning.
458 entry.QuotedLocation = directory;
459 entry.QuotedLocation += "/";
460 entry.QuotedLocation += entry.FileName;
463 // Queue the file if it has not yet been encountered and it
464 // matches the regular expression for recursive scanning. Note
465 // that this check does not account for the possibility of two
466 // headers with the same name in different directories when one
467 // is included by double-quotes and the other by angle brackets.
468 // It also does not work properly if two header files with the same
469 // name exist in different directories, and both are included from a
470 // file their own directory by simply using "filename.h" (#12619)
471 // This kind of problem will be fixed when a more
472 // preprocessor-like implementation of this scanner is created.
473 if (this->IncludeRegexScan.find(entry.FileName.c_str()))
475 newCacheEntry->UnscannedEntries.push_back(entry);
476 if(this->Encountered.find(entry.FileName) == this->Encountered.end())
478 this->Encountered.insert(entry.FileName);
479 this->Unscanned.push(entry);
486 //----------------------------------------------------------------------------
487 void cmDependsC::SetupTransforms()
489 // Get the transformation rules.
490 std::vector<std::string> transformRules;
491 cmMakefile* mf = this->LocalGenerator->GetMakefile();
492 if(const char* xform =
493 mf->GetDefinition("CMAKE_INCLUDE_TRANSFORMS"))
495 cmSystemTools::ExpandListArgument(xform, transformRules, true);
497 for(std::vector<std::string>::const_iterator tri = transformRules.begin();
498 tri != transformRules.end(); ++tri)
500 this->ParseTransform(*tri);
503 this->IncludeRegexTransformString = INCLUDE_REGEX_TRANSFORM_MARKER;
504 if(!this->TransformRules.empty())
506 // Construct the regular expression to match lines to be
508 std::string xform = "^([ \t]*#[ \t]*(include|import)[ \t]*)(";
509 const char* sep = "";
510 for(TransformRulesType::const_iterator tri = this->TransformRules.begin();
511 tri != this->TransformRules.end(); ++tri)
517 xform += ")[ \t]*\\(([^),]*)\\)";
518 this->IncludeRegexTransform.compile(xform.c_str());
520 // Build a string that encodes all transformation rules and will
521 // change when rules are changed.
522 this->IncludeRegexTransformString += xform;
523 for(TransformRulesType::const_iterator tri = this->TransformRules.begin();
524 tri != this->TransformRules.end(); ++tri)
526 this->IncludeRegexTransformString += " ";
527 this->IncludeRegexTransformString += tri->first;
528 this->IncludeRegexTransformString += "(%)=";
529 this->IncludeRegexTransformString += tri->second;
534 //----------------------------------------------------------------------------
535 void cmDependsC::ParseTransform(std::string const& xform)
537 // A transform rule is of the form SOME_MACRO(%)=value-with-%
538 // We can simply separate with "(%)=".
539 std::string::size_type pos = xform.find("(%)=");
540 if(pos == xform.npos || pos == 0)
544 std::string name = xform.substr(0, pos);
545 std::string value = xform.substr(pos+4, xform.npos);
546 this->TransformRules[name] = value;
549 //----------------------------------------------------------------------------
550 void cmDependsC::TransformLine(std::string& line)
552 // Check for a transform rule match. Return if none.
553 if(!this->IncludeRegexTransform.find(line.c_str()))
557 TransformRulesType::const_iterator tri =
558 this->TransformRules.find(this->IncludeRegexTransform.match(3));
559 if(tri == this->TransformRules.end())
564 // Construct the transformed line.
565 std::string newline = this->IncludeRegexTransform.match(1);
566 std::string arg = this->IncludeRegexTransform.match(4);
567 for(const char* c = tri->second.c_str(); *c; ++c)
579 // Return the transformed line.