cmMacroCommand.cxx 10.1 KB
Newer Older
1
2
3
/*============================================================================
  CMake - Cross Platform Makefile Generator
  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Ken Martin's avatar
Ken Martin committed
4

5
6
  Distributed under the OSI-approved BSD License (the "License");
  see accompanying file Copyright.txt for details.
Ken Martin's avatar
Ken Martin committed
7

8
9
10
11
  This software is distributed WITHOUT ANY WARRANTY; without even the
  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  See the License for more information.
============================================================================*/
Ken Martin's avatar
Ken Martin committed
12
13
#include "cmMacroCommand.h"

14
15
#include "cmake.h"

16
17
// define the class for macro commands
class cmMacroHelperCommand : public cmCommand
Ken Martin's avatar
Ken Martin committed
18
{
19
20
public:
  cmMacroHelperCommand() {}
Andy Cedilnik's avatar
Andy Cedilnik committed
21

22
23
  ///! clean up any memory allocated by the macro
  ~cmMacroHelperCommand() {};
Andy Cedilnik's avatar
Andy Cedilnik committed
24

25
26
27
28
29
30
  /**
   * This is used to avoid including this command
   * in documentation. This is mainly used by
   * cmMacroHelperCommand and cmFunctionHelperCommand
   * which cannot provide appropriate documentation.
   */
31
  virtual bool ShouldAppearInDocumentation() const
32
33
34
35
    {
    return false;
    }

36
37
38
  /**
   * This is a virtual constructor for the command.
   */
Andy Cedilnik's avatar
Andy Cedilnik committed
39
  virtual cmCommand* Clone()
40
41
42
  {
    cmMacroHelperCommand *newC = new cmMacroHelperCommand;
    // we must copy when we clone
Ken Martin's avatar
Ken Martin committed
43
44
    newC->Args = this->Args;
    newC->Functions = this->Functions;
45
    newC->FilePath = this->FilePath;
46
    newC->Policies = this->Policies;
47
48
    return newC;
  }
Andy Cedilnik's avatar
Andy Cedilnik committed
49

50
51
52
  /**
   * This determines if the command is invoked when in script mode.
   */
53
  virtual bool IsScriptable() const { return true; }
54

55
56
57
58
  /**
   * This is called when the command is first encountered in
   * the CMakeLists.txt file.
   */
59
  virtual bool InvokeInitialPass(const std::vector<cmListFileArgument>& args,
60
                                 cmExecutionStatus &);
61

62
63
  virtual bool InitialPass(std::vector<std::string> const&,
                           cmExecutionStatus &) { return false; };
Andy Cedilnik's avatar
Andy Cedilnik committed
64

65
66
67
  /**
   * The name of the command as specified in CMakeList.txt.
   */
68
  virtual const char* GetName() const { return this->Args[0].c_str(); }
69

70
71
  cmTypeMacro(cmMacroHelperCommand, cmCommand);

Ken Martin's avatar
Ken Martin committed
72
73
  std::vector<std::string> Args;
  std::vector<cmListFileFunction> Functions;
74
  cmPolicies::PolicyMap Policies;
75
  std::string FilePath;
76
77
78
79
};


bool cmMacroHelperCommand::InvokeInitialPass
80
81
(const std::vector<cmListFileArgument>& args,
 cmExecutionStatus &inStatus)
82
83
84
{
  // Expand the argument list to the macro.
  std::vector<std::string> expandedArgs;
Ken Martin's avatar
Ken Martin committed
85
  this->Makefile->ExpandArguments(args, expandedArgs);
Andy Cedilnik's avatar
Andy Cedilnik committed
86

87
88
89
90
91
92
  std::string tmps;
  cmListFileArgument arg;
  std::string variable;

  // make sure the number of arguments passed is at least the number
  // required by the signature
Ken Martin's avatar
Ken Martin committed
93
  if (expandedArgs.size() < this->Args.size() - 1)
Ken Martin's avatar
Ken Martin committed
94
    {
Andy Cedilnik's avatar
Andy Cedilnik committed
95
    std::string errorMsg =
96
      "Macro invoked with incorrect arguments for macro named: ";
Ken Martin's avatar
Ken Martin committed
97
    errorMsg += this->Args[0];
98
99
    this->SetError(errorMsg.c_str());
    return false;
Ken Martin's avatar
Ken Martin committed
100
    }
Andy Cedilnik's avatar
Andy Cedilnik committed
101

102
103
104
  // Enforce matching logical blocks inside the macro.
  cmMakefile::LexicalPushPop lexScope(this->Makefile);

105
106
107
108
  // Push a weak policy scope which restores the policies recorded at
  // macro creation.
  cmMakefile::PolicyPushPop polScope(this->Makefile, true, this->Policies);

109
110
111
112
  // set the value of argc
  cmOStringStream argcDefStream;
  argcDefStream << expandedArgs.size();
  std::string argcDef = argcDefStream.str();
Andy Cedilnik's avatar
Andy Cedilnik committed
113

114
115
116
  // declare varuiables for ARGV ARGN but do not compute until needed
  std::string argvDef;
  std::string argnDef;
117
118
  bool argnDefInitialized = false;
  bool argvDefInitialized = false;
119
120
121
122
  if( this->Functions.size())
    {
    this->FilePath = this->Functions[0].FilePath;
    }
123
124
125
  // Invoke all the functions that were collected in the block.
  cmListFileFunction newLFF;
  // for each function
Ken Martin's avatar
Ken Martin committed
126
  for(unsigned int c = 0; c < this->Functions.size(); ++c)
127
    {
128
    // Replace the formal arguments and then invoke the command.
Ken Martin's avatar
Ken Martin committed
129
130
131
132
133
    newLFF.Arguments.clear();
    newLFF.Arguments.reserve(this->Functions[c].Arguments.size());
    newLFF.Name = this->Functions[c].Name;
    newLFF.FilePath = this->Functions[c].FilePath;
    newLFF.Line = this->Functions[c].Line;
Andy Cedilnik's avatar
Andy Cedilnik committed
134

135
    // for each argument of the current function
136
    for (std::vector<cmListFileArgument>::iterator k =
Ken Martin's avatar
Ken Martin committed
137
138
           this->Functions[c].Arguments.begin();
         k != this->Functions[c].Arguments.end(); ++k)
139
      {
140
141
142
      // Set the FilePath on the arguments to match the function since it is
      // not stored and the original values may be freed
      k->FilePath = this->FilePath.c_str();
143
144
145
146
147
148
      if(k->Delim == cmListFileArgument::Bracket)
        {
        arg.Value = k->Value;
        }
      else
        {
149
150
151
        tmps = k->Value;
        // replace formal arguments
        for (unsigned int j = 1; j < this->Args.size(); ++j)
152
          {
153
154
155
156
157
158
159
160
161
162
163
164
165
          variable = "${";
          variable += this->Args[j];
          variable += "}";
          cmSystemTools::ReplaceString(tmps, variable.c_str(),
                                       expandedArgs[j-1].c_str());
          }
        // replace argc
        cmSystemTools::ReplaceString(tmps, "${ARGC}",argcDef.c_str());

        // repleace ARGN
        if (tmps.find("${ARGN}") != std::string::npos)
          {
          if (!argnDefInitialized)
166
            {
167
168
169
            std::vector<std::string>::const_iterator eit;
            std::vector<std::string>::size_type cnt = 0;
            for(eit = expandedArgs.begin(); eit != expandedArgs.end(); ++eit)
170
              {
171
              if ( cnt >= this->Args.size()-1 )
172
                {
173
174
175
176
177
                if ( argnDef.size() > 0 )
                  {
                  argnDef += ";";
                  }
                argnDef += *eit;
178
                }
179
              cnt ++;
180
              }
181
            argnDefInitialized = true;
182
            }
183
          cmSystemTools::ReplaceString(tmps, "${ARGN}", argnDef.c_str());
184
          }
Andy Cedilnik's avatar
Andy Cedilnik committed
185

186
187
188
        // if the current argument of the current function has ${ARGV in it
        // then try replacing ARGV values
        if (tmps.find("${ARGV") != std::string::npos)
189
          {
190
191
192
193
          char argvName[60];

          // repleace ARGV, compute it only once
          if (!argvDefInitialized)
194
            {
195
196
            std::vector<std::string>::const_iterator eit;
            for(eit = expandedArgs.begin(); eit != expandedArgs.end(); ++eit)
197
              {
198
199
200
201
202
              if ( argvDef.size() > 0 )
                {
                argvDef += ";";
                }
              argvDef += *eit;
203
              }
204
            argvDefInitialized = true;
205
            }
206
          cmSystemTools::ReplaceString(tmps, "${ARGV}", argvDef.c_str());
Andy Cedilnik's avatar
Andy Cedilnik committed
207

208
209
210
211
212
213
214
          // also replace the ARGV1 ARGV2 ... etc
          for (unsigned int t = 0; t < expandedArgs.size(); ++t)
            {
            sprintf(argvName,"${ARGV%i}",t);
            cmSystemTools::ReplaceString(tmps, argvName,
                                         expandedArgs[t].c_str());
            }
215
          }
Andy Cedilnik's avatar
Andy Cedilnik committed
216

217
        arg.Value = tmps;
218
        }
219
      arg.Delim = k->Delim;
220
221
      arg.FilePath = k->FilePath;
      arg.Line = k->Line;
Ken Martin's avatar
Ken Martin committed
222
      newLFF.Arguments.push_back(arg);
223
      }
224
    cmExecutionStatus status;
225
226
    if(!this->Makefile->ExecuteCommand(newLFF, status) ||
       status.GetNestedError())
227
      {
228
229
      // The error message should have already included the call stack
      // so we do not need to report an error here.
230
      lexScope.Quiet();
231
      polScope.Quiet();
232
      inStatus.SetNestedError(true);
233
234
      return false;
      }
235
236
237
238
239
240
241
242
243
244
    if (status.GetReturnInvoked())
      {
      inStatus.SetReturnInvoked(true);
      return true;
      }
    if (status.GetBreakInvoked())
      {
      inStatus.SetBreakInvoked(true);
      return true;
      }
245
246
247
248
249
    }
  return true;
}

bool cmMacroFunctionBlocker::
250
251
IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile &mf,
                  cmExecutionStatus &)
252
253
254
{
  // record commands until we hit the ENDMACRO
  // at the ENDMACRO call we shift gears and start looking for invocations
255
  if(!cmSystemTools::Strucmp(lff.Name.c_str(),"macro"))
256
    {
Ken Martin's avatar
Ken Martin committed
257
258
    this->Depth++;
    }
259
  else if(!cmSystemTools::Strucmp(lff.Name.c_str(),"endmacro"))
Ken Martin's avatar
Ken Martin committed
260
261
    {
    // if this is the endmacro for this macro then execute
262
    if (!this->Depth)
263
      {
Ken Martin's avatar
Ken Martin committed
264
      std::string name = this->Args[0];
265
266
      std::vector<std::string>::size_type cc;
      name += "(";
Ken Martin's avatar
Ken Martin committed
267
      for ( cc = 0; cc < this->Args.size(); cc ++ )
268
        {
Ken Martin's avatar
Ken Martin committed
269
        name += " " + this->Args[cc];
270
        }
271
      name += " )";
Ken Martin's avatar
Ken Martin committed
272
      mf.AddMacro(this->Args[0].c_str(), name.c_str());
273
274
      // create a new command and add it to cmake
      cmMacroHelperCommand *f = new cmMacroHelperCommand();
Ken Martin's avatar
Ken Martin committed
275
276
      f->Args = this->Args;
      f->Functions = this->Functions;
277
      mf.RecordPolicies(f->Policies);
Ken Martin's avatar
Ken Martin committed
278
      std::string newName = "_" + this->Args[0];
279
      mf.GetCMakeInstance()->RenameCommand(this->Args[0].c_str(),
Ken Martin's avatar
Ken Martin committed
280
                                           newName.c_str());
281
      mf.AddCommand(f);
Andy Cedilnik's avatar
Andy Cedilnik committed
282

283
      // remove the function blocker now that the macro is defined
284
      mf.RemoveFunctionBlocker(this, lff);
285
      return true;
Ken Martin's avatar
Ken Martin committed
286
      }
Ken Martin's avatar
Ken Martin committed
287
288
289
290
291
    else
      {
      // decrement for each nested macro that ends
      this->Depth--;
      }
Ken Martin's avatar
Ken Martin committed
292
    }
Andy Cedilnik's avatar
Andy Cedilnik committed
293

294
295
  // if it wasn't an endmacro and we are not executing then we must be
  // recording
Ken Martin's avatar
Ken Martin committed
296
  this->Functions.push_back(lff);
297
  return true;
Ken Martin's avatar
Ken Martin committed
298
}
Andy Cedilnik's avatar
Andy Cedilnik committed
299

Ken Martin's avatar
Ken Martin committed
300
301

bool cmMacroFunctionBlocker::
Andy Cedilnik's avatar
Andy Cedilnik committed
302
ShouldRemove(const cmListFileFunction& lff, cmMakefile &mf)
Ken Martin's avatar
Ken Martin committed
303
{
304
  if(!cmSystemTools::Strucmp(lff.Name.c_str(),"endmacro"))
305
306
    {
    std::vector<std::string> expandedArguments;
Ken Martin's avatar
Ken Martin committed
307
    mf.ExpandArguments(lff.Arguments, expandedArguments);
308
309
310
311
    // if the endmacro has arguments make sure they
    // match the arguments of the macro
    if ((expandedArguments.empty() ||
         (expandedArguments[0] == this->Args[0])))
312
313
314
315
      {
      return true;
      }
    }
Ken Martin's avatar
Ken Martin committed
316

Ken Martin's avatar
Ken Martin committed
317
318
319
  return false;
}

320
321
bool cmMacroCommand::InitialPass(std::vector<std::string> const& args,
                                 cmExecutionStatus &)
Ken Martin's avatar
Ken Martin committed
322
323
324
325
326
327
{
  if(args.size() < 1)
    {
    this->SetError("called with incorrect number of arguments");
    return false;
    }
Andy Cedilnik's avatar
Andy Cedilnik committed
328

Ken Martin's avatar
Ken Martin committed
329
330
331
332
  // create a function blocker
  cmMacroFunctionBlocker *f = new cmMacroFunctionBlocker();
  for(std::vector<std::string>::const_iterator j = args.begin();
      j != args.end(); ++j)
333
    {
Ken Martin's avatar
Ken Martin committed
334
    f->Args.push_back(*j);
Ken Martin's avatar
Ken Martin committed
335
    }
Ken Martin's avatar
Ken Martin committed
336
  this->Makefile->AddFunctionBlocker(f);
Ken Martin's avatar
Ken Martin committed
337
338
339
  return true;
}