util.cpp 245 KB
Newer Older
1
/*****************************************************************************
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2
 *
3
 * 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4
 *
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5
 * Copyright (C) 1997-2013 by Dimitri van Heesch.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6 7 8 9 10 11 12
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation under the terms of the GNU General Public License is hereby 
 * granted. No representations are made about the suitability of this software 
 * for any purpose. It is provided "as is" without express or implied warranty.
 * See the GNU General Public License for more details.
 *
Dimitri van Heesch's avatar
Dimitri van Heesch committed
13 14
 * Documents produced by Doxygen are derivative works derived from the
 * input used in their production; they are not affected by this license.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
15 16 17 18 19
 *
 */

#include <stdlib.h>
#include <ctype.h>
20
#include <errno.h>
21
#include <math.h>
22

Dimitri van Heesch's avatar
Dimitri van Heesch committed
23
#include "md5.h"
24

25
#include <qregexp.h>
26
#include <qfileinfo.h>
27
#include <qdir.h>
28
#include <qdatetime.h>
29
#include <qcache.h>
Dimitri van Heesch's avatar
Dimitri van Heesch committed
30

Dimitri van Heesch's avatar
Dimitri van Heesch committed
31 32 33 34 35 36 37 38 39
#include "util.h"
#include "message.h"
#include "classdef.h"
#include "filedef.h"
#include "doxygen.h"
#include "outputlist.h"
#include "defargs.h"
#include "language.h"
#include "config.h"
40
#include "htmlhelp.h"
41
#include "example.h"
42
#include "version.h"
Dimitri van Heesch's avatar
Dimitri van Heesch committed
43
#include "groupdef.h"
44
#include "reflist.h"
45
#include "pagedef.h"
46
#include "debug.h"
47
#include "searchindex.h"
48
#include "doxygen.h"
49
#include "textdocvisitor.h"
50
#include "portable.h"
51
#include "parserintf.h"
52
#include "bufstr.h"
53
#include "image.h"
54
#include "growbuf.h"
55 56
#include "entry.h"
#include "arguments.h"
57 58 59 60 61 62 63
#include "memberlist.h"
#include "classlist.h"
#include "namespacedef.h"
#include "membername.h"
#include "filename.h"
#include "membergroup.h"
#include "dirdef.h"
Dimitri van Heesch's avatar
Dimitri van Heesch committed
64

65 66 67 68 69 70 71 72 73 74 75 76
#define ENABLE_TRACINGSUPPORT 0

#if defined(_OS_MAC_) && ENABLE_TRACINGSUPPORT
#define TRACINGSUPPORT
#endif

#ifdef TRACINGSUPPORT
#include <execinfo.h>
#include <unistd.h>
#endif


77 78
//------------------------------------------------------------------------

79 80 81 82 83 84 85 86 87 88
// selects one of the name to sub-dir mapping algorithms that is used
// to select a sub directory when CREATE_SUBDIRS is set to YES.

#define ALGO_COUNT 1
#define ALGO_CRC16 2
#define ALGO_MD5   3
    
//#define MAP_ALGO ALGO_COUNT
//#define MAP_ALGO ALGO_CRC16
#define MAP_ALGO ALGO_MD5
89

90 91
#define REL_PATH_TO_ROOT "../../"

92 93 94 95
//------------------------------------------------------------------------
// TextGeneratorOLImpl implementation
//------------------------------------------------------------------------

96 97 98
TextGeneratorOLImpl::TextGeneratorOLImpl(OutputDocInterface &od) : m_od(od) 
{
}
99

Dimitri van Heesch's avatar
Dimitri van Heesch committed
100
void TextGeneratorOLImpl::writeString(const char *s,bool keepSpaces) const
101
{ 
102 103
  if (s==0) return;
  //printf("TextGeneratorOlImpl::writeString('%s',%d)\n",s,keepSpaces);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
  if (keepSpaces)
  {
    const char *p=s;
    if (p)
    {
      char cs[2];
      char c;
      cs[1]='\0';
      while ((c=*p++))
      {
        if (c==' ') m_od.writeNonBreakableSpace(1); 
        else cs[0]=c,m_od.docify(cs);
      }
    }
  }
  else
  {
    m_od.docify(s); 
  }
123 124
}

125
void TextGeneratorOLImpl::writeBreak(int indent) const
126
{ 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
127
  m_od.lineBreak("typebreak");
128 129 130 131 132
  int i;
  for (i=0;i<indent;i++)
  {
    m_od.writeNonBreakableSpace(3);
  }
133 134 135 136 137 138
}

void TextGeneratorOLImpl::writeLink(const char *extRef,const char *file,
                                    const char *anchor,const char *text
                                   ) const
{
139
  //printf("TextGeneratorOlImpl::writeLink('%s')\n",text);
140
  m_od.writeObjectLink(extRef,file,anchor,text);
141 142 143 144 145
}

//------------------------------------------------------------------------
//------------------------------------------------------------------------

Dimitri van Heesch's avatar
Dimitri van Heesch committed
146 147 148
// an inheritance tree of depth of 100000 should be enough for everyone :-)
const int maxInheritanceDepth = 100000; 

149
/*! 
150
  Removes all anonymous scopes from string s
151 152 153 154 155 156 157 158 159 160 161 162 163
  Possible examples:
\verbatim
   "bla::@10::blep"      => "bla::blep"
   "bla::@10::@11::blep" => "bla::blep"
   "@10::blep"           => "blep"
   " @10::blep"          => "blep"
   "@9::@10::blep"       => "blep"
   "bla::@1"             => "bla"
   "bla::@1::@2"         => "bla"
   "bla @1"              => "bla"
\endverbatim
 */
QCString removeAnonymousScopes(const QCString &s)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
164 165
{
  QCString result;
166 167 168
  if (s.isEmpty()) return result;
  static QRegExp re("[ :]*@[0-9]+[: ]*");
  int i,l,sl=s.length();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
169
  int p=0;
170
  while ((i=re.match(s,p,&l))!=-1)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
171
  {
172 173 174 175 176 177 178 179 180
    result+=s.mid(p,i-p);
    int c=i;
    bool b1=FALSE,b2=FALSE;
    while (c<i+l && s.at(c)!='@') if (s.at(c++)==':') b1=TRUE;
    c=i+l-1;
    while (c>=i && s.at(c)!='@') if (s.at(c--)==':') b2=TRUE;
    if (b1 && b2) 
    { 
      result+="::"; 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
181
    }
182 183 184 185 186 187 188
    p=i+l;
  }
  result+=s.right(sl-p);
  //printf("removeAnonymousScopes(`%s')=`%s'\n",s.data(),result.data());
  return result;
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
189 190
// replace anonymous scopes with __anonymous__ or replacement if provided
QCString replaceAnonymousScopes(const QCString &s,const char *replacement)
191 192 193 194 195 196 197 198 199
{
  QCString result;
  if (s.isEmpty()) return result;
  static QRegExp re("@[0-9]+");
  int i,l,sl=s.length();
  int p=0;
  while ((i=re.match(s,p,&l))!=-1)
  {
    result+=s.mid(p,i-p);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
200 201 202 203 204 205 206 207
    if (replacement)
    {
      result+=replacement;
    }
    else
    {
      result+="__anonymous__";
    }
208
    p=i+l;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
209
  }
210 211
  result+=s.right(sl-p);
  //printf("replaceAnonymousScopes(`%s')=`%s'\n",s.data(),result.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
212 213 214
  return result;
}

215

216
// strip anonymous left hand side part of the scope
217
QCString stripAnonymousNamespaceScope(const QCString &s)
218
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
219 220
  int i,p=0,l;
  QCString newScope;
221
  int sl = s.length();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
222 223 224
  while ((i=getScopeFragment(s,p,&l))!=-1)
  {
    //printf("Scope fragment %s\n",s.mid(i,l).data());
225
    if (Doxygen::namespaceSDict->find(s.left(i+l))!=0)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
226 227 228 229 230 231 232
    {
      if (s.at(i)!='@')
      {
        if (!newScope.isEmpty()) newScope+="::";
        newScope+=s.mid(i,l);
      }
    }
233
    else if (i<sl)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
234 235
    {
      if (!newScope.isEmpty()) newScope+="::";
236
      newScope+=s.right(sl-i);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
237 238 239 240 241 242 243
      goto done;
    }
    p=i+l;
  }
done:
  //printf("stripAnonymousNamespaceScope(`%s')=`%s'\n",s.data(),newScope.data());
  return newScope;
244 245
}

246
void writePageRef(OutputDocInterface &od,const char *cn,const char *mn)
247
{
248
  od.pushGeneratorState();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
249
  
250 251
  od.disable(OutputGenerator::Html);
  od.disable(OutputGenerator::Man);
252 253
  if (Config_getBool("PDF_HYPERLINKS")) od.disable(OutputGenerator::Latex);
  if (Config_getBool("RTF_HYPERLINKS")) od.disable(OutputGenerator::RTF);
254 255 256 257 258
  od.startPageRef();
  od.docify(theTranslator->trPageAbbreviation());
  od.endPageRef(cn,mn);

  od.popGeneratorState();
259
}
260

Dimitri van Heesch's avatar
Dimitri van Heesch committed
261 262 263 264
/*! Generate a place holder for a position in a list. Used for
 *  translators to be able to specify different elements orders
 *  depending on whether text flows from left to right or visa versa.
 */
265
QCString generateMarker(int id)
266
{
267
  QCString result;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
268
  result.sprintf("@%d",id);
269 270
  return result;
}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
271

272
static QCString stripFromPath(const QCString &path,QStrList &l)
273
{
274
  // look at all the strings in the list and strip the longest match  
275
  const char *s=l.first();
276 277
  QCString potential;
  unsigned int length = 0;
278 279 280
  while (s)
  {
    QCString prefix = s;
281
    if (prefix.length() > length &&
Dimitri van Heesch's avatar
Dimitri van Heesch committed
282
        qstricmp(path.left(prefix.length()),prefix)==0) // case insensitive compare
283
    {
284 285
      length = prefix.length();
      potential = path.right(path.length()-prefix.length());
286
    }
287
    s = l.next();
288
  }
289
  if (length) return potential;
290 291 292
  return path;
}

293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
/*! strip part of \a path if it matches
 *  one of the paths in the Config_getList("STRIP_FROM_PATH") list
 */
QCString stripFromPath(const QCString &path)
{
  return stripFromPath(path,Config_getList("STRIP_FROM_PATH"));
}

/*! strip part of \a path if it matches
 *  one of the paths in the Config_getList("INCLUDE_PATH") list
 */
QCString stripFromIncludePath(const QCString &path)
{
  return stripFromPath(path,Config_getList("STRIP_FROM_INC_PATH"));
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
309 310 311 312
/*! try to determine if \a name is a source or a header file name by looking
 * at the extension. A number of variations is allowed in both upper and 
 * lower case) If anyone knows or uses another extension please let me know :-)
 */
Dimitri van Heesch's avatar
Dimitri van Heesch committed
313 314
int guessSection(const char *name)
{
315
  QCString n=((QCString)name).lower();
316 317 318 319 320 321
  if (n.right(2)==".c"    || // source
      n.right(3)==".cc"   ||
      n.right(4)==".cxx"  ||
      n.right(4)==".cpp"  ||
      n.right(4)==".c++"  ||
      n.right(5)==".java" ||
Dimitri van Heesch's avatar
Dimitri van Heesch committed
322 323 324
      n.right(2)==".m"    ||
      n.right(2)==".M"    ||
      n.right(3)==".mm"   ||
325 326 327 328
      n.right(3)==".ii"   || // inline
      n.right(4)==".ixx"  ||
      n.right(4)==".ipp"  ||
      n.right(4)==".i++"  ||
329
      n.right(4)==".inl"  ||
Dimitri van Heesch's avatar
Dimitri van Heesch committed
330
      n.right(4)==".xml" 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
331
     ) return Entry::SOURCE_SEC;
332
  if (n.right(2)==".h"   || // header
Dimitri van Heesch's avatar
Dimitri van Heesch committed
333 334 335
      n.right(3)==".hh"  ||
      n.right(4)==".hxx" ||
      n.right(4)==".hpp" ||
336
      n.right(4)==".h++" ||
337
      n.right(4)==".idl" ||
338
      n.right(4)==".ddl" ||
339
      n.right(5)==".pidl"
Dimitri van Heesch's avatar
Dimitri van Heesch committed
340 341 342 343
     ) return Entry::HEADER_SEC;
  return 0;
}

344 345
QCString resolveTypeDef(Definition *context,const QCString &qualifiedName,
                        Definition **typedefContext)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
346
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
347
  //printf("<<resolveTypeDef(%s,%s)\n",
348
  //          context ? context->name().data() : "<none>",qualifiedName.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
349
  QCString result;
350 351 352 353 354
  if (qualifiedName.isEmpty()) 
  {
    //printf("  qualified name empty!\n");
    return result;
  }
355

356 357 358 359 360 361 362 363 364
  Definition *mContext=context;
  if (typedefContext) *typedefContext=context;

  // see if the qualified name has a scope part
  int scopeIndex = qualifiedName.findRev("::");
  QCString resName=qualifiedName;
  if (scopeIndex!=-1) // strip scope part for the name
  {
    resName=qualifiedName.right(qualifiedName.length()-scopeIndex-2);
365 366 367
    if (resName.isEmpty())
    {
      // qualifiedName was of form A:: !
368
      //printf("  qualified name of form A::!\n");
369 370
      return result;
    }
371
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
372 373 374
  MemberDef *md=0;
  while (mContext && md==0)
  {
375 376 377
    // step 1: get the right scope
    Definition *resScope=mContext;
    if (scopeIndex!=-1) 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
378
    {
379 380 381 382 383 384 385 386 387 388
      // split-off scope part
      QCString resScopeName = qualifiedName.left(scopeIndex);
      //printf("resScopeName=`%s'\n",resScopeName.data());

      // look-up scope in context
      int is,ps=0;
      int l;
      while ((is=getScopeFragment(resScopeName,ps,&l))!=-1)
      {
        QCString qualScopePart = resScopeName.mid(is,l);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
389
        QCString tmp = resolveTypeDef(mContext,qualScopePart);
390 391 392 393 394 395
        if (!tmp.isEmpty()) qualScopePart=tmp;
        resScope = resScope->findInnerCompound(qualScopePart);
        //printf("qualScopePart=`%s' resScope=%p\n",qualScopePart.data(),resScope);
        if (resScope==0) break;
        ps=is+l;
      }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
396
    }
397
    //printf("resScope=%s\n",resScope?resScope->name().data():"<none>");
398 399 400
    
    // step 2: get the member
    if (resScope) // no scope or scope found in the current context 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
401
    {
402 403 404 405 406
      //printf("scope found: %s, look for typedef %s\n",
      //     resScope->qualifiedName().data(),resName.data());
      MemberNameSDict *mnd=0;
      if (resScope->definitionType()==Definition::TypeClass)
      {
407
        mnd=Doxygen::memberNameSDict;
408 409
      }
      else
Dimitri van Heesch's avatar
Dimitri van Heesch committed
410
      {
411
        mnd=Doxygen::functionNameSDict;
412 413 414 415 416 417
      }
      MemberName *mn=mnd->find(resName);
      if (mn)
      {
        MemberNameIterator mni(*mn);
        MemberDef *tmd=0;
418
        int minDist=-1;
419
        for (;(tmd=mni.current());++mni)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
420
        {
421 422 423 424
          //printf("Found member %s resScope=%s outerScope=%s mContext=%p\n",
          //    tmd->name().data(), resScope->name().data(), 
          //    tmd->getOuterScope()->name().data(), mContext);
          if (tmd->isTypedef() /*&& tmd->getOuterScope()==resScope*/)
425
          {
426 427
            int dist=isAccessibleFrom(resScope,0,tmd);
            if (dist!=-1 && (md==0 || dist<minDist))
428
            {
429 430
              md = tmd;
              minDist = dist;
431
            }
432
          }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
433 434 435 436 437
        }
      }
    }
    mContext=mContext->getOuterScope();
  }
438 439

  // step 3: get the member's type
Dimitri van Heesch's avatar
Dimitri van Heesch committed
440 441
  if (md)
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
442 443
    //printf(">>resolveTypeDef: Found typedef name `%s' in scope `%s' value=`%s' args='%s'\n",
    //    qualifiedName.data(),context->name().data(),md->typeString(),md->argsString()
Dimitri van Heesch's avatar
Dimitri van Heesch committed
444 445
    //    );
    result=md->typeString();
446
    QCString args = md->argsString();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
447
    if (args.find(")(")!=-1) // typedef of a function/member pointer
448
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
449
      result+=args;
450
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
451
    else if (args.find('[')!=-1) // typedef of an array
Dimitri van Heesch's avatar
Dimitri van Heesch committed
452 453 454
    {
      result+=args;
    }
455
    if (typedefContext) *typedefContext=md->getOuterScope();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
456 457 458
  }
  else
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
459
    //printf(">>resolveTypeDef: Typedef `%s' not found in scope `%s'!\n",
460
    //    qualifiedName.data(),context ? context->name().data() : "<global>");
Dimitri van Heesch's avatar
Dimitri van Heesch committed
461 462 463 464 465
  }
  return result;
  
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
466

Dimitri van Heesch's avatar
Dimitri van Heesch committed
467 468 469
/*! Get a class definition given its name. 
 *  Returns 0 if the class is not found.
 */
Dimitri van Heesch's avatar
Dimitri van Heesch committed
470
ClassDef *getClass(const char *n)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
471
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
472 473 474 475 476 477 478 479 480 481 482 483 484
  if (n==0 || n[0]=='\0') return 0;
  QCString name=n;
  ClassDef *result = Doxygen::classSDict->find(name);
  //if (result==0 && !exact) // also try generic and protocol versions
  //{
  //  result = Doxygen::classSDict->find(name+"-g");
  //  if (result==0)
  //  {
  //    result = Doxygen::classSDict->find(name+"-p");
  //  }
  //}
  //printf("getClass(%s)=%s\n",n,result?result->name().data():"<none>");
  return result;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
485 486
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
487 488 489
NamespaceDef *getResolvedNamespace(const char *name)
{
  if (name==0 || name[0]=='\0') return 0;
490
  QCString *subst = Doxygen::namespaceAliasDict[name];
Dimitri van Heesch's avatar
Dimitri van Heesch committed
491 492 493 494
  if (subst)
  {
    int count=0; // recursion detection guard
    QCString *newSubst;
495
    while ((newSubst=Doxygen::namespaceAliasDict[*subst]) && count<10)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
496 497 498 499 500 501
    {
      subst=newSubst;
      count++;
    }
    if (count==10)
    {
502
      warn_uncond("possible recursive namespace alias detected for %s!\n",name);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
503
    }
504
    return Doxygen::namespaceSDict->find(subst->data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
505 506 507
  }
  else
  {
508
    return Doxygen::namespaceSDict->find(name);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
509 510 511
  }
}

512
static QDict<MemberDef> g_resolvedTypedefs;
513
static QDict<Definition> g_visitedNamespaces;
514 515

// forward declaration
Dimitri van Heesch's avatar
Dimitri van Heesch committed
516
static ClassDef *getResolvedClassRec(Definition *scope,
517 518
                              FileDef *fileScope,
                              const char *n,
519
                              MemberDef **pTypeDef,
520 521
                              QCString *pTemplSpec,
                              QCString *pResolvedType
522
                             );
523
int isAccessibleFromWithExpScope(Definition *scope,FileDef *fileScope,Definition *item,
524 525
                     const QCString &explicitScopePart);

526 527
/*! Returns the class representing the value of the typedef represented by \a md
 *  within file \a fileScope.
528 529 530 531 532
 *
 *  Example: typedef A T; will return the class representing A if it is a class.
 * 
 *  Example: typedef int T; will return 0, since "int" is not a class.
 */
533
ClassDef *newResolveTypedef(FileDef *fileScope,MemberDef *md,
534
                            MemberDef **pMemType,QCString *pTemplSpec,
535 536
                            QCString *pResolvedType,
                            ArgumentList *actTemplParams)
537
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
538
  //printf("newResolveTypedef(md=%p,cachedVal=%p)\n",md,md->getCachedTypedefVal());
539 540 541
  bool isCached = md->isTypedefValCached(); // value already cached
  if (isCached)
  {
542
    //printf("Already cached %s->%s [%s]\n",
543
    //    md->name().data(),
544 545 546
    //    md->getCachedTypedefVal()?md->getCachedTypedefVal()->name().data():"<none>",
    //    md->getCachedResolvedTypedef()?md->getCachedResolvedTypedef().data():"<none>");

547 548
    if (pTemplSpec)    *pTemplSpec    = md->getCachedTypedefTemplSpec();
    if (pResolvedType) *pResolvedType = md->getCachedResolvedTypedef();
549 550
    return md->getCachedTypedefVal();
  }
551
  //printf("new typedef\n");
552 553
  QCString qname = md->qualifiedName();
  if (g_resolvedTypedefs.find(qname)) return 0; // typedef already done
554

555 556
  g_resolvedTypedefs.insert(qname,md); // put on the trace list
  
557
  ClassDef *typeClass = md->getClassDef();
558
  QCString type = md->typeString(); // get the "value" of the typedef
559 560
  if (typeClass && typeClass->isTemplate() && 
      actTemplParams && actTemplParams->count()>0)
561 562 563 564
  {
    type = substituteTemplateArgumentsInString(type,
            typeClass->templateArguments(),actTemplParams);
  }
565 566 567
  QCString typedefValue = type;
  int tl=type.length();
  int ip=tl-1; // remove * and & at the end
568 569 570 571 572
  while (ip>=0 && (type.at(ip)=='*' || type.at(ip)=='&' || type.at(ip)==' ')) 
  {
    ip--;
  }
  type=type.left(ip+1);
573 574 575
  type.stripPrefix("const ");  // strip leading "const"
  type.stripPrefix("struct "); // strip leading "struct"
  type.stripPrefix("union ");  // strip leading "union"
576
  int sp=0;
577
  tl=type.length(); // length may have been changed
578
  while (sp<tl && type.at(sp)==' ') sp++;
579 580
  MemberDef *memTypeDef = 0;
  ClassDef  *result = getResolvedClassRec(md->getOuterScope(),
581 582
                                  fileScope,type,&memTypeDef,0,pResolvedType);
  // if type is a typedef then return what it resolves to.
583 584
  if (memTypeDef && memTypeDef->isTypedef()) 
  {
585 586
    result=newResolveTypedef(fileScope,memTypeDef,pMemType,pTemplSpec);
    goto done;
587 588 589 590 591
  }
  else if (memTypeDef && memTypeDef->isEnumerate() && pMemType)
  {
    *pMemType = memTypeDef;
  }
592

593
  //printf("type=%s result=%p\n",type.data(),result);
594 595 596
  if (result==0)
  {
    // try unspecialized version if type is template
597
    int si=type.findRev("::");
598
    int i=type.find('<');
599
    if (si==-1 && i!=-1) // typedef of a template => try the unspecialized version
600
    {
601 602 603
      if (pTemplSpec) *pTemplSpec = type.mid(i);
      result = getResolvedClassRec(md->getOuterScope(),fileScope,
                                   type.left(i),0,0,pResolvedType);
604 605
      //printf("result=%p pRresolvedType=%s sp=%d ip=%d tl=%d\n",
      //    result,pResolvedType?pResolvedType->data():"<none>",sp,ip,tl);
606
    }
607 608 609 610 611 612 613 614 615
    else if (si!=-1) // A::B
    {
      i=type.find('<',si);
      if (i==-1) // Something like A<T>::B => lookup A::B
      {
        i=type.length();
      }
      else // Something like A<T>::B<S> => lookup A::B, spec=<S>
      {
616
        if (pTemplSpec) *pTemplSpec = type.mid(i);
617 618
      }
      result = getResolvedClassRec(md->getOuterScope(),fileScope,
619 620 621 622
           stripTemplateSpecifiersFromScope(type.left(i),FALSE),0,0,
           pResolvedType);
    }

623
    //if (result) ip=si+sp+1;
624 625 626 627 628 629 630 631
  }

done:
  if (pResolvedType)
  {
    if (result)
    {
      *pResolvedType=result->qualifiedName();
632
      //printf("*pResolvedType=%s\n",pResolvedType->data());
633 634 635 636 637 638
      if (sp>0)    pResolvedType->prepend(typedefValue.left(sp));
      if (ip<tl-1) pResolvedType->append(typedefValue.right(tl-ip-1));
    }
    else
    {
      *pResolvedType=typedefValue;
639
    }
640 641 642
  }

  // remember computed value for next time
Dimitri van Heesch's avatar
Dimitri van Heesch committed
643
  if (result && result->getDefFileName()!="<code>") 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
644 645 646 647 648
    // this check is needed to prevent that temporary classes that are 
    // introduced while parsing code fragments are being cached here.
  {
    //printf("setting cached typedef %p in result %p\n",md,result);
    //printf("==> %s (%s,%d)\n",result->name().data(),result->getDefFileName().data(),result->getDefLine());
649
    //printf("*pResolvedType=%s\n",pResolvedType?pResolvedType->data():"<none>");
650 651 652 653
    md->cacheTypedefVal(result,
        pTemplSpec ? *pTemplSpec : QCString(),
        pResolvedType ? *pResolvedType : QCString()
       );
Dimitri van Heesch's avatar
Dimitri van Heesch committed
654
  }
655 656 657 658 659 660 661 662 663
  
  g_resolvedTypedefs.remove(qname); // remove from the trace list
  
  return result;
}

/*! Substitutes a simple unqualified \a name within \a scope. Returns the
 *  value of the typedef or \a name if no typedef was found.
 */
664 665
static QCString substTypedef(Definition *scope,FileDef *fileScope,const QCString &name,
            MemberDef **pTypeDef=0)
666
{
667 668 669 670
  QCString result=name;
  if (name.isEmpty()) return result;

  // lookup scope fragment in the symbol map
671 672
  DefinitionIntf *di = Doxygen::symbolMap->find(name);
  if (di==0) return result; // no matches
673 674

  MemberDef *bestMatch=0;
675
  if (di->definitionType()==DefinitionIntf::TypeSymbolList) // multi symbols
676
  {
677 678 679 680 681
    // search for the best match
    DefinitionListIterator dli(*(DefinitionList*)di);
    Definition *d;
    int minDistance=10000; // init at "infinite"
    for (dli.toFirst();(d=dli.current());++dli) // foreach definition
682
    {
683 684
      // only look at members
      if (d->definitionType()==Definition::TypeMember)
685
      {
686 687 688
        // that are also typedefs
        MemberDef *md = (MemberDef *)d;
        if (md->isTypedef()) // d is a typedef
689
        {
690 691 692 693 694 695 696 697
          // test accessibility of typedef within scope.
          int distance = isAccessibleFromWithExpScope(scope,fileScope,d,"");
          if (distance!=-1 && distance<minDistance) 
            // definition is accessible and a better match
          {
            minDistance=distance;
            bestMatch = md; 
          }
698
        }
699 700 701
      }
    }
  }
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
  else if (di->definitionType()==DefinitionIntf::TypeMember) // single symbol
  {
    Definition *d = (Definition*)di;
    // that are also typedefs
    MemberDef *md = (MemberDef *)di;
    if (md->isTypedef()) // d is a typedef
    {
      // test accessibility of typedef within scope.
      int distance = isAccessibleFromWithExpScope(scope,fileScope,d,"");
      if (distance!=-1) // definition is accessible 
      {
        bestMatch = md; 
      }
    }
  }
717 718 719 720 721 722
  if (bestMatch) 
  {
    result = bestMatch->typeString();
    if (pTypeDef) *pTypeDef=bestMatch;
  }
  
723 724 725 726 727
  //printf("substTypedef(%s,%s)=%s\n",scope?scope->name().data():"<global>",
  //                                  name.data(),result.data());
  return result;
}

728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
static Definition *endOfPathIsUsedClass(SDict<Definition> *cl,const QCString &localName)
{
  if (cl)
  {
    SDict<Definition>::Iterator cli(*cl);
    Definition *cd;
    for (cli.toFirst();(cd=cli.current());++cli)
    {
      if (cd->localName()==localName)
      {
        return cd;
      }
    }
  }
  return 0;
}

745 746 747 748 749 750 751
/*! Starting with scope \a start, the string \a path is interpreted as
 *  a part of a qualified scope name (e.g. A::B::C), and the scope is 
 *  searched. If found the scope definition is returned, otherwise 0 
 *  is returned.
 */
static Definition *followPath(Definition *start,FileDef *fileScope,const QCString &path)
{
752
  int is,ps;
753 754
  int l;
  Definition *current=start;
755
  ps=0;
756
  //printf("followPath: start='%s' path='%s'\n",start?start->name().data():"<none>",path.data());
757 758 759 760
  // for each part of the explicit scope
  while ((is=getScopeFragment(path,ps,&l))!=-1)
  {
    // try to resolve the part if it is a typedef
761 762
    MemberDef *typeDef=0;
    QCString qualScopePart = substTypedef(current,fileScope,path.mid(is,l),&typeDef);
763
    //printf("      qualScopePart=%s\n",qualScopePart.data());
764 765 766 767 768
    if (typeDef)
    {
      ClassDef *type = newResolveTypedef(fileScope,typeDef);
      if (type)
      {
769
        //printf("Found type %s\n",type->name().data());
770 771 772
        return type;
      }
    }
773
    Definition *next = current->findInnerCompound(qualScopePart);
774 775 776 777
    //printf("++ Looking for %s inside %s result %s\n",
    //     qualScopePart.data(),
    //     current->name().data(),
    //     next?next->name().data():"<null>");
778 779
    if (next==0) // failed to follow the path 
    {
780
      //printf("==> next==0!\n");
781 782
      if (current->definitionType()==Definition::TypeNamespace)
      {
783
        next = endOfPathIsUsedClass(
784 785 786 787
            ((NamespaceDef *)current)->getUsedClasses(),qualScopePart);
      }
      else if (current->definitionType()==Definition::TypeFile)
      {
788
        next = endOfPathIsUsedClass(
789 790
            ((FileDef *)current)->getUsedClasses(),qualScopePart);
      }
791
      current = next;
792 793 794 795 796
      if (current==0) break;
    }
    else // continue to follow scope
    {
      current = next;
797
      //printf("==> current = %p\n",current);
798
    }
799 800
    ps=is+l;
  }
801 802
  //printf("followPath(start=%s,path=%s) result=%s\n",
  //    start->name().data(),path.data(),current?current->name().data():"<null>");
803 804 805
  return current; // path could be followed
}

806
bool accessibleViaUsingClass(const SDict<Definition> *cl,
807 808
                             FileDef *fileScope,
                             Definition *item,
809 810
                             const QCString &explicitScopePart=""
                            )
811
{
812
  //printf("accessibleViaUsingClass(%p)\n",cl);
813 814
  if (cl) // see if the class was imported via a using statement 
  {
815 816 817
    SDict<Definition>::Iterator cli(*cl);
    Definition *ucd;
    bool explicitScopePartEmpty = explicitScopePart.isEmpty();
818 819
    for (cli.toFirst();(ucd=cli.current());++cli)
    {
820
      //printf("Trying via used class %s\n",ucd->name().data());
821 822
      Definition *sc = explicitScopePartEmpty ? ucd : followPath(ucd,fileScope,explicitScopePart);
      if (sc && sc==item) return TRUE; 
823
      //printf("Try via used class done\n");
824
    }
825 826 827 828
  }
  return FALSE;
}

829 830 831 832
bool accessibleViaUsingNamespace(const NamespaceSDict *nl,
                                 FileDef *fileScope,
                                 Definition *item,
                                 const QCString &explicitScopePart="")
833
{
834
  static QDict<void> visitedDict;
835 836 837 838
  if (nl) // check used namespaces for the class
  {
    NamespaceSDict::Iterator nli(*nl);
    NamespaceDef *und;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
839 840
    int count=0;
    for (nli.toFirst();(und=nli.current());++nli,count++)
841
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
842 843
      //printf("[Trying via used namespace %s: count=%d/%d\n",und->name().data(),
      //    count,nl->count());
844
      Definition *sc = explicitScopePart.isEmpty() ? und : followPath(und,fileScope,explicitScopePart);
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
      if (sc && item->getOuterScope()==sc) 
      {
        //printf("] found it\n");
        return TRUE; 
      }
      QCString key=und->name();
      if (und->getUsedNamespaces() && visitedDict.find(key)==0)
      {
        visitedDict.insert(key,(void *)0x08);

        if (accessibleViaUsingNamespace(und->getUsedNamespaces(),fileScope,item,explicitScopePart))
        {
          //printf("] found it via recursion\n");
          return TRUE;
        }

        visitedDict.remove(key);
      }
      //printf("] Try via used namespace done\n");
864 865 866 867 868
    }
  }
  return FALSE;
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
869 870
const int MAX_STACK_SIZE = 1000;

Dimitri van Heesch's avatar
Dimitri van Heesch committed
871 872 873
/** Helper class representing the stack of items considered while resolving
 *  the scope.
 */
Dimitri van Heesch's avatar
Dimitri van Heesch committed
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
class AccessStack
{
  public:
    AccessStack() : m_index(0) {}
    void push(Definition *scope,FileDef *fileScope,Definition *item)
    {
      if (m_index<MAX_STACK_SIZE)
      {
        m_elements[m_index].scope     = scope;
        m_elements[m_index].fileScope = fileScope;
        m_elements[m_index].item      = item;
        m_index++;
      }
    }
    void push(Definition *scope,FileDef *fileScope,Definition *item,const QCString &expScope)
    {
      if (m_index<MAX_STACK_SIZE)
      {
        m_elements[m_index].scope     = scope;
        m_elements[m_index].fileScope = fileScope;
        m_elements[m_index].item      = item;
        m_elements[m_index].expScope  = expScope;
        m_index++;
      }
    }
    void pop()
    {
      if (m_index>0) m_index--;
    }
    bool find(Definition *scope,FileDef *fileScope, Definition *item)
    {
      int i=0;
      for (i=0;i<m_index;i++)
      {
        AccessElem *e = &m_elements[i];
        if (e->scope==scope && e->fileScope==fileScope && e->item==item) 
        {
          return TRUE;
        }
      }
      return FALSE;
    }
    bool find(Definition *scope,FileDef *fileScope, Definition *item,const QCString &expScope)
    {
      int i=0;
      for (i=0;i<m_index;i++)
      {
        AccessElem *e = &m_elements[i];
        if (e->scope==scope && e->fileScope==fileScope && e->item==item && e->expScope==expScope) 
        {
          return TRUE;
        }
      }
      return FALSE;
    }

  private:
Dimitri van Heesch's avatar
Dimitri van Heesch committed
931
    /** Element in the stack. */
Dimitri van Heesch's avatar
Dimitri van Heesch committed
932 933 934 935 936 937 938 939 940 941
    struct AccessElem
    {
      Definition *scope;
      FileDef *fileScope;
      Definition *item;
      QCString expScope;
    };
    int m_index;
    AccessElem m_elements[MAX_STACK_SIZE];
};
942

943 944 945 946 947
/* Returns the "distance" (=number of levels up) from item to scope, or -1
 * if item in not inside scope. 
 */
int isAccessibleFrom(Definition *scope,FileDef *fileScope,Definition *item)
{
948
  //printf("<isAccesibleFrom(scope=%s,item=%s itemScope=%s)\n",
949
  //    scope->name().data(),item->name().data(),item->getOuterScope()->name().data());
950

Dimitri van Heesch's avatar
Dimitri van Heesch committed
951 952
  static AccessStack accessStack;
  if (accessStack.find(scope,fileScope,item))
953
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
954
    return -1;
955
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
956
  accessStack.push(scope,fileScope,item);
957

958 959
  int result=0; // assume we found it
  int i;
960

961
  Definition *itemScope=item->getOuterScope();
962
  bool memberAccessibleFromScope = 
963 964 965 966
      (item->definitionType()==Definition::TypeMember &&                   // a member
       itemScope && itemScope->definitionType()==Definition::TypeClass  && // of a class
       scope->definitionType()==Definition::TypeClass &&                   // accessible
       ((ClassDef*)scope)->isAccessibleMember((MemberDef *)item)           // from scope
967 968
      );
  bool nestedClassInsideBaseClass = 
969 970 971 972
      (item->definitionType()==Definition::TypeClass &&                    // a nested class
       itemScope && itemScope->definitionType()==Definition::TypeClass &&  // inside a base 
       scope->definitionType()==Definition::TypeClass &&                   // class of scope
       ((ClassDef*)scope)->isBaseClass((ClassDef*)itemScope,TRUE)          
973 974 975
      );

  if (itemScope==scope || memberAccessibleFromScope || nestedClassInsideBaseClass) 
976
  {
977
    //printf("> found it\n");
978 979 980
    if (nestedClassInsideBaseClass) result++; // penalty for base class to prevent
                                              // this is preferred over nested class in this class
                                              // see bug 686956
981 982 983 984 985
  }
  else if (scope==Doxygen::globalScope)
  {
    if (fileScope)
    {
986
      SDict<Definition> *cl = fileScope->getUsedClasses();
987 988
      if (accessibleViaUsingClass(cl,fileScope,item)) 
      {
989
        //printf("> found via used class\n");
990 991
        goto done;
      }
992
      NamespaceSDict *nl = fileScope->getUsedNamespaces();
993 994
      if (accessibleViaUsingNamespace(nl,fileScope,item)) 
      {
995
        //printf("> found via used namespace\n");
996 997
        goto done;
      }
998
    }
999
    //printf("> reached global scope\n");
1000
    result=-1; // not found in path to globalScope
1001 1002 1003 1004 1005 1006 1007
  }
  else // keep searching
  {
    // check if scope is a namespace, which is using other classes and namespaces
    if (scope->definitionType()==Definition::TypeNamespace)
    {
      NamespaceDef *nscope = (NamespaceDef*)scope;
1008
      //printf("  %s is namespace with %d used classes\n",nscope->name().data(),nscope->getUsedClasses());
1009
      SDict<Definition> *cl = nscope->getUsedClasses();
1010 1011
      if (accessibleViaUsingClass(cl,fileScope,item)) 
      {
1012
        //printf("> found via used class\n");
1013 1014
        goto done;
      }
1015
      NamespaceSDict *nl = nscope->getUsedNamespaces();
1016 1017
      if (accessibleViaUsingNamespace(nl,fileScope,item)) 
      {
1018
        //printf("> found via used namespace\n");
1019 1020
        goto done;
      }
1021 1022
    }
    // repeat for the parent scope
1023
    i=isAccessibleFrom(scope->getOuterScope(),fileScope,item);
1024
    //printf("> result=%d\n",i);
1025
    result= (i==-1) ? -1 : i+2;
1026
  }
1027
done:
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1028
  accessStack.pop();
1029
  //Doxygen::lookupCache.insert(key,new int(result));
1030
  return result;
1031 1032 1033 1034 1035
}


/* Returns the "distance" (=number of levels up) from item to scope, or -1
 * if item in not in this scope. The explicitScopePart limits the search
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
 * to scopes that match \a scope (or its parent scope(s)) plus the explicit part.
 * Example:
 *
 * class A { public: class I {}; };
 * class B { public: class J {}; };
 *
 * - Looking for item=='J' inside scope=='B' will return 0.
 * - Looking for item=='I' inside scope=='B' will return -1 
 *   (as it is not found in B nor in the global scope).
 * - Looking for item=='A::I' inside scope=='B', first the match B::A::I is tried but 
 *   not found and then A::I is searched in the global scope, which matches and 
 *   thus the result is 1.
1048
 */
1049 1050
int isAccessibleFromWithExpScope(Definition *scope,FileDef *fileScope,
                     Definition *item,const QCString &explicitScopePart)
1051 1052 1053 1054 1055 1056
{
  if (explicitScopePart.isEmpty())
  {
    // handle degenerate case where there is no explicit scope.
    return isAccessibleFrom(scope,fileScope,item);
  }
1057

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1058 1059
  static AccessStack accessStack;
  if (accessStack.find(scope,fileScope,item,explicitScopePart))
1060
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1061
    return -1;
1062
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1063 1064
  accessStack.push(scope,fileScope,item,explicitScopePart);

1065

1066
  //printf("  <isAccessibleFromWithExpScope(%s,%s,%s)\n",scope?scope->name().data():"<global>",
1067 1068
  //                                      item?item->name().data():"<none>",
  //                                      explicitScopePart.data());
1069
  int result=0; // assume we found it
1070 1071 1072
  Definition *newScope = followPath(scope,fileScope,explicitScopePart);
  if (newScope)  // explicitScope is inside scope => newScope is the result
  {
1073
    Definition *itemScope = item->getOuterScope();
1074
    //printf("    scope traversal successful %s<->%s!\n",itemScope->name().data(),newScope->name().data());
1075 1076 1077 1078 1079
    //if (newScope && newScope->definitionType()==Definition::TypeClass)
    //{
    //  ClassDef *cd = (ClassDef *)newScope;
    //  printf("---> Class %s: bases=%p\n",cd->name().data(),cd->baseClasses());
    //}
1080
    if (itemScope==newScope)  // exact match of scopes => distance==0
1081 1082 1083
    {
      //printf("> found it\n");
    }
1084 1085 1086 1087 1088 1089 1090 1091 1092
    else if (itemScope && newScope &&
             itemScope->definitionType()==Definition::TypeClass &&
             newScope->definitionType()==Definition::TypeClass &&
             ((ClassDef*)newScope)->isBaseClass((ClassDef*)itemScope,TRUE,0)
            )
    {
      // inheritance is also ok. Example: looking for B::I, where 
      // class A { public: class I {} };
      // class B : public A {}
1093 1094 1095 1096 1097
      // but looking for B::I, where
      // class A { public: class I {} };
      // class B { public: class I {} };
      // will find A::I, so we still prefer a direct match and give this one a distance of 1
      result=1;
1098

1099 1100
      //printf("scope(%s) is base class of newScope(%s)\n",
      //    scope->name().data(),newScope->name().data());
1101
    }
1102
    else
1103 1104
    {
      int i=-1;
1105 1106
      if (newScope->definitionType()==Definition::TypeNamespace)
      {
1107
        g_visitedNamespaces.insert(newScope->name(),newScope);
1108 1109 1110 1111 1112
        // this part deals with the case where item is a class
        // A::B::C but is explicit referenced as A::C, where B is imported
        // in A via a using directive.
        //printf("newScope is a namespace: %s!\n",newScope->name().data());
        NamespaceDef *nscope = (NamespaceDef*)newScope;
1113
        SDict<Definition> *cl = nscope->getUsedClasses();
1114 1115
        if (cl)
        {
1116 1117
          SDict<Definition>::Iterator cli(*cl);
          Definition *cd;
1118 1119
          for (cli.toFirst();(cd=cli.current());++cli)
          {
1120
            //printf("Trying for class %s\n",cd->name().data());
1121
            if (cd==item)
1122
            {
1123
              //printf("> class is used in this scope\n");
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
              goto done;
            }
          }
        }
        NamespaceSDict *nl = nscope->getUsedNamespaces();
        if (nl)
        {
          NamespaceSDict::Iterator nli(*nl);
          NamespaceDef *nd;
          for (nli.toFirst();(nd=nli.current());++nli)
          {
1135
            if (g_visitedNamespaces.find(nd->name())==0)
1136
            {
1137
              //printf("Trying for namespace %s\n",nd->name().data());
1138
              i = isAccessibleFromWithExpScope(scope,fileScope,item,nd->name());
1139 1140 1141 1142 1143
              if (i!=-1)
              {
                //printf("> found via explicit scope of used namespace\n");
                goto done;
              }
1144 1145 1146 1147 1148
            }
          }
        }
      }
      // repeat for the parent scope
1149
      if (scope!=Doxygen::globalScope)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1150
      {
1151
        i = isAccessibleFromWithExpScope(scope->getOuterScope(),fileScope,
1152
            item,explicitScopePart);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1153
      }
1154
      //printf("  | result=%d\n",i);
1155
      result = (i==-1) ? -1 : i+2;
1156 1157 1158 1159
    }
  }
  else // failed to resolve explicitScope
  {
1160
    //printf("    failed to resolve: scope=%s\n",scope->name().data());
1161 1162 1163 1164
    if (scope->definitionType()==Definition::TypeNamespace)
    {
      NamespaceDef *nscope = (NamespaceDef*)scope;
      NamespaceSDict *nl = nscope->getUsedNamespaces();
1165 1166 1167 1168 1169
      if (accessibleViaUsingNamespace(nl,fileScope,item,explicitScopePart)) 
      {
        //printf("> found in used namespace\n");
        goto done;
      }
1170 1171 1172 1173
    }
    if (scope==Doxygen::globalScope)
    {
      if (fileScope)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1174
      {
1175
        NamespaceSDict *nl = fileScope->getUsedNamespaces();
1176 1177 1178 1179 1180
        if (accessibleViaUsingNamespace(nl,fileScope,item,explicitScopePart)) 
        {
          //printf("> found in used namespace\n");
          goto done;
        }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1181
      }
1182 1183
      //printf("> not found\n");
      result=-1;
1184 1185 1186
    }
    else // continue by looking into the parent scope
    {
1187
      int i=isAccessibleFromWithExpScope(scope->getOuterScope(),fileScope,
1188
          item,explicitScopePart);
1189
      //printf("> result=%d\n",i);
1190
      result= (i==-1) ? -1 : i+2;
1191 1192
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1193

1194
done:
1195
  //printf("  > result=%d\n",result);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1196
  accessStack.pop();
1197
  //Doxygen::lookupCache.insert(key,new int(result));
1198
  return result;
1199 1200
}

1201
int computeQualifiedIndex(const QCString &name)
1202 1203 1204 1205 1206
{
  int i = name.find('<');
  return name.findRev("::",i==-1 ? name.length() : i);
}

1207
static void getResolvedSymbol(Definition *scope,
1208 1209 1210
                       FileDef *fileScope,
                       Definition *d, 
                       const QCString &explicitScopePart,
1211
                       ArgumentList *actTemplParams,
1212 1213 1214
                       int &minDistance,
                       ClassDef *&bestMatch,
                       MemberDef *&bestTypedef,
1215 1216
                       QCString &bestTemplSpec,
                       QCString &bestResolvedType
1217 1218
                      )
{
1219
  //printf("  => found type %x name=%s d=%p\n",
1220
  //       d->definitionType(),d->name().data(),d);
1221

1222
  // only look at classes and members that are enums or typedefs
1223 1224 1225 1226 1227 1228 1229 1230 1231
  if (d->definitionType()==Definition::TypeClass ||
      (d->definitionType()==Definition::TypeMember && 
       (((MemberDef*)d)->isTypedef() || ((MemberDef*)d)->isEnumerate()) 
      )
     )
  {
    g_visitedNamespaces.clear();
    // test accessibility of definition within scope.
    int distance = isAccessibleFromWithExpScope(scope,fileScope,d,explicitScopePart);
1232
    //printf("  %s; distance %s (%p) is %d\n",scope->name().data(),d->name().data(),d,distance);
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
    if (distance!=-1) // definition is accessible
    {
      // see if we are dealing with a class or a typedef
      if (d->definitionType()==Definition::TypeClass) // d is a class
      {
        ClassDef *cd = (ClassDef *)d;
        //printf("cd=%s\n",cd->name().data());
        if (!cd->isTemplateArgument()) // skip classes that
          // are only there to 
          // represent a template 
          // argument
        {
          //printf("is not a templ arg\n");
          if (distance<minDistance) // found a definition that is "closer"
          {
            minDistance=distance;
            bestMatch = cd; 
            bestTypedef = 0;
            bestTemplSpec.resize(0);
1252
            bestResolvedType = cd->qualifiedName();
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
          }
          else if (distance==minDistance &&
              fileScope && bestMatch &&
              fileScope->getUsedNamespaces() && 
              d->getOuterScope()->definitionType()==Definition::TypeNamespace && 
              bestMatch->getOuterScope()==Doxygen::globalScope
              )
          {
            // in case the distance is equal it could be that a class X
            // is defined in a namespace and in the global scope. When searched
            // in the global scope the distance is 0 in both cases. We have
            // to choose one of the definitions: we choose the one in the
            // namespace if the fileScope imports namespaces and the definition
            // found was in a namespace while the best match so far isn't.
            // Just a non-perfect heuristic but it could help in some situations
            // (kdecore code is an example).
            minDistance=distance;
            bestMatch = cd; 
            bestTypedef = 0;
            bestTemplSpec.resize(0);
1273
            bestResolvedType = cd->qualifiedName();
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
          }
        }
        else
        {
          //printf("  is a template argument!\n");
        }
      }
      else if (d->definitionType()==Definition::TypeMember)
      {
        MemberDef *md = (MemberDef *)d;
        //printf("  member isTypedef()=%d\n",md->isTypedef());
        if (md->isTypedef()) // d is a typedef
        {
          QCString args=md->argsString();
          if (args.isEmpty()) // do not expand "typedef t a[4];"
          {
            //printf("    found typedef!\n");

            // we found a symbol at this distance, but if it didn't
            // resolve to a class, we still have to make sure that
            // something at a greater distance does not match, since
            // that symbol is hidden by this one.
            if (distance<minDistance)
            {
              QCString spec;
1299
              QCString type;
1300 1301
              minDistance=distance;
              MemberDef *enumType = 0;
1302
              ClassDef *cd = newResolveTypedef(fileScope,md,&enumType,&spec,&type,actTemplParams);
1303
              if (cd)  // type resolves to a class
1304
              {
1305
                //printf("      bestTypeDef=%p spec=%s type=%s\n",md,spec.data(),type.data());
1306 1307 1308
                bestMatch = cd;
                bestTypedef = md;
                bestTemplSpec = spec;
1309
                bestResolvedType = type;
1310
              }
1311
              else if (enumType) // type resolves to a enum
1312 1313 1314 1315 1316
              {
                //printf("      is enum\n");
                bestMatch = 0;
                bestTypedef = enumType;
                bestTemplSpec = "";
1317
                bestResolvedType = enumType->qualifiedName();
1318
              }
1319 1320 1321 1322 1323 1324 1325
              else if (md->isReference()) // external reference
              {
                bestMatch = 0;
                bestTypedef = md;
                bestTemplSpec = spec;
                bestResolvedType = type;
              }
1326 1327
              else
              {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1328 1329 1330 1331
                bestMatch = 0;
                bestTypedef = md;
                bestTemplSpec.resize(0);
                bestResolvedType.resize(0);
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
                //printf("      no match\n");
              }
            }
            else
            {
              //printf("      not the best match %d min=%d\n",distance,minDistance);
            }
          }
          else
          {
            //printf("     not a simple typedef\n")
          }
        }
        else if (md->isEnumerate())
        {
          if (distance<minDistance)
          {
            minDistance=distance;
            bestMatch = 0;
            bestTypedef = md;
            bestTemplSpec = "";
1353
            bestResolvedType = md->qualifiedName();
1354 1355 1356 1357 1358 1359 1360 1361 1362
          }
        }
      }
    } // if definition accessible
    else
    {
      //printf("  Not accessible!\n");
    }
  } // if definition is a class or member
1363
  //printf("  bestMatch=%p bestResolvedType=%s\n",bestMatch,bestResolvedType.data());
1364 1365
}

1366
/* Find the fully qualified class name referred to by the input class
1367 1368 1369 1370 1371
 * or typedef name against the input scope.
 * Loops through scope and each of its parent scopes looking for a
 * match against the input name. Can recursively call itself when 
 * resolving typedefs.
 */
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1372
static ClassDef *getResolvedClassRec(Definition *scope,
1373 1374 1375
    FileDef *fileScope,
    const char *n,
    MemberDef **pTypeDef,
1376 1377
    QCString *pTemplSpec,
    QCString *pResolvedType
1378
    )
1379 1380
{
  //printf("[getResolvedClassRec(%s,%s)\n",scope?scope->name().data():"<global>",n);
1381
  QCString name;
1382
  QCString explicitScopePart;
1383 1384 1385 1386 1387 1388 1389 1390 1391
  QCString strippedTemplateParams;
  name=stripTemplateSpecifiersFromScope
                     (removeRedundantWhiteSpace(n),TRUE,
                      &strippedTemplateParams);
  ArgumentList actTemplParams;
  if (!strippedTemplateParams.isEmpty()) // template part that was stripped
  {
    stringToArgumentList(strippedTemplateParams,&actTemplParams);
  }
1392

1393 1394
  int qualifierIndex = computeQualifiedIndex(name);
  //printf("name=%s qualifierIndex=%d\n",name.data(),qualifierIndex);
1395 1396 1397 1398 1399 1400 1401 1402
  if (qualifierIndex!=-1) // qualified name
  {
    // split off the explicit scope part
    explicitScopePart=name.left(qualifierIndex);
    // todo: improve namespace alias substitution
    replaceNamespaceAliases(explicitScopePart,explicitScopePart.length());
    name=name.mid(qualifierIndex+2);
  }
1403

1404 1405 1406 1407 1408
  if (name.isEmpty()) 
  {
    //printf("] empty name\n");
    return 0; // empty name
  }
1409

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1410
  //printf("Looking for symbol %s\n",name.data());
1411
  DefinitionIntf *di = Doxygen::symbolMap->find(name);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1412 1413
  // the -g (for C# generics) and -p (for ObjC protocols) are now already 
  // stripped from the key used in the symbolMap, so that is not needed here.
1414
  if (di==0) 
1415
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1416 1417 1418
    //di = Doxygen::symbolMap->find(name+"-g");
    //if (di==0)
    //{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1419 1420 1421 1422 1423 1424
      di = Doxygen::symbolMap->find(name+"-p");
      if (di==0)
      {
        //printf("no such symbol!\n");
        return 0;
      }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1425
    //}
1426
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1427
  //printf("found symbol!\n");
1428

1429
  bool hasUsingStatements = 
1430 1431 1432 1433 1434
    (fileScope && ((fileScope->getUsedNamespaces() && 
                    fileScope->getUsedNamespaces()->count()>0) ||
                   (fileScope->getUsedClasses() && 
                    fileScope->getUsedClasses()->count()>0)) 
    );
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1435
  //printf("hasUsingStatements=%d\n",hasUsingStatements);
1436 1437 1438 1439 1440 1441
  // Since it is often the case that the same name is searched in the same
  // scope over an over again (especially for the linked source code generation)
  // we use a cache to collect previous results. This is possible since the
  // result of a lookup is deterministic. As the key we use the concatenated
  // scope, the name to search for and the explicit scope prefix. The speedup
  // achieved by this simple cache can be enormous.
1442 1443 1444
  int scopeNameLen = scope->name().length()+1;
  int nameLen = name.length()+1;
  int explicitPartLen = explicitScopePart.length();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1445
  int fileScopeLen = hasUsingStatements ? 1+fileScope->absFilePath().length() : 0;
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456

  // below is a more efficient coding of
  // QCString key=scope->name()+"+"+name+"+"+explicitScopePart;
  QCString key(scopeNameLen+nameLen+explicitPartLen+fileScopeLen+1);
  char *p=key.data();
  qstrcpy(p,scope->name()); *(p+scopeNameLen-1)='+';
  p+=scopeNameLen;
  qstrcpy(p,name); *(p+nameLen-1)='+';
  p+=nameLen;
  qstrcpy(p,explicitScopePart);
  p+=explicitPartLen;
1457

1458 1459 1460 1461
  // if a file scope is given and it contains using statements we should
  // also use the file part in the key (as a class name can be in
  // two different namespaces and a using statement in a file can select 
  // one of them).
1462
  if (hasUsingStatements)
1463
  {
1464 1465 1466
    // below is a more efficient coding of
    // key+="+"+fileScope->name();
    *p++='+';
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1467
    qstrcpy(p,fileScope->absFilePath());
1468
    p+=fileScopeLen-1;
1469
  }
1470
  *p='\0';
1471

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1472
  LookupInfo *pval=Doxygen::lookupCache->find(key);
1473
  //printf("Searching for %s result=%p\n",key.data(),pval);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1474
  if (pval)
1475
  {
1476 1477 1478
    //printf("LookupInfo %p %p '%s' %p\n", 
    //    pval->classDef, pval->typeDef, pval->templSpec.data(), 
    //    pval->resolvedType.data()); 
1479 1480 1481
    if (pTemplSpec)    *pTemplSpec=pval->templSpec;
    if (pTypeDef)      *pTypeDef=pval->typeDef;
    if (pResolvedType) *pResolvedType=pval->resolvedType;
1482 1483
    //printf("] cachedMatch=%s\n",
    //    pval->classDef?pval->classDef->name().data():"<none>");
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1484 1485
    //if (pTemplSpec) 
    //  printf("templSpec=%s\n",pTemplSpec->data());
1486
    return pval->classDef; 
1487 1488
  }
  else // not found yet; we already add a 0 to avoid the possibility of 
1489
    // endless recursion.
1490
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1491
    Doxygen::lookupCache->insert(key,new LookupInfo);
1492 1493 1494
  }

  ClassDef *bestMatch=0;
1495
  MemberDef *bestTypedef=0;
1496
  QCString bestTemplSpec;
1497
  QCString bestResolvedType;
1498
  int minDistance=10000; // init at "infinite"
1499

1500
  if (di->definitionType()==DefinitionIntf::TypeSymbolList) // not a unique name
1501
  {
1502
    //printf("  name is not unique\n");
1503 1504 1505 1506
    DefinitionListIterator dli(*(DefinitionList*)di);
    Definition *d;
    int count=0;
    for (dli.toFirst();(d=dli.current());++dli,++count) // foreach definition
1507
    {
1508
      getResolvedSymbol(scope,fileScope,d,explicitScopePart,&actTemplParams,
1509 1510
                        minDistance,bestMatch,bestTypedef,bestTemplSpec,
                        bestResolvedType);
1511 1512
    }
  }
1513
  else // unique name
1514
  {
1515
    //printf("  name is unique\n");
1516
    Definition *d = (Definition *)di;
1517
    getResolvedSymbol(scope,fileScope,d,explicitScopePart,&actTemplParams,
1518 1519
                      minDistance,bestMatch,bestTypedef,bestTemplSpec,
                      bestResolvedType);
1520
  }
1521

1522
  if (pTypeDef) 
1523
  {
1524
    *pTypeDef = bestTypedef;
1525 1526 1527 1528 1529
  }
  if (pTemplSpec)
  {
    *pTemplSpec = bestTemplSpec;
  }
1530 1531 1532 1533 1534 1535
  if (pResolvedType)
  {
    *pResolvedType = bestResolvedType;
  }
  //printf("getResolvedClassRec: bestMatch=%p pval->resolvedType=%s\n",
  //    bestMatch,bestResolvedType.data());
1536

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1537
  pval=Doxygen::lookupCache->find(key);
1538 1539
  if (pval)
  {
1540 1541 1542 1543
    pval->classDef     = bestMatch;
    pval->typeDef      = bestTypedef;
    pval->templSpec    = bestTemplSpec;
    pval->resolvedType = bestResolvedType;
1544 1545 1546
  }
  else
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1547
    Doxygen::lookupCache->insert(key,new LookupInfo(bestMatch,bestTypedef,bestTemplSpec,bestResolvedType));
1548
  }
1549 1550
  //printf("] bestMatch=%s distance=%d\n",
  //    bestMatch?bestMatch->name().data():"<none>",minDistance);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1551 1552
  //if (pTemplSpec) 
  //  printf("templSpec=%s\n",pTemplSpec->data());
1553
  return bestMatch;
1554 1555
}

1556
/* Find the fully qualified class name referred to by the input class
1557 1558 1559 1560 1561
 * or typedef name against the input scope.
 * Loops through scope and each of its parent scopes looking for a
 * match against the input name. 
 */
ClassDef *getResolvedClass(Definition *scope,
1562 1563 1564 1565 1566
    FileDef *fileScope,
    const char *n,
    MemberDef **pTypeDef,
    QCString *pTemplSpec,
    bool mayBeUnlinkable,
1567 1568
    bool mayBeHidden,
    QCString *pResolvedType
1569
    )
1570
{
1571
  static bool optimizeOutputVhdl = Config_getBool("OPTIMIZE_OUTPUT_VHDL");
1572 1573 1574 1575
  g_resolvedTypedefs.clear();
  if (scope==0 ||
      (scope->definitionType()!=Definition::TypeClass && 
       scope->definitionType()!=Definition::TypeNamespace
1576
      ) ||
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1577
      (scope->getLanguage()==SrcLangExt_Java && QCString(n).find("::")!=-1)
1578 1579 1580 1581
     )
  {
    scope=Doxygen::globalScope;
  }
1582
  //printf("------------ getResolvedClass(scope=%s,file=%s,name=%s,mayUnlinkable=%d)\n",
1583 1584 1585 1586 1587
  //    scope?scope->name().data():"<global>",
  //    fileScope?fileScope->name().data():"<none>",
  //    n,
  //    mayBeUnlinkable
  //   );
1588 1589 1590 1591 1592 1593 1594 1595 1596
  ClassDef *result;
  if (optimizeOutputVhdl)
  {
    result = getClass(n);
  }
  else
  {
    result = getResolvedClassRec(scope,fileScope,n,pTypeDef,pTemplSpec,pResolvedType);
  }
1597 1598 1599 1600 1601 1602
  if (result==0) // for nested classes imported via tag files, the scope may not
                 // present, so we check the class name directly as well.
                 // See also bug701314
  {
    result = getClass(n);
  }
1603 1604
  if (!mayBeUnlinkable && result && !result->isLinkable()) 
  {
1605 1606
    if (!mayBeHidden || !result->isHidden())
    {
1607
      //printf("result was %s\n",result?result->name().data():"<none>");
1608
      result=0; // don't link to artificial/hidden classes unless explicitly allowed
1609
    }
1610
  }
1611 1612 1613
  //printf("getResolvedClass(%s,%s)=%s\n",scope?scope->name().data():"<global>",
  //                                  n,result?result->name().data():"<none>");
  return result;
1614 1615
}

1616 1617 1618 1619 1620
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------

1621 1622 1623 1624 1625
static bool findOperator(const QCString &s,int i)
{
  int b = s.findRev("operator",i);
  if (b==-1) return FALSE; // not found
  b+=8;
1626
  while (b<i) // check if there are only spaces in between 
1627
    // the operator and the >
1628
  {
1629
    if (!isspace((uchar)s.at(b))) return FALSE;
1630 1631 1632 1633 1634
    b++;
  }
  return TRUE;
}

1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
static bool findOperator2(const QCString &s,int i)
{
  int b = s.findRev("operator",i);
  if (b==-1) return FALSE; // not found
  b+=8;
  while (b<i) // check if there are only non-ascii
              // characters in front of the operator
  {
    if (isId((uchar)s.at(b))) return FALSE;
    b++;
  }
  return TRUE;
}

1649
static const char constScope[]   = { 'c', 'o', 'n', 's', 't', ':' };
1650
static const char virtualScope[] = { 'v', 'i', 'r', 't', 'u', 'a', 'l', ':' };
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1651

1652
// Note: this function is not reentrant due to the use of static buffer!
1653
QCString removeRedundantWhiteSpace(const QCString &s)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1654
{
1655
  static bool cliSupport = Config_getBool("CPP_CLI_SUPPORT");
1656 1657 1658
  static bool vhdl = Config_getBool("OPTIMIZE_OUTPUT_VHDL");
   
  if (s.isEmpty() || vhdl) return s;
1659
  static GrowBuf growBuf;
1660 1661 1662
  //int resultLen = 1024;
  //int resultPos = 0;
  //QCString result(resultLen);
1663
  // we use growBuf.addChar(c) instead of result+=c to 
1664
  // improve the performance of this function
1665
  growBuf.clear();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1666
  uint i;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1667
  uint l=s.length();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1668
  uint csp=0;
1669
  uint vsp=0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1670
  for (i=0;i<l;i++)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1671
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1672
nextChar:
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1673
    char c=s.at(i);
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696

    // search for "const"
    if (csp<6 && c==constScope[csp] && // character matches substring "const"
         (csp>0 ||                     // if it is the first character 
          i==0  ||                     // the previous may not be a digit
          !isId(s.at(i-1))
         )
       )
      csp++; 
    else // reset counter
      csp=0;

    // search for "virtual"
    if (vsp<8 && c==virtualScope[vsp] && // character matches substring "virtual"
         (vsp>0 ||                       // if it is the first character
          i==0  ||                       // the previous may not be a digit 
          !isId(s.at(i-1))
         )
       )
      vsp++;
    else // reset counter
      vsp=0;

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1697 1698 1699
    if (c=='"') // quoted string
    {
      i++;
1700
      growBuf.addChar(c);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1701 1702 1703
      while (i<l)
      {
        char cc=s.at(i);
1704
        growBuf.addChar(cc);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1705
        if (cc=='\\') // escaped character
1706
        { 
1707
          growBuf.addChar(s.at(i+1));
1708 1709
          i+=2; 
        }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1710 1711 1712 1713 1714 1715 1716
        else if (cc=='"') // end of string
        { i++; goto nextChar; }
        else // any other character
        { i++; }
      }
    }
    else if (i<l-2 && c=='<' &&  // current char is a <
1717
        (isId(s.at(i+1)) || isspace((uchar)s.at(i+1))) && // next char is an id char or space
1718
        (i<8 || !findOperator(s,i)) // string in front is not "operator"
1719
        )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1720
    {
1721 1722
      growBuf.addChar('<');
      growBuf.addChar(' ');
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1723
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1724
    else if (i>0 && c=='>' && // current char is a >
1725 1726 1727
        (isId(s.at(i-1)) || isspace((uchar)s.at(i-1)) || s.at(i-1)=='*' || s.at(i-1)=='&') && // prev char is an id char or space
        (i<8 || !findOperator(s,i)) // string in front is not "operator"
        )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1728
    {
1729 1730
      growBuf.addChar(' ');
      growBuf.addChar('>');
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1731
    }
1732
    else if (i>0 && c==',' && !isspace((uchar)s.at(i-1))
1733
        && ((i<l-1 && (isId(s.at(i+1)) || s.at(i+1)=='[')) // the [ is for attributes (see bug702170)
1734 1735
          || (i<l-2 && s.at(i+1)=='$' && isId(s.at(i+2)))  // for PHP
          || (i<l-3 && s.at(i+1)=='&' && s.at(i+2)=='$' && isId(s.at(i+3)))))  // for PHP
1736
    {
1737 1738
      growBuf.addChar(',');
      growBuf.addChar(' ');
1739
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1740
    else if (i>0 && 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1741 1742 1743
         ((isId(s.at(i)) && s.at(i-1)==')') || 
          (s.at(i)=='\''  && s.at(i-1)==' ')
         )
1744
        )
1745
    {
1746 1747
      growBuf.addChar(' ');
      growBuf.addChar(s.at(i));
1748
    }
1749 1750 1751 1752 1753 1754 1755
    else if (c=='t' && csp==5 /*&& (i<5 || !isId(s.at(i-5)))*/ &&
             !(isId(s.at(i+1)) /*|| s.at(i+1)==' '*/ || 
               s.at(i+1)==')' || 
               s.at(i+1)==',' || 
               s.at(i+1)=='\0'
              )
            ) 
1756
      // prevent const ::A from being converted to const::A
1757
    {
1758 1759
      growBuf.addChar('t');
      growBuf.addChar(' ');
1760
      if (s.at(i+1)==' ') i++;
1761 1762
      csp=0;
    }
1763 1764
    else if (c==':' && csp==6 /*&& (i<6 || !isId(s.at(i-6)))*/) 
      // replace const::A by const ::A
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1765
    {
1766 1767
      growBuf.addChar(' ');
      growBuf.addChar(':');
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1768 1769
      csp=0;
    }
1770 1771 1772 1773 1774 1775 1776
    else if (c=='l' && vsp==7 /*&& (i<7 || !isId(s.at(i-7)))*/ &&
             !(isId(s.at(i+1)) /*|| s.at(i+1)==' '*/ || 
               s.at(i+1)==')' || 
               s.at(i+1)==',' || 
               s.at(i+1)=='\0'
              )
            ) 
1777
      // prevent virtual ::A from being converted to virtual::A
1778
    {
1779 1780
      growBuf.addChar('l');
      growBuf.addChar(' ');
1781 1782 1783
      if (s.at(i+1)==' ') i++;
      vsp=0;
    }
1784 1785
    else if (c==':' && vsp==8 /*&& (i<8 || !isId(s.at(i-8)))*/) 
      // replace virtual::A by virtual ::A
1786
    {
1787 1788
      growBuf.addChar(' ');
      growBuf.addChar(':');
1789 1790
      vsp=0;
    }
1791
    else if (!isspace((uchar)c) || // not a space
1792 1793 1794 1795 1796 1797 1798
          ( i>0 && i<l-1 &&          // internal character
            (isId(s.at(i-1)) || s.at(i-1)==')' || s.at(i-1)==',' || s.at(i-1)=='>' || s.at(i-1)==']') && 
            (isId(s.at(i+1)) || 
             (i<l-2 && s.at(i+1)=='$' && isId(s.at(i+2))) || 
             (i<l-3 && s.at(i+1)=='&' && s.at(i+2)=='$' && isId(s.at(i+3)))
            )
          ) 
1799
        )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1800
    {
1801
      if (c=='*' || c=='&' || c=='@' || c=='$')
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1802
      {  
1803
        //uint rl=result.length();
1804 1805
        uint rl=growBuf.getPos();
        if ((rl>0 && (isId(growBuf.at(rl-1)) || growBuf.at(rl-1)=='>')) &&
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1806
            ((c!='*' && c!='&') || !findOperator2(s,i)) // avoid splitting operator* and operator->* and operator&
1807 1808
           ) 
        {
1809
          growBuf.addChar(' ');
1810
        }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1811
      }
1812 1813 1814 1815 1816 1817 1818 1819
      else if (c=='-')
      {
        uint rl=growBuf.getPos();
        if (rl>0 && growBuf.at(rl-1)==')' && i<l-1 && s.at(i+1)=='>') // trailing return type ')->' => ') ->'
        {
          growBuf.addChar(' ');
        }
      }
1820
      growBuf.addChar(c);
1821 1822 1823 1824
      if (cliSupport &&
          (c=='^' || c=='%') && i>1 && isId(s.at(i-1)) &&
          !findOperator(s,i)
         ) 
1825
      {
1826
        growBuf.addChar(' '); // C++/CLI: Type^ name and Type% name
1827
      }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1828 1829
    }
  }
1830
  //printf("removeRedundantWhiteSpace(`%s')=`%s'\n",s.data(),result.data());
1831
  growBuf.addChar(0);
1832
  //result.resize(resultPos);
1833
  return growBuf.get();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1834 1835
}  

1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
/**
 * Returns the position in the string where a function parameter list
 * begins, or -1 if one is not found.
 */
int findParameterList(const QString &name)
{
  int pos=-1;
  int templateDepth=0;
  do
  {
    if (templateDepth > 0)
    {
      int nextOpenPos=name.findRev('>', pos);
      int nextClosePos=name.findRev('<', pos);
      if (nextOpenPos!=-1 && nextOpenPos>nextClosePos)
      {
        ++templateDepth;
        pos=nextOpenPos-1;
      }
1855
      else if (nextClosePos!=-1)
1856 1857 1858 1859
      {
        --templateDepth;
        pos=nextClosePos-1;
      }
1860 1861 1862 1863
      else // more >'s than <'s, see bug701295
      {
        return -1;
      }
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
    }
    else
    {
      int lastAnglePos=name.findRev('>', pos);
      int bracePos=name.findRev('(', pos);
      if (lastAnglePos!=-1 && lastAnglePos>bracePos)
      {
        ++templateDepth;
        pos=lastAnglePos-1;
      }
      else
      {
1876 1877
        int bp = bracePos>0 ? name.findRev('(',bracePos-1) : -1;
        return bp==-1 ? bracePos : bp;
1878 1879 1880 1881 1882 1883
      }
    }
  } while (pos!=-1);
  return -1;
}

1884
bool rightScopeMatch(const QCString &scope, const QCString &name)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1885
{
1886 1887
  int sl=scope.length();
  int nl=name.length();
1888
  return (name==scope || // equal 
1889 1890 1891 1892
          (scope.right(nl)==name && // substring 
           sl-nl>1 && scope.at(sl-nl-1)==':' && scope.at(sl-nl-2)==':' // scope
          ) 
         );
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1893 1894
}

1895
bool leftScopeMatch(const QCString &scope, const QCString &name)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1896
{
1897 1898
  int sl=scope.length();
  int nl=name.length();
1899
  return (name==scope || // equal 
1900 1901 1902 1903
          (scope.left(nl)==name && // substring 
           sl>nl+1 && scope.at(nl)==':' && scope.at(nl+1)==':' // scope
          ) 
         );
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1904 1905
}

1906

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1907
void linkifyText(const TextGeneratorIntf &out,Definition *scope,
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1908
    FileDef *fileScope,Definition *self,
1909
    const char *text, bool autoBreak,bool external,
1910
    bool keepSpaces,int indentLevel)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1911
{
1912
  //printf("linkify=`%s'\n",text);
1913
  static QRegExp regExp("[a-z_A-Z\\x80-\\xFF][~!a-z_A-Z0-9$\\\\.:\\x80-\\xFF]*");
1914
  static QRegExp regExpSplit("(?!:),");
1915
  QCString txtStr=text;
1916
  int strLen = txtStr.length();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1917
  //printf("linkifyText scope=%s fileScope=%s strtxt=%s strlen=%d external=%d\n",
1918 1919
  //    scope?scope->name().data():"<none>",
  //    fileScope?fileScope->name().data():"<none>",
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1920
  //    txtStr.data(),strLen,external);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1921 1922 1923 1924
  int matchLen;
  int index=0;
  int newIndex;
  int skipIndex=0;
1925
  int floatingIndex=0;
1926
  if (strLen==0) return;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1927
  // read a word from the text string
1928
  while ((newIndex=regExp.match(txtStr,index,&matchLen))!=-1 && 
1929 1930
      (newIndex==0 || !(txtStr.at(newIndex-1)>='0' && txtStr.at(newIndex-1)<='9')) // avoid matching part of hex numbers
      )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1931 1932
  {
    // add non-word part to the result
1933
    floatingIndex+=newIndex-skipIndex+matchLen;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1934 1935 1936 1937 1938 1939
    bool insideString=FALSE; 
    int i;
    for (i=index;i<newIndex;i++) 
    { 
      if (txtStr.at(i)=='"') insideString=!insideString; 
    }
1940

1941
    //printf("floatingIndex=%d strlen=%d autoBreak=%d\n",floatingIndex,strLen,autoBreak);
1942
    if (strLen>35 && floatingIndex>30 && autoBreak) // try to insert a split point
1943 1944 1945
    {
      QCString splitText = txtStr.mid(skipIndex,newIndex-skipIndex);
      int splitLength = splitText.length();
1946
      int offset=1;
1947
      i=splitText.find(regExpSplit,0);
1948 1949
      if (i==-1) { i=splitText.find('<'); if (i!=-1) offset=0; }
      if (i==-1) i=splitText.find('>');
1950
      if (i==-1) i=splitText.find(' ');
1951
      //printf("splitText=[%s] len=%d i=%d offset=%d\n",splitText.data(),splitLength,i,offset);
1952 1953
      if (i!=-1) // add a link-break at i in case of Html output
      {
1954
        out.writeString(splitText.left(i+offset),keepSpaces);
1955
        out.writeBreak(indentLevel==0 ? 0 : indentLevel+1);
1956 1957
        out.writeString(splitText.right(splitLength-i-offset),keepSpaces);
        floatingIndex=splitLength-i-offset+matchLen;
1958
      } 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1959 1960
      else
      {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1961
        out.writeString(splitText,keepSpaces); 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1962
      }
1963 1964 1965
    }
    else
    {
1966
      //ol.docify(txtStr.mid(skipIndex,newIndex-skipIndex)); 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1967
      out.writeString(txtStr.mid(skipIndex,newIndex-skipIndex),keepSpaces); 
1968
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1969
    // get word from string
1970
    QCString word=txtStr.mid(newIndex,matchLen);
1971
    QCString matchWord = substitute(substitute(word,"\\","::"),".","::");
1972 1973
    //printf("linkifyText word=%s matchWord=%s scope=%s\n",
    //    word.data(),matchWord.data(),scope?scope->name().data():"<none>");
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1974 1975
    bool found=FALSE;
    if (!insideString)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1976
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1977 1978 1979 1980 1981
      ClassDef     *cd=0;
      FileDef      *fd=0;
      MemberDef    *md=0;
      NamespaceDef *nd=0;
      GroupDef     *gd=0;
1982
      //printf("** Match word '%s'\n",matchWord.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1983

1984
      MemberDef *typeDef=0;
1985 1986
      cd=getResolvedClass(scope,fileScope,matchWord,&typeDef);
      if (typeDef) // First look at typedef then class, see bug 584184.
1987
      {
1988
        //printf("Found typedef %s\n",typeDef->name().data());
1989
        if (external ? typeDef->isLinkable() : typeDef->isLinkableInProject())
1990
        {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1991 1992 1993 1994 1995 1996 1997 1998
          if (typeDef->getOuterScope()!=self)
          {
            out.writeLink(typeDef->getReference(),
                typeDef->getOutputFileBase(),
                typeDef->anchor(),
                word);
            found=TRUE;
          }
1999
        }
2000
      }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2001
      if (!found && (cd || (cd=getClass(matchWord)))) 
2002 2003 2004 2005 2006
      {
        //printf("Found class %s\n",cd->name().data());
        // add link to the result
        if (external ? cd->isLinkable() : cd->isLinkableInProject())
        {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2007 2008 2009 2010 2011
          if (cd!=self)
          {
            out.writeLink(cd->getReference(),cd->getOutputFileBase(),cd->anchor(),word);
            found=TRUE;
          }
2012 2013
        }
      }
2014
      else if ((cd=getClass(matchWord+"-p"))) // search for Obj-C protocols as well
2015 2016 2017 2018
      {
        // add link to the result
        if (external ? cd->isLinkable() : cd->isLinkableInProject())
        {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2019 2020 2021 2022 2023
          if (cd!=self)
          {
            out.writeLink(cd->getReference(),cd->getOutputFileBase(),cd->anchor(),word);
            found=TRUE;
          }
2024 2025
        }
      }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
//      else if ((cd=getClass(matchWord+"-g"))) // C# generic as well
//      {
//        // add link to the result
//        if (external ? cd->isLinkable() : cd->isLinkableInProject())
//        {
//          if (cd!=self)
//          {
//            out.writeLink(cd->getReference(),cd->getOutputFileBase(),cd->anchor(),word);
//            found=TRUE;
//          }
//        }
//      }
2038 2039 2040 2041
      else
      {
        //printf("   -> nothing\n");
      }
2042

2043
      int m = matchWord.findRev("::");
2044
      QCString scopeName;
2045
      if (scope && 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2046 2047 2048
          (scope->definitionType()==Definition::TypeClass || 
           scope->definitionType()==Definition::TypeNamespace
          ) 
2049 2050 2051 2052
         )
      {
        scopeName=scope->name();
      }
2053 2054 2055 2056 2057 2058
      else if (m!=-1)
      {
        scopeName = matchWord.left(m);
        matchWord = matchWord.mid(m+2);
      }

2059 2060
      //printf("ScopeName=%s\n",scopeName.data());
      //if (!found) printf("Trying to link %s in %s\n",word.data(),scopeName.data()); 
2061
      if (!found && 
2062
          getDefs(scopeName,matchWord,0,md,cd,fd,nd,gd) && 
2063 2064 2065
          //(md->isTypedef() || md->isEnumerate() || 
          // md->isReference() || md->isVariable()
          //) && 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2066
          (external ? md->isLinkable() : md->isLinkableInProject()) 
2067
         )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2068
      {
2069
        //printf("Found ref scope=%s\n",d?d->name().data():"<global>");
2070 2071
        //ol.writeObjectLink(d->getReference(),d->getOutputFileBase(),
        //                       md->anchor(),word);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2072 2073 2074 2075 2076 2077 2078 2079
        if (md!=self && (self==0 || md->name()!=self->name())) 
          // name check is needed for overloaded members, where getDefs just returns one
        {
          out.writeLink(md->getReference(),md->getOutputFileBase(),
              md->anchor(),word);
          //printf("found symbol %s\n",matchWord.data());
          found=TRUE;
        }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2080 2081
      }
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2082 2083

    if (!found) // add word to the result
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2084
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2085
      out.writeString(word,keepSpaces);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2086 2087
    }
    // set next start point in the string
2088
    //printf("index=%d/%d\n",index,txtStr.length());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2089 2090 2091
    skipIndex=index=newIndex+matchLen;
  }
  // add last part of the string to the result.
2092
  //ol.docify(txtStr.right(txtStr.length()-skipIndex));
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2093
  out.writeString(txtStr.right(txtStr.length()-skipIndex),keepSpaces);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2094 2095 2096
}


Dimitri van Heesch's avatar
Dimitri van Heesch committed
2097
void writeExample(OutputList &ol,ExampleSDict *ed)
2098
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2099
  QCString exampleLine=theTranslator->trWriteList(ed->count());
2100

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2101 2102 2103
  //bool latexEnabled = ol.isEnabled(OutputGenerator::Latex);
  //bool manEnabled   = ol.isEnabled(OutputGenerator::Man);
  //bool htmlEnabled  = ol.isEnabled(OutputGenerator::Html);
2104 2105 2106 2107 2108 2109
  QRegExp marker("@[0-9]+");
  int index=0,newIndex,matchLen;
  // now replace all markers in inheritLine with links to the classes
  while ((newIndex=marker.match(exampleLine,index,&matchLen))!=-1)
  {
    bool ok;
2110
    ol.parseText(exampleLine.mid(index,newIndex-index));
2111
    uint entryIndex = exampleLine.mid(newIndex+1,matchLen-1).toUInt(&ok);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2112
    Example *e=ed->at(entryIndex);
2113 2114
    if (ok && e) 
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2115 2116 2117 2118
      ol.pushGeneratorState();
      //if (latexEnabled) ol.disable(OutputGenerator::Latex);
      ol.disable(OutputGenerator::Latex);
      ol.disable(OutputGenerator::RTF);
2119
      // link for Html / man
2120
      //printf("writeObjectLink(file=%s)\n",e->file.data());
2121
      ol.writeObjectLink(0,e->file,e->anchor,e->name);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2122
      ol.popGeneratorState();
2123

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2124 2125 2126 2127
      ol.pushGeneratorState();
      //if (latexEnabled) ol.enable(OutputGenerator::Latex);
      ol.disable(OutputGenerator::Man);
      ol.disable(OutputGenerator::Html);
2128 2129 2130
      // link for Latex / pdf with anchor because the sources
      // are not hyperlinked (not possible with a verbatim environment).
      ol.writeObjectLink(0,e->file,0,e->name);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2131 2132 2133
      //if (manEnabled) ol.enable(OutputGenerator::Man);
      //if (htmlEnabled) ol.enable(OutputGenerator::Html);
      ol.popGeneratorState();
2134
    }
2135 2136
    index=newIndex+matchLen;
  } 
2137
  ol.parseText(exampleLine.right(exampleLine.length()-index));
2138 2139 2140 2141
  ol.writeString(".");
}


2142
QCString argListToString(ArgumentList *al,bool useCanonicalType,bool showDefVals)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2143
{
2144
  QCString result;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2145
  if (al==0) return result;
2146 2147
  ArgumentListIterator ali(*al);
  Argument *a=ali.current();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2148 2149 2150
  result+="(";
  while (a)
  {
2151
    QCString type1 = useCanonicalType && !a->canType.isEmpty() ?
2152
      a->canType : a->type;
2153
    QCString type2;
2154 2155 2156 2157 2158 2159
    int i=type1.find(")("); // hack to deal with function pointers
    if (i!=-1)
    {
      type2=type1.mid(i);
      type1=type1.left(i);
    }
2160 2161 2162 2163
    if (!a->attrib.isEmpty())
    {
      result+=a->attrib+" ";
    }
2164 2165
    if (!a->name.isEmpty() || !a->array.isEmpty())
    {
2166
      result+= type1+" "+a->name+type2+a->array;
2167 2168 2169
    }
    else
    {
2170
      result+= type1+type2;
2171
    }
2172
    if (!a->defval.isEmpty() && showDefVals)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2173 2174 2175
    {
      result+="="+a->defval;
    }
2176 2177 2178
    ++ali;
    a = ali.current();
    if (a) result+=", ";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2179 2180 2181 2182
  }
  result+=")";
  if (al->constSpecifier) result+=" const";
  if (al->volatileSpecifier) result+=" volatile";
2183 2184
  if (!al->trailingReturnType.isEmpty()) result+=" -> "+al->trailingReturnType;
  if (al->pureSpecifier) result+=" =0";
2185
  return removeRedundantWhiteSpace(result);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2186 2187
}

2188
QCString tempArgListToString(ArgumentList *al)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2189
{
2190
  QCString result;
2191
  if (al==0) return result;
2192
  result="<";
2193 2194
  ArgumentListIterator ali(*al);
  Argument *a=ali.current();
2195
  while (a)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2196
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2197
    if (!a->name.isEmpty()) // add template argument name
2198
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2199 2200 2201 2202 2203 2204 2205 2206
      if (a->type.left(4)=="out") // C# covariance
      {
        result+="out ";
      }
      else if (a->type.left(3)=="in") // C# contravariance
      {
        result+="in ";
      }
2207 2208 2209 2210 2211 2212 2213 2214 2215 2216
      result+=a->name;
    }
    else // extract name from type
    {
      int i=a->type.length()-1;
      while (i>=0 && isId(a->type.at(i))) i--;
      if (i>0)
      {
        result+=a->type.right(a->type.length()-i-1);
      }
2217 2218 2219 2220
      else // nothing found -> take whole name
      {
        result+=a->type;
      }
2221
    }
2222 2223
    ++ali;
    a=ali.current();
2224
    if (a) result+=", ";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2225
  }
2226
  result+=">";
2227
  return removeRedundantWhiteSpace(result);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2228 2229 2230 2231
}


// compute the HTML anchors for a list of members
2232
void setAnchors(MemberList *ml)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2233
{
2234
  //int count=0;
2235
  if (ml==0) return;
2236 2237 2238
  MemberListIterator mli(*ml);
  MemberDef *md;
  for (;(md=mli.current());++mli)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2239
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2240 2241
    if (!md->isReference())
    {
2242 2243 2244 2245 2246 2247 2248
      //QCString anchor;
      //if (groupId==-1)
      //  anchor.sprintf("%c%d",id,count++);
      //else
      //  anchor.sprintf("%c%d_%d",id,groupId,count++);
      //if (cd) anchor.prepend(escapeCharsInString(cd->name(),FALSE));
      md->setAnchor();
2249 2250
      //printf("setAnchors(): Member %s outputFileBase=%s anchor %s result %s\n",
      //    md->name().data(),md->getOutputFileBase().data(),anchor.data(),md->anchor().data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2251
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2252 2253 2254 2255 2256
  }
}

//----------------------------------------------------------------------------

2257
/*! takes the \a buf of the given length \a len and converts CR LF (DOS)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2258 2259 2260 2261
 * or CR (MAC) line ending to LF (Unix).  Returns the length of the
 * converted content (i.e. the same as \a len (Unix, MAC) or
 * smaller (DOS).
 */
2262 2263
int filterCRLF(char *buf,int len)
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2264 2265 2266 2267 2268
  int src = 0;    // source index
  int dest = 0;   // destination index
  char c;         // current character

  while (src<len)
2269
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2270 2271
    c = buf[src++];            // Remember the processed character.
    if (c == '\r')             // CR to be solved (MAC, DOS)
2272
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2273 2274 2275
      c = '\n';                // each CR to LF
      if (src<len && buf[src] == '\n')
        ++src;                 // skip LF just after CR (DOS) 
2276
    }
2277 2278 2279 2280
    else if ( c == '\0' && src<len-1) // filter out internal \0 characters, as it will confuse the parser
    {
      c = ' ';                 // turn into a space
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2281
    buf[dest++] = c;           // copy the (modified) character to dest
2282
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2283
  return dest;                 // length of the valid part of the buf
2284 2285
}

2286
static QCString getFilterFromList(const char *name,const QStrList &filterList,bool &found)
2287
{
2288
  found=FALSE;
2289 2290 2291
  // compare the file name to the filter pattern list
  QStrListIterator sli(filterList);
  char* filterStr;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2292
  for (sli.toFirst(); (filterStr = sli.current()); ++sli)
2293 2294 2295 2296 2297 2298
  {
    QCString fs = filterStr;
    int i_equals=fs.find('=');
    if (i_equals!=-1)
    {
      QCString filterPattern = fs.left(i_equals);
2299
      QRegExp fpat(filterPattern,portable_fileSystemIsCaseSensitive(),TRUE); 
2300 2301 2302 2303
      if (fpat.match(name)!=-1) 
      {
        // found a match!
        QCString filterName = fs.mid(i_equals+1);
2304 2305 2306 2307
        if (filterName.find(' ')!=-1)
        { // add quotes if the name has spaces
          filterName="\""+filterName+"\"";
        }
2308
        found=TRUE;
2309 2310 2311 2312 2313 2314 2315 2316 2317
        return filterName;
      }
    }
  }

  // no match
  return "";
}

2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
/*! looks for a filter for the file \a name.  Returns the name of the filter
 *  if there is a match for the file name, otherwise an empty string.
 *  In case \a inSourceCode is TRUE then first the source filter list is
 *  considered.
 */
QCString getFileFilter(const char* name,bool isSourceCode)
{
  // sanity check
  if (name==0) return "";

  QStrList& filterSrcList = Config_getList("FILTER_SOURCE_PATTERNS");
  QStrList& filterList    = Config_getList("FILTER_PATTERNS");

  QCString filterName;
  bool found=FALSE;
  if (isSourceCode && !filterSrcList.isEmpty())
  { // first look for source filter pattern list
    filterName = getFilterFromList(name,filterSrcList,found);
  }
2337
  if (!found && filterName.isEmpty())
2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
  { // then look for filter pattern list
    filterName = getFilterFromList(name,filterList,found);
  }
  if (!found)
  { // then use the generic input filter
    return Config_getString("INPUT_FILTER");
  }
  else
  {
    return filterName;
  }
}

2351 2352 2353

QCString transcodeCharacterStringToUTF8(const QCString &input)
{
2354
  bool error=FALSE;
2355 2356 2357 2358 2359 2360 2361 2362 2363
  static QCString inputEncoding = Config_getString("INPUT_ENCODING");
  const char *outputEncoding = "UTF-8";
  if (inputEncoding.isEmpty() || qstricmp(inputEncoding,outputEncoding)==0) return input;
  int inputSize=input.length();
  int outputSize=inputSize*4+1;
  QCString output(outputSize);
  void *cd = portable_iconv_open(outputEncoding,inputEncoding);
  if (cd==(void *)(-1)) 
  {
2364
    err("unsupported character conversion: '%s'->'%s'\n",
2365
        inputEncoding.data(),outputEncoding);
2366
    error=TRUE;
2367
  }
2368
  if (!error)
2369
  {
2370 2371
    size_t iLeft=inputSize;
    size_t oLeft=outputSize;
2372
    char *inputPtr = input.data();
2373 2374 2375
    char *outputPtr = output.data();
    if (!portable_iconv(cd, &inputPtr, &iLeft, &outputPtr, &oLeft))
    {
2376
      outputSize-=(int)oLeft;
2377 2378 2379 2380 2381 2382
      output.resize(outputSize+1);
      output.at(outputSize)='\0';
      //printf("iconv: input size=%d output size=%d\n[%s]\n",size,newSize,srcBuf.data());
    }
    else
    {
2383
      err("failed to translate characters from %s to %s: check INPUT_ENCODING\ninput=[%s]\n",
2384 2385 2386
          inputEncoding.data(),outputEncoding,input.data());
      error=TRUE;
    }
2387 2388
  }
  portable_iconv_close(cd);
2389
  return error ? input : output;
2390 2391
}

2392 2393 2394 2395
/*! reads a file with name \a name and returns it as a string. If \a filter
 *  is TRUE the file will be filtered by any user specified input filter.
 *  If \a name is "-" the string will be read from standard input. 
 */
2396
QCString fileToString(const char *name,bool filter,bool isSourceCode)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2397 2398
{
  if (name==0 || name[0]==0) return 0;
2399 2400 2401 2402
  QFile f;

  bool fileOpened=FALSE;
  if (name[0]=='-' && name[1]==0) // read from stdin
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2403
  {
2404
    fileOpened=f.open(IO_ReadOnly,stdin);
2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415
    if (fileOpened)
    {
      const int bSize=4096;
      QCString contents(bSize);
      int totalSize=0;
      int size;
      while ((size=f.readBlock(contents.data()+totalSize,bSize))==bSize)
      {
        totalSize+=bSize;
        contents.resize(totalSize+bSize); 
      }
2416
      totalSize = filterCRLF(contents.data(),totalSize+size)+2;
2417 2418 2419 2420 2421
      contents.resize(totalSize);
      contents.at(totalSize-2)='\n'; // to help the scanner
      contents.at(totalSize-1)='\0';
      return contents;
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2422
  }
2423
  else // read from file
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2424
  {
2425 2426 2427
    QFileInfo fi(name);
    if (!fi.exists() || !fi.isFile())
    {
2428
      err("file `%s' not found\n",name);
2429
      return "";
2430
    }
2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442
    BufStr buf(fi.size());
    fileOpened=readInputFile(name,buf,filter,isSourceCode);
    if (fileOpened)
    {
      int s = buf.size();
      if (s>1 && buf.at(s-2)!='\n')
      {
        buf.at(s-1)='\n';
        buf.addChar(0);
      }
      return buf.data();
    }
2443 2444 2445
  }
  if (!fileOpened)  
  {
2446
    err("cannot open file `%s' for reading\n",name);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2447
  }
2448
  return "";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2449 2450
}

2451
QCString dateToString(bool includeTime)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2452
{
2453 2454 2455 2456 2457 2458 2459 2460 2461
  QDateTime current = QDateTime::currentDateTime();
  return theTranslator->trDateTime(current.date().year(),
                                   current.date().month(),
                                   current.date().day(),
                                   current.date().dayOfWeek(),
                                   current.time().hour(),
                                   current.time().minute(),
                                   current.time().second(),
                                   includeTime);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2462 2463
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2464 2465 2466 2467 2468 2469 2470 2471
QCString yearToString()
{
  const QDate &d=QDate::currentDate();
  QCString result;
  result.sprintf("%d", d.year());
  return result;
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2472 2473 2474 2475
//----------------------------------------------------------------------
// recursive function that returns the number of branches in the 
// inheritance tree that the base class `bcd' is below the class `cd'

2476
int minClassDistance(const ClassDef *cd,const ClassDef *bcd,int level)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2477
{
2478
  if (bcd->categoryOf()) // use class that is being extended in case of 
2479
    // an Objective-C category
2480 2481 2482
  {
    bcd=bcd->categoryOf();
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2483
  if (cd==bcd) return level; 
2484 2485
  if (level==256)
  {
2486
    warn_uncond("class %s seem to have a recursive "
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2487
        "inheritance relation!\n",cd->name().data());
2488 2489
    return -1;
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2490
  int m=maxInheritanceDepth; 
2491
  if (cd->baseClasses())
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2492
  {
2493 2494 2495
    BaseClassListIterator bcli(*cd->baseClasses());
    BaseClassDef *bcdi;
    for (;(bcdi=bcli.current());++bcli)
2496 2497 2498 2499 2500
    {
      int mc=minClassDistance(bcdi->classDef,bcd,level+1);
      if (mc<m) m=mc;
      if (m<0) break;
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2501 2502 2503 2504
  }
  return m;
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517
Protection classInheritedProtectionLevel(ClassDef *cd,ClassDef *bcd,Protection prot,int level)
{
  if (bcd->categoryOf()) // use class that is being extended in case of 
    // an Objective-C category
  {
    bcd=bcd->categoryOf();
  }
  if (cd==bcd) 
  {
    goto exit;
  }
  if (level==256)
  {
2518
    err("Internal inconsistency: found class %s seem to have a recursive "
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2519 2520 2521 2522
        "inheritance relation! Please send a bug report to dimitri@stack.nl\n",cd->name().data());
  }
  else if (cd->baseClasses())
  {
2523 2524 2525
    BaseClassListIterator bcli(*cd->baseClasses());
    BaseClassDef *bcdi;
    for (;(bcdi=bcli.current()) && prot!=Private;++bcli)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536
    {
      Protection baseProt = classInheritedProtectionLevel(bcdi->classDef,bcd,bcdi->prot,level+1);
      if (baseProt==Private)   prot=Private;
      else if (baseProt==Protected) prot=Protected;
    }
  }
exit:
  //printf("classInheritedProtectionLevel(%s,%s)=%d\n",cd->name().data(),bcd->name().data(),prot);
  return prot;
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2537 2538 2539 2540 2541 2542 2543 2544
//static void printArgList(ArgumentList *al)
//{
//  if (al==0) return;
//  ArgumentListIterator ali(*al);
//  Argument *a;
//  printf("(");
//  for (;(a=ali.current());++ali)
//  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2545
//    printf("t=`%s' n=`%s' v=`%s' ",a->type.data(),!a->name.isEmpty()>0?a->name.data():"",!a->defval.isEmpty()>0?a->defval.data():""); 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2546 2547 2548 2549
//  }
//  printf(")");
//}

2550
#ifndef NEWMATCH
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2551
// strip any template specifiers that follow className in string s
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2552
static QCString trimTemplateSpecifiers(
2553 2554 2555 2556
    const QCString &namespaceName,
    const QCString &className,
    const QCString &s
    )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2557
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2558 2559 2560 2561
  //printf("trimTemplateSpecifiers(%s,%s,%s)\n",namespaceName.data(),className.data(),s.data());
  QCString scopeName=mergeScopes(namespaceName,className);
  ClassDef *cd=getClass(scopeName);
  if (cd==0) return s; // should not happen, but guard anyway.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2562

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2563 2564 2565
  QCString result=s;

  int i=className.length()-1;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2566
  if (i>=0 && className.at(i)=='>') // template specialization
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592
  {
    // replace unspecialized occurrences in s, with their specialized versions.
    int count=1;
    int cl=i+1;
    while (i>=0)
    {
      char c=className.at(i);
      if (c=='>') count++,i--;
      else if (c=='<') { count--; if (count==0) break; }
      else i--;
    }
    QCString unspecClassName=className.left(i);
    int l=i;
    int p=0;
    while ((i=result.find(unspecClassName,p))!=-1)
    {
      if (result.at(i+l)!='<') // unspecialized version
      {
        result=result.left(i)+className+result.right(result.length()-i-l);
        l=cl;
      }
      p=i+l;
    }
  }

  //printf("result after specialization: %s\n",result.data());
2593

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2594 2595
  QCString qualName=cd->qualifiedNameWithTemplateParameters();
  //printf("QualifiedName = %s\n",qualName.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2596
  // We strip the template arguments following className (if any)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2597
  if (!qualName.isEmpty()) // there is a class name
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2598
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2599 2600 2601 2602
    int is,ps=0;
    int p=0,l,i;

    while ((is=getScopeFragment(qualName,ps,&l))!=-1)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2603
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2604 2605 2606 2607 2608 2609 2610 2611 2612
      QCString qualNamePart = qualName.right(qualName.length()-is);
      //printf("qualNamePart=%s\n",qualNamePart.data());
      while ((i=result.find(qualNamePart,p))!=-1)
      {
        int ql=qualNamePart.length();
        result=result.left(i)+cd->name()+result.right(result.length()-i-ql);
        p=i+cd->name().length();
      }
      ps=is+l;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2613 2614
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2615
  //printf("result=%s\n",result.data());
2616

2617
  return result.stripWhiteSpace();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2618 2619
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2620 2621 2622 2623 2624 2625 2626 2627
/*!
 * @param pattern pattern to look for
 * @param s string to search in
 * @param p position to start
 * @param len resulting pattern length
 * @returns position on which string is found, or -1 if not found
 */
static int findScopePattern(const QCString &pattern,const QCString &s,
2628
    int p,int *len)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681
{
  int sl=s.length();
  int pl=pattern.length();
  int sp=0; 
  *len=0;
  while (p<sl)
  {
    sp=p; // start of match
    int pp=0; // pattern position
    while (p<sl && pp<pl)
    {
      if (s.at(p)=='<') // skip template arguments while matching
      {
        int bc=1;
        //printf("skipping pos=%d c=%c\n",p,s.at(p));
        p++;
        while (p<sl)
        {
          if (s.at(p)=='<') bc++;
          else if (s.at(p)=='>') 
          {
            bc--;
            if (bc==0) 
            {
              p++;
              break;
            }
          }
          //printf("skipping pos=%d c=%c\n",p,s.at(p));
          p++;
        }
      }
      else if (s.at(p)==pattern.at(pp))
      {
        //printf("match at position p=%d pp=%d c=%c\n",p,pp,s.at(p));
        p++;
        pp++;
      }
      else // no match
      {
        //printf("restarting at %d c=%c pat=%s\n",p,s.at(p),pattern.data());
        p=sp+1;
        break;
      }
    }
    if (pp==pl) // whole pattern matches
    {
      *len=p-sp;
      return sp;
    }
  }
  return -1;
}
2682

2683
static QCString trimScope(const QCString &name,const QCString &s)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2684
{
2685 2686 2687
  int scopeOffset=name.length();
  QCString result=s;
  do // for each scope
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2688
  {
2689 2690 2691
    QCString tmp;
    QCString scope=name.left(scopeOffset)+"::";
    //printf("Trying with scope=`%s'\n",scope.data());
2692

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2693 2694
    int i,p=0,l;
    while ((i=findScopePattern(scope,result,p,&l))!=-1) // for each occurrence
2695 2696
    {
      tmp+=result.mid(p,i-p); // add part before pattern
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2697
      p=i+l;
2698 2699 2700 2701 2702 2703
    }
    tmp+=result.right(result.length()-p); // add trailing part

    scopeOffset=name.findRev("::",scopeOffset-1);
    result = tmp;
  } while (scopeOffset>0);   
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2704
  //printf("trimScope(name=%s,scope=%s)=%s\n",name.data(),s.data(),result.data());
2705
  return result;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2706
}
2707
#endif
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2708

2709
void trimBaseClassScope(BaseClassList *bcl,QCString &s,int level=0)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2710
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2711
  //printf("trimBaseClassScope level=%d `%s'\n",level,s.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2712 2713 2714 2715 2716
  BaseClassListIterator bcli(*bcl);
  BaseClassDef *bcd;
  for (;(bcd=bcli.current());++bcli)
  {
    ClassDef *cd=bcd->classDef;
2717
    //printf("Trying class %s\n",cd->name().data());
2718
    int spos=s.find(cd->name()+"::");
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2719 2720
    if (spos!=-1)
    {
2721
      s = s.left(spos)+s.right(
2722 2723
          s.length()-spos-cd->name().length()-2
          );
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2724
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2725
    //printf("base class `%s'\n",cd->name().data());
2726
    if (cd->baseClasses())
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2727
      trimBaseClassScope(cd->baseClasses(),s,level+1); 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2728 2729 2730
  }
}

2731
#if 0
2732 2733 2734 2735
/*! if either t1 or t2 contains a namespace scope, then remove that
 *  scope. If neither or both have a namespace scope, t1 and t2 remain
 *  unchanged.
 */
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2736
static void trimNamespaceScope(QCString &t1,QCString &t2,const QCString &nsName)
2737 2738 2739 2740 2741
{
  int p1=t1.length();
  int p2=t2.length();
  for (;;)
  {
2742 2743
    int i1=p1==0 ? -1 : t1.findRev("::",p1);
    int i2=p2==0 ? -1 : t2.findRev("::",p2);
2744 2745 2746 2747 2748 2749 2750
    if (i1==-1 && i2==-1)
    {
      return;
    }
    if (i1!=-1 && i2==-1) // only t1 has a scope
    {
      QCString scope=t1.left(i1);
2751
      replaceNamespaceAliases(scope,i1);
2752

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2753 2754
      int so=nsName.length();
      do
2755
      {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2756 2757 2758
        QCString fullScope=nsName.left(so);
        if (!fullScope.isEmpty() && !scope.isEmpty()) fullScope+="::";
        fullScope+=scope;
2759
        if (!fullScope.isEmpty() && Doxygen::namespaceSDict[fullScope]!=0) // scope is a namespace
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771
        {
          t1 = t1.right(t1.length()-i1-2);
          return;
        }
        if (so==0)
        {
          so=-1;
        }
        else if ((so=nsName.findRev("::",so-1))==-1)
        {
          so=0;
        }
2772
      }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2773
      while (so>=0);
2774 2775 2776 2777
    }
    else if (i1==-1 && i2!=-1) // only t2 has a scope
    {
      QCString scope=t2.left(i2);
2778
      replaceNamespaceAliases(scope,i2);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2779 2780 2781

      int so=nsName.length();
      do
2782
      {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2783 2784 2785
        QCString fullScope=nsName.left(so);
        if (!fullScope.isEmpty() && !scope.isEmpty()) fullScope+="::";
        fullScope+=scope;
2786
        if (!fullScope.isEmpty() && Doxygen::namespaceSDict[fullScope]!=0) // scope is a namespace
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
        {
          t2 = t2.right(t2.length()-i2-2);
          return;
        }
        if (so==0)
        {
          so=-1;
        }
        else if ((so=nsName.findRev("::",so-1))==-1)
        {
          so=0;
        }
2799
      }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2800
      while (so>=0);
2801 2802 2803 2804 2805
    }
    p1 = QMAX(i1-2,0);
    p2 = QMAX(i2-2,0);
  }
}
2806
#endif
2807

2808 2809 2810 2811 2812
static void stripIrrelevantString(QCString &target,const QCString &str)
{
  if (target==str) { target.resize(0); return; }
  int i,p=0;
  int l=str.length();
2813
  bool changed=FALSE;
2814 2815 2816
  while ((i=target.find(str,p))!=-1)
  {
    bool isMatch = (i==0 || !isId(target.at(i-1))) && // not a character before str
2817
      (i+l==(int)target.length() || !isId(target.at(i+l))); // not a character after str
2818 2819 2820 2821 2822 2823 2824 2825
    if (isMatch)
    {
      int i1=target.find('*',i+l);
      int i2=target.find('&',i+l);
      if (i1==-1 && i2==-1)
      {
        // strip str from target at index i
        target=target.left(i)+target.right(target.length()-i-l); 
2826
        changed=TRUE;
2827 2828 2829 2830 2831 2832
        i-=l;
      }
      else if ((i1!=-1 && i<i1) || (i2!=-1 && i<i2)) // str before * or &
      {
        // move str to front
        target=str+" "+target.left(i)+target.right(target.length()-i-l);
2833
        changed=TRUE;
2834 2835 2836 2837 2838
        i++;
      }
    }
    p = i+l;
  }
2839
  if (changed) target=target.stripWhiteSpace();
2840 2841
}

2842 2843
/*! According to the C++ spec and Ivan Vecerina:

2844 2845
  Parameter declarations  that differ only in the presence or absence
  of const and/or volatile are equivalent.
2846

2847 2848
  So the following example, show what is stripped by this routine
  for const. The same is done for volatile.
2849

2850 2851 2852 2853 2854 2855
  \code
  const T param     ->   T param          // not relevant
  const T& param    ->   const T& param   // const needed               
  T* const param    ->   T* param         // not relevant                   
  const T* param    ->   const T* param   // const needed
  \endcode
2856 2857 2858
 */
void stripIrrelevantConstVolatile(QCString &s)
{
2859
  //printf("stripIrrelevantConstVolatile(%s)=",s.data());
2860 2861
  stripIrrelevantString(s,"const");
  stripIrrelevantString(s,"volatile");
2862
  //printf("%s\n",s.data());
2863 2864
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2865

2866 2867 2868 2869 2870 2871
// a bit of debug support for matchArguments
#define MATCH
#define NOMATCH
//#define MATCH printf("Match at line %d\n",__LINE__);
//#define NOMATCH printf("Nomatch at line %d\n",__LINE__);

2872
#ifndef NEWMATCH
2873
static bool matchArgument(const Argument *srcA,const Argument *dstA,
2874 2875 2876 2877
    const QCString &className,
    const QCString &namespaceName,
    NamespaceSDict *usingNamespaces,
    SDict<Definition> *usingClasses)
2878
{
2879
  //printf("match argument start `%s|%s' <-> `%s|%s' using nsp=%p class=%p\n",
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2880
  //    srcA->type.data(),srcA->name.data(),
2881 2882 2883
  //    dstA->type.data(),dstA->name.data(),
  //    usingNamespaces,
  //    usingClasses);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2884 2885 2886 2887 2888

  // TODO: resolve any typedefs names that are part of srcA->type
  //       before matching. This should use className and namespaceName
  //       and usingNamespaces and usingClass to determine which typedefs
  //       are in-scope, so it will not be very efficient :-(
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2889 2890 2891

  QCString srcAType=trimTemplateSpecifiers(namespaceName,className,srcA->type);
  QCString dstAType=trimTemplateSpecifiers(namespaceName,className,dstA->type);
2892 2893
  QCString srcAName=srcA->name.stripWhiteSpace();
  QCString dstAName=dstA->name.stripWhiteSpace();
2894 2895
  srcAType.stripPrefix("class ");
  dstAType.stripPrefix("class ");
2896

2897
  // allow distinguishing "const A" from "const B" even though 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2898
  // from a syntactic point of view they would be two names of the same 
2899
  // type "const". This is not fool prove of course, but should at least 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2900
  // catch the most common cases.
2901
  if ((srcAType=="const" || srcAType=="volatile") && !srcAName.isEmpty())
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2902 2903
  {
    srcAType+=" ";
2904
    srcAType+=srcAName;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2905
  } 
2906
  if ((dstAType=="const" || dstAType=="volatile") && !dstAName.isEmpty())
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2907 2908
  {
    dstAType+=" ";
2909
    dstAType+=dstAName;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2910
  }
2911
  if (srcAName=="const" || srcAName=="volatile")
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2912
  {
2913 2914
    srcAType+=srcAName;
    srcAName.resize(0);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2915
  }
2916
  else if (dstA->name=="const" || dstA->name=="volatile")
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2917 2918
  {
    dstAType+=dstA->name;
2919
    dstAName.resize(0);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2920
  }
2921

2922 2923 2924
  stripIrrelevantConstVolatile(srcAType);
  stripIrrelevantConstVolatile(dstAType);

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2925
  // strip typename keyword
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2926
  if (qstrncmp(srcAType,"typename ",9)==0)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2927 2928 2929
  {
    srcAType = srcAType.right(srcAType.length()-9); 
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2930
  if (qstrncmp(dstAType,"typename ",9)==0)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2931 2932 2933
  {
    dstAType = dstAType.right(dstAType.length()-9); 
  }
2934

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2935 2936 2937
  srcAType = removeRedundantWhiteSpace(srcAType);
  dstAType = removeRedundantWhiteSpace(dstAType);

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2938 2939 2940
  //srcAType=stripTemplateSpecifiersFromScope(srcAType,FALSE);
  //dstAType=stripTemplateSpecifiersFromScope(dstAType,FALSE);

2941 2942
  //printf("srcA=`%s|%s' dstA=`%s|%s'\n",srcAType.data(),srcAName.data(),
  //      dstAType.data(),dstAName.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2943

2944 2945 2946
  if (srcA->array!=dstA->array) // nomatch for char[] against char
  {
    NOMATCH
2947
      return FALSE;
2948 2949 2950 2951 2952 2953
  }
  if (srcAType!=dstAType) // check if the argument only differs on name 
  {

    // remove a namespace scope that is only in one type 
    // (assuming a using statement was used)
2954 2955 2956
    //printf("Trimming %s<->%s: %s\n",srcAType.data(),dstAType.data(),namespaceName.data());
    //trimNamespaceScope(srcAType,dstAType,namespaceName);
    //printf("After Trimming %s<->%s\n",srcAType.data(),dstAType.data());
2957

2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971
    //QCString srcScope;
    //QCString dstScope;

    // strip redundant scope specifiers
    if (!className.isEmpty())
    {
      srcAType=trimScope(className,srcAType);
      dstAType=trimScope(className,dstAType);
      //printf("trimScope: `%s' <=> `%s'\n",srcAType.data(),dstAType.data());
      ClassDef *cd;
      if (!namespaceName.isEmpty())
        cd=getClass(namespaceName+"::"+className);
      else
        cd=getClass(className);
2972
      if (cd && cd->baseClasses())
2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983
      {
        trimBaseClassScope(cd->baseClasses(),srcAType); 
        trimBaseClassScope(cd->baseClasses(),dstAType); 
      }
      //printf("trimBaseClassScope: `%s' <=> `%s'\n",srcAType.data(),dstAType.data());
    }
    if (!namespaceName.isEmpty())
    {
      srcAType=trimScope(namespaceName,srcAType);
      dstAType=trimScope(namespaceName,dstAType);
    }
2984
    //printf("#usingNamespace=%d\n",usingNamespaces->count());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2985
    if (usingNamespaces && usingNamespaces->count()>0)
2986
    {
2987
      NamespaceSDict::Iterator nli(*usingNamespaces);
2988 2989 2990 2991 2992 2993 2994
      NamespaceDef *nd;
      for (;(nd=nli.current());++nli)
      {
        srcAType=trimScope(nd->name(),srcAType);
        dstAType=trimScope(nd->name(),dstAType);
      }
    }
2995
    //printf("#usingClasses=%d\n",usingClasses->count());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2996 2997
    if (usingClasses && usingClasses->count()>0)
    {
2998 2999
      SDict<Definition>::Iterator cli(*usingClasses);
      Definition *cd;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3000 3001 3002 3003 3004 3005
      for (;(cd=cli.current());++cli)
      {
        srcAType=trimScope(cd->name(),srcAType);
        dstAType=trimScope(cd->name(),dstAType);
      }
    }
3006

3007 3008
    //printf("2. srcA=%s|%s dstA=%s|%s\n",srcAType.data(),srcAName.data(),
    //    dstAType.data(),dstAName.data());
3009

3010 3011
    if (!srcAName.isEmpty() && !dstA->type.isEmpty() &&
        (srcAType+" "+srcAName)==dstAType)
3012 3013
    {
      MATCH
3014
      return TRUE;
3015
    }
3016 3017
    else if (!dstAName.isEmpty() && !srcA->type.isEmpty() &&
        (dstAType+" "+dstAName)==srcAType)
3018 3019
    {
      MATCH
3020
      return TRUE;
3021
    }
3022

3023 3024 3025 3026 3027 3028 3029 3030

    uint srcPos=0,dstPos=0; 
    bool equal=TRUE;
    while (srcPos<srcAType.length() && dstPos<dstAType.length() && equal)
    {
      equal=srcAType.at(srcPos)==dstAType.at(dstPos);
      if (equal) srcPos++,dstPos++; 
    }
3031 3032 3033
    uint srcATypeLen=srcAType.length();
    uint dstATypeLen=dstAType.length();
    if (srcPos<srcATypeLen && dstPos<dstATypeLen)
3034 3035 3036 3037 3038 3039
    {
      // if nothing matches or the match ends in the middle or at the
      // end of a string then there is no match
      if (srcPos==0 || dstPos==0) 
      {
        NOMATCH
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3040
        return FALSE;
3041 3042 3043
      }
      if (isId(srcAType.at(srcPos)) && isId(dstAType.at(dstPos)))
      {
3044
        //printf("partial match srcPos=%d dstPos=%d!\n",srcPos,dstPos);
3045
        // check if a name if already found -> if no then there is no match
3046
        if (!srcAName.isEmpty() || !dstAName.isEmpty()) 
3047 3048
        {
          NOMATCH
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3049
          return FALSE;
3050
        }
3051 3052 3053 3054 3055 3056 3057
        // types only
        while (srcPos<srcATypeLen && isId(srcAType.at(srcPos))) srcPos++;
        while (dstPos<dstATypeLen && isId(dstAType.at(dstPos))) dstPos++;
        if (srcPos<srcATypeLen || 
            dstPos<dstATypeLen ||
            (srcPos==srcATypeLen && dstPos==dstATypeLen)
           ) 
3058 3059
        {
          NOMATCH
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3060
          return FALSE;
3061 3062 3063 3064 3065
        }
      }
      else
      {
        // otherwise we assume that a name starts at the current position.
3066 3067
        while (srcPos<srcATypeLen && isId(srcAType.at(srcPos))) srcPos++;
        while (dstPos<dstATypeLen && isId(dstAType.at(dstPos))) dstPos++;
3068

3069 3070 3071 3072 3073
        // if nothing more follows for both types then we assume we have
        // found a match. Note that now `signed int' and `signed' match, but
        // seeing that int is not a name can only be done by looking at the
        // semantics.

3074
        if (srcPos!=srcATypeLen || dstPos!=dstATypeLen) 
3075 3076
        { 
          NOMATCH
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3077
          return FALSE; 
3078 3079 3080 3081 3082
        }
      }
    }
    else if (dstPos<dstAType.length())
    {
3083
      if (!isspace((uchar)dstAType.at(dstPos))) // maybe the names differ
3084
      {
3085
        if (!dstAName.isEmpty()) // dst has its name separated from its type
3086 3087
        {
          NOMATCH
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3088
          return FALSE;
3089
        }
3090 3091 3092 3093
        while (dstPos<dstAType.length() && isId(dstAType.at(dstPos))) dstPos++;
        if (dstPos!=dstAType.length()) 
        {
          NOMATCH
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3094
          return FALSE; // more than a difference in name -> no match
3095 3096
        }
      }
3097
      else  // maybe dst has a name while src has not
3098 3099 3100
      {
        dstPos++;
        while (dstPos<dstAType.length() && isId(dstAType.at(dstPos))) dstPos++;
3101
        if (dstPos!=dstAType.length() || !srcAName.isEmpty()) 
3102 3103
        {
          NOMATCH
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3104
          return FALSE; // nope not a name -> no match
3105 3106 3107 3108 3109
        }
      }
    }
    else if (srcPos<srcAType.length())
    {
3110
      if (!isspace((uchar)srcAType.at(srcPos))) // maybe the names differ
3111
      {
3112
        if (!srcAName.isEmpty()) // src has its name separated from its type
3113 3114
        {
          NOMATCH
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3115
          return FALSE;
3116
        }
3117 3118 3119 3120
        while (srcPos<srcAType.length() && isId(srcAType.at(srcPos))) srcPos++;
        if (srcPos!=srcAType.length()) 
        {
          NOMATCH
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3121
          return FALSE; // more than a difference in name -> no match
3122 3123 3124 3125 3126 3127
        }
      }
      else // maybe src has a name while dst has not
      {
        srcPos++;
        while (srcPos<srcAType.length() && isId(srcAType.at(srcPos))) srcPos++;
3128
        if (srcPos!=srcAType.length() || !dstAName.isEmpty()) 
3129 3130
        {
          NOMATCH
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3131
          return FALSE; // nope not a name -> no match
3132 3133 3134 3135 3136
        }
      }
    }
  }
  MATCH
3137
  return TRUE;
3138 3139 3140 3141 3142 3143 3144 3145 3146 3147
}


/*!
 * Matches the arguments list srcAl with the argument list dstAl
 * Returns TRUE if the argument lists are equal. Two argument list are 
 * considered equal if the number of arguments is equal and the types of all 
 * arguments are equal. Furthermore the const and volatile specifiers 
 * stored in the list should be equal.
 */
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3148
bool matchArguments(ArgumentList *srcAl,ArgumentList *dstAl,
3149 3150 3151
    const char *cl,const char *ns,bool checkCV,
    NamespaceSDict *usingNamespaces,
    SDict<Definition> *usingClasses)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3152
{
3153 3154 3155
  QCString className=cl;
  QCString namespaceName=ns;

3156
  // strip template specialization from class name if present
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3157 3158 3159 3160 3161
  //int til=className.find('<'),tir=className.find('>');
  //if (til!=-1 && tir!=-1 && tir>til) 
  //{
  //  className=className.left(til)+className.right(className.length()-tir-1);
  //}
3162

Dimitri van Heesch's avatar
Dimitri van Heesch committed
3163
  //printf("matchArguments(%s,%s) className=%s namespaceName=%s checkCV=%d usingNamespaces=%d usingClasses=%d\n",
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3164 3165
  //    srcAl ? argListToString(srcAl).data() : "",
  //    dstAl ? argListToString(dstAl).data() : "",
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3166 3167 3168 3169
  //    cl,ns,checkCV,
  //    usingNamespaces?usingNamespaces->count():0,
  //    usingClasses?usingClasses->count():0
  //    );
3170

Dimitri van Heesch's avatar
Dimitri van Heesch committed
3171 3172
  if (srcAl==0 || dstAl==0)
  {
3173 3174 3175 3176
    bool match = srcAl==dstAl; // at least one of the members is not a function
    if (match)
    {
      MATCH
3177
      return TRUE;
3178 3179 3180 3181
    }
    else
    {
      NOMATCH
3182
      return FALSE;
3183
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3184
  }
3185

3186
  // handle special case with void argument
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3187
  if ( srcAl->count()==0 && dstAl->count()==1 && 
3188
      dstAl->getFirst()->type=="void" )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3189 3190 3191 3192
  { // special case for finding match between func() and func(void)
    Argument *a=new Argument;
    a->type = "void";
    srcAl->append(a);
3193
    MATCH
3194
    return TRUE;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3195 3196
  }
  if ( dstAl->count()==0 && srcAl->count()==1 &&
3197
      srcAl->getFirst()->type=="void" )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3198 3199 3200 3201
  { // special case for finding match between func(void) and func()
    Argument *a=new Argument;
    a->type = "void";
    dstAl->append(a);
3202
    MATCH
3203
    return TRUE;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3204
  }
3205

Dimitri van Heesch's avatar
Dimitri van Heesch committed
3206 3207
  if (srcAl->count() != dstAl->count())
  {
3208
    NOMATCH
3209
    return FALSE; // different number of arguments -> no match
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3210
  }
3211 3212

  if (checkCV)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3213
  {
3214 3215
    if (srcAl->constSpecifier != dstAl->constSpecifier) 
    {
3216
      NOMATCH
3217
      return FALSE; // one member is const, the other not -> no match
3218 3219 3220
    }
    if (srcAl->volatileSpecifier != dstAl->volatileSpecifier)
    {
3221
      NOMATCH
3222
      return FALSE; // one member is volatile, the other not -> no match
3223
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3224 3225 3226 3227 3228 3229 3230
  }

  // so far the argument list could match, so we need to compare the types of
  // all arguments.
  ArgumentListIterator srcAli(*srcAl),dstAli(*dstAl);
  Argument *srcA,*dstA;
  for (;(srcA=srcAli.current(),dstA=dstAli.current());++srcAli,++dstAli)
3231
  { 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3232 3233
    if (!matchArgument(srcA,dstA,className,namespaceName,
          usingNamespaces,usingClasses))
3234
    {
3235
      NOMATCH
3236
      return FALSE;
3237
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3238
  }
3239
  MATCH
3240
  return TRUE; // all arguments match 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3241 3242
}

3243 3244
#endif

Dimitri van Heesch's avatar
Dimitri van Heesch committed
3245
#if 0
3246 3247 3248 3249 3250
static QCString resolveSymbolName(FileDef *fs,Definition *symbol,QCString &templSpec)
{
  ASSERT(symbol!=0);
  if (symbol->definitionType()==Definition::TypeMember && 
      ((MemberDef*)symbol)->isTypedef()) // if symbol is a typedef then try
3251
    // to resolve it
3252 3253 3254 3255 3256
  {
    MemberDef *md = 0;
    ClassDef *cd = newResolveTypedef(fs,(MemberDef*)symbol,&md,&templSpec);
    if (cd)
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3257
      return cd->qualifiedName()+templSpec;
3258 3259 3260 3261 3262 3263 3264 3265
    }
    else if (md)
    {
      return md->qualifiedName();
    }
  }
  return symbol->qualifiedName();
}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279
#endif

static QCString stripDeclKeywords(const QCString &s)
{
  int i=s.find(" class ");
  if (i!=-1) return s.left(i)+s.mid(i+6);
  i=s.find(" typename ");
  if (i!=-1) return s.left(i)+s.mid(i+9);
  i=s.find(" union ");
  if (i!=-1) return s.left(i)+s.mid(i+6);
  i=s.find(" struct ");
  if (i!=-1) return s.left(i)+s.mid(i+7);
  return s;
}
3280

3281 3282 3283
// forward decl for circular dependencies
static QCString extractCanonicalType(Definition *d,FileDef *fs,QCString type);

3284
QCString getCanonicalTemplateSpec(Definition *d,FileDef *fs,const QCString& spec)
3285
{
3286
  
3287
  QCString templSpec = spec.stripWhiteSpace();
3288 3289 3290 3291 3292 3293 3294
  // this part had been commented out before... but it is needed to match for instance
  // std::list<std::string> against list<string> so it is now back again!
  if (!templSpec.isEmpty() && templSpec.at(0) == '<') 
  {
    templSpec = "< " + extractCanonicalType(d,fs,templSpec.right(templSpec.length()-1).stripWhiteSpace());
  }
  QCString resolvedType = resolveTypeDef(d,templSpec);
3295 3296 3297 3298 3299 3300
  if (!resolvedType.isEmpty()) // not known as a typedef either
  {
    templSpec = resolvedType;
  }
  //printf("getCanonicalTemplateSpec(%s)=%s\n",spec.data(),templSpec.data());
  return templSpec;
3301 3302 3303
}


3304
static QCString getCanonicalTypeForIdentifier(
3305
    Definition *d,FileDef *fs,const QCString &word,
3306
    QCString *tSpec,int count=0)
3307
{
3308 3309
  if (count>10) return word; // oops recursion

3310
  QCString symName,scope,result,templSpec,tmpName;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3311
  //DefinitionList *defList=0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3312 3313
  if (tSpec && !tSpec->isEmpty()) 
    templSpec = stripDeclKeywords(getCanonicalTemplateSpec(d,fs,*tSpec));
3314

3315
  if (word.findRev("::")!=-1 && !(tmpName=stripScope(word)).isEmpty())
3316
  {
3317
    symName=tmpName; // name without scope
3318 3319 3320 3321 3322
  }
  else
  {
    symName=word;
  }
3323 3324
  //printf("getCanonicalTypeForIdentifier(%s,[%s->%s]) start\n",
  //    word.data(),tSpec?tSpec->data():"<none>",templSpec.data());
3325

3326 3327 3328
  ClassDef *cd = 0;
  MemberDef *mType = 0;
  QCString ts;
3329
  QCString resolvedType;
3330 3331

  // lookup class / class template instance
3332
  cd = getResolvedClass(d,fs,word+templSpec,&mType,&ts,TRUE,TRUE,&resolvedType);
3333 3334
  bool isTemplInst = cd && !templSpec.isEmpty();
  if (!cd && !templSpec.isEmpty())
3335
  {
3336
    // class template specialization not known, look up class template
3337
    cd = getResolvedClass(d,fs,word,&mType,&ts,TRUE,TRUE,&resolvedType);
3338
  }
3339
  if (cd && cd->isUsedOnly()) cd=0; // ignore types introduced by usage relations
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3340

3341
  //printf("cd=%p mtype=%p\n",cd,mType);
3342
  //printf("  getCanonicalTypeForIdentifer: symbol=%s word=%s cd=%s d=%s fs=%s cd->isTemplate=%d\n",
3343 3344 3345 3346
  //    symName.data(),
  //    word.data(),
  //    cd?cd->name().data():"<none>",
  //    d?d->name().data():"<none>",
3347 3348
  //    fs?fs->name().data():"<none>",
  //    cd?cd->isTemplate():-1
3349
  //   );
3350

3351
  //printf("  >>>> word '%s' => '%s' templSpec=%s ts=%s tSpec=%s isTemplate=%d resolvedType=%s\n",
3352
  //    (word+templSpec).data(),
3353
  //    cd?cd->qualifiedName().data():"<none>",
3354 3355
  //    templSpec.data(),ts.data(),
  //    tSpec?tSpec->data():"<null>",
3356 3357 3358 3359
  //    cd?cd->isTemplate():FALSE,
  //    resolvedType.data());

  //printf("  mtype=%s\n",mType?mType->name().data():"<none>");
3360

3361
  if (cd) // resolves to a known class type
3362
  {
3363 3364
    if (cd==d && tSpec) *tSpec="";

3365
    if (mType && mType->isTypedef()) // but via a typedef
3366
    {
3367
      result = resolvedType+ts; // the +ts was added for bug 685125
3368
    }
3369
    else
3370
    {
3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381
      if (isTemplInst)
      {
        // spec is already part of class type
        templSpec="";
        if (tSpec) *tSpec="";
      }
      else if (!ts.isEmpty() && templSpec.isEmpty())
      {
        // use formal template args for spec
        templSpec = stripDeclKeywords(getCanonicalTemplateSpec(d,fs,ts));
      }
3382

3383
      result = removeRedundantWhiteSpace(cd->qualifiedName() + templSpec);
3384

3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403
      if (cd->isTemplate() && tSpec) //
      {
        if (!templSpec.isEmpty()) // specific instance
        {
          result=cd->name()+templSpec;
        }
        else // use template type
        {
          result=cd->qualifiedNameWithTemplateParameters();
        }
        // template class, so remove the template part (it is part of the class name)
        *tSpec="";
      }
      else if (ts.isEmpty() && !templSpec.isEmpty() && cd && !cd->isTemplate() && tSpec)
      {
        // obscure case, where a class is used as a template, but doxygen think it is
        // not (could happen when loading the class from a tag file).
        *tSpec="";
      }
3404
    }
3405 3406 3407 3408 3409
  }
  else if (mType && mType->isEnumerate()) // an enum
  {
    result = mType->qualifiedName();
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3410 3411
  else if (mType && mType->isTypedef()) // a typedef
  {
3412
    //result = mType->qualifiedName(); // changed after 1.7.2
3413
    //result = mType->typeString();
3414
    //printf("word=%s typeString=%s\n",word.data(),mType->typeString());
3415 3416
    if (word!=mType->typeString())
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3417
      result = getCanonicalTypeForIdentifier(d,fs,mType->typeString(),tSpec,count+1);
3418 3419 3420 3421 3422
    }
    else
    {
      result = mType->typeString();
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3423
  }
3424
  else // fallback
3425
  {
3426
    resolvedType = resolveTypeDef(d,word);
3427
    //printf("typedef [%s]->[%s]\n",word.data(),resolvedType.data());
3428
    if (resolvedType.isEmpty()) // not known as a typedef either
3429
    {
3430
      result = word;
3431
    }
3432
    else
3433
    {
3434
      result = resolvedType;
3435 3436
    }
  }
3437
  //printf("getCanonicalTypeForIdentifier [%s]->[%s]\n",word.data(),result.data());
3438 3439
  return result;
}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3440

3441
static QCString extractCanonicalType(Definition *d,FileDef *fs,QCString type)
3442
{
3443
  type = type.stripWhiteSpace();
3444

3445
  // strip const and volatile keywords that are not relevant for the type
3446
  stripIrrelevantConstVolatile(type);
3447

3448
  // strip leading keywords
3449 3450 3451 3452 3453
  type.stripPrefix("class ");
  type.stripPrefix("struct ");
  type.stripPrefix("union ");
  type.stripPrefix("enum ");
  type.stripPrefix("typename ");
3454

3455
  type = removeRedundantWhiteSpace(type);
3456
  //printf("extractCanonicalType(type=%s) start: def=%s file=%s\n",type.data(),
3457
  //    d ? d->name().data() : "<null>",fs ? fs->name().data() : "<null>");
3458

3459
  //static QRegExp id("[a-z_A-Z\\x80-\\xFF][:a-z_A-Z0-9\\x80-\\xFF]*");
3460

3461 3462
  QCString canType;
  QCString templSpec,word;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3463 3464
  int i,p=0,pp=0;
  while ((i=extractClassNameFromType(type,p,word,templSpec))!=-1)
3465
    // foreach identifier in the type
3466
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3467
    //printf("     i=%d p=%d\n",i,p);
3468
    if (i>pp) canType += type.mid(pp,i-pp);
3469

3470

3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483
    QCString ct = getCanonicalTypeForIdentifier(d,fs,word,&templSpec);

    // in case the ct is empty it means that "word" represents scope "d"
    // and this does not need to be added to the canonical 
    // type (it is redundant), so/ we skip it. This solves problem 589616.
    if (ct.isEmpty() && type.mid(p,2)=="::")
    {
      p+=2;
    }
    else
    {
      canType += ct;
    }
3484 3485
    //printf(" word=%s templSpec=%s canType=%s ct=%s\n",
    //    word.data(),templSpec.data(),canType.data(),ct.data());
3486
    if (!templSpec.isEmpty()) // if we didn't use up the templSpec already
3487 3488
                              // (i.e. type is not a template specialization)
                              // then resolve any identifiers inside. 
3489
    {
3490
      static QRegExp re("[a-z_A-Z\\x80-\\xFF][a-z_A-Z0-9\\x80-\\xFF]*");
3491
      int tp=0,tl,ti;
3492
      // for each identifier template specifier
3493
      //printf("adding resolved %s to %s\n",templSpec.data(),canType.data());
3494
      while ((ti=re.match(templSpec,tp,&tl))!=-1)
3495
      {
3496 3497 3498
        canType += templSpec.mid(tp,ti-tp);
        canType += getCanonicalTypeForIdentifier(d,fs,templSpec.mid(ti,tl),0);
        tp=ti+tl;
3499
      }
3500
      canType+=templSpec.right(templSpec.length()-tp);
3501
    }
3502

Dimitri van Heesch's avatar
Dimitri van Heesch committed
3503
    pp=p;
3504
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3505
  canType += type.right(type.length()-pp);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3506
  //printf("extractCanonicalType = '%s'->'%s'\n",type.data(),canType.data());
3507

3508 3509 3510
  return removeRedundantWhiteSpace(canType);
}

3511 3512 3513 3514
static QCString extractCanonicalArgType(Definition *d,FileDef *fs,const Argument *arg)
{
  QCString type = arg->type.stripWhiteSpace();
  QCString name = arg->name;
3515
  //printf("----- extractCanonicalArgType(type=%s,name=%s)\n",type.data(),name.data());
3516 3517 3518 3519 3520 3521 3522 3523 3524 3525
  if ((type=="const" || type=="volatile") && !name.isEmpty()) 
  { // name is part of type => correct
    type+=" ";
    type+=name;
  } 
  if (name=="const" || name=="volatile")
  { // name is part of type => correct
    if (!type.isEmpty()) type+=" ";
    type+=name;
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3526 3527 3528 3529
  if (!arg->array.isEmpty())
  {
    type+=arg->array;
  }
3530 3531 3532 3533

  return extractCanonicalType(d,fs,type);
}

3534
static bool matchArgument2(
3535 3536 3537
    Definition *srcScope,FileDef *srcFileScope,Argument *srcA,
    Definition *dstScope,FileDef *dstFileScope,Argument *dstA
    )
3538
{
3539 3540 3541 3542 3543
  //printf(">> match argument: %s::`%s|%s' (%s) <-> %s::`%s|%s' (%s)\n",
  //    srcScope ? srcScope->name().data() : "",
  //    srcA->type.data(),srcA->name.data(),srcA->canType.data(),
  //    dstScope ? dstScope->name().data() : "",
  //    dstA->type.data(),dstA->name.data(),dstA->canType.data());
3544

Dimitri van Heesch's avatar
Dimitri van Heesch committed
3545 3546 3547 3548 3549
  //if (srcA->array!=dstA->array) // nomatch for char[] against char
  //{
  //  NOMATCH
  //  return FALSE;
  //}
3550 3551 3552 3553 3554 3555 3556 3557 3558
  QCString sSrcName = " "+srcA->name;
  QCString sDstName = " "+dstA->name;
  QCString srcType  = srcA->type;
  QCString dstType  = dstA->type;
  stripIrrelevantConstVolatile(srcType);
  stripIrrelevantConstVolatile(dstType);
  //printf("'%s'<->'%s'\n",sSrcName.data(),dstType.right(sSrcName.length()).data());
  //printf("'%s'<->'%s'\n",sDstName.data(),srcType.right(sDstName.length()).data());
  if (sSrcName==dstType.right(sSrcName.length()))
3559 3560 3561
  { // case "unsigned int" <-> "unsigned int i"
    srcA->type+=sSrcName;
    srcA->name="";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3562
    srcA->canType=""; // invalidate cached type value
3563
  }
3564
  else if (sDstName==srcType.right(sDstName.length()))
3565 3566 3567
  { // case "unsigned int i" <-> "unsigned int"
    dstA->type+=sDstName;
    dstA->name="";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3568
    dstA->canType=""; // invalidate cached type value
3569
  }
3570

3571 3572
  if (srcA->canType.isEmpty())
  {
3573
    srcA->canType = extractCanonicalArgType(srcScope,srcFileScope,srcA);
3574 3575 3576
  }
  if (dstA->canType.isEmpty())
  {
3577
    dstA->canType = extractCanonicalArgType(dstScope,dstFileScope,dstA);
3578
  }
3579

3580
  if (srcA->canType==dstA->canType)
3581 3582
  {
    MATCH
3583
    return TRUE;
3584 3585 3586
  }
  else
  {
3587 3588
    //printf("   Canonical types do not match [%s]<->[%s]\n",
    //    srcA->canType.data(),dstA->canType.data());
3589
    NOMATCH
3590
    return FALSE;
3591 3592 3593 3594 3595 3596
  }
}


// new algorithm for argument matching
bool matchArguments2(Definition *srcScope,FileDef *srcFileScope,ArgumentList *srcAl,
3597 3598 3599
    Definition *dstScope,FileDef *dstFileScope,ArgumentList *dstAl,
    bool checkCV
    )
3600
{
3601
  //printf("*** matchArguments2\n");
3602 3603 3604 3605 3606 3607 3608 3609
  ASSERT(srcScope!=0 && dstScope!=0);

  if (srcAl==0 || dstAl==0)
  {
    bool match = srcAl==dstAl; // at least one of the members is not a function
    if (match)
    {
      MATCH
3610
      return TRUE;
3611 3612 3613 3614
    }
    else
    {
      NOMATCH
3615
      return FALSE;
3616 3617
    }
  }
3618

3619 3620
  // handle special case with void argument
  if ( srcAl->count()==0 && dstAl->count()==1 && 
3621
      dstAl->getFirst()->type=="void" )
3622 3623 3624 3625 3626
  { // special case for finding match between func() and func(void)
    Argument *a=new Argument;
    a->type = "void";
    srcAl->append(a);
    MATCH
3627
    return TRUE;
3628 3629
  }
  if ( dstAl->count()==0 && srcAl->count()==1 &&
3630
      srcAl->getFirst()->type=="void" )
3631 3632 3633 3634 3635
  { // special case for finding match between func(void) and func()
    Argument *a=new Argument;
    a->type = "void";
    dstAl->append(a);
    MATCH
3636
    return TRUE;
3637
  }
3638

3639 3640 3641
  if (srcAl->count() != dstAl->count())
  {
    NOMATCH
3642
    return FALSE; // different number of arguments -> no match
3643 3644 3645 3646 3647 3648 3649
  }

  if (checkCV)
  {
    if (srcAl->constSpecifier != dstAl->constSpecifier) 
    {
      NOMATCH
3650
      return FALSE; // one member is const, the other not -> no match
3651 3652 3653 3654
    }
    if (srcAl->volatileSpecifier != dstAl->volatileSpecifier)
    {
      NOMATCH
3655
      return FALSE; // one member is volatile, the other not -> no match
3656 3657 3658 3659 3660 3661 3662 3663 3664 3665
    }
  }

  // so far the argument list could match, so we need to compare the types of
  // all arguments.
  ArgumentListIterator srcAli(*srcAl),dstAli(*dstAl);
  Argument *srcA,*dstA;
  for (;(srcA=srcAli.current(),dstA=dstAli.current());++srcAli,++dstAli)
  { 
    if (!matchArgument2(srcScope,srcFileScope,srcA,
3666
          dstScope,dstFileScope,dstA)
3667 3668 3669
       )
    {
      NOMATCH
3670
      return FALSE;
3671 3672 3673
    }
  }
  MATCH
3674
  return TRUE; // all arguments match 
3675 3676 3677 3678
}



Dimitri van Heesch's avatar
Dimitri van Heesch committed
3679 3680
// merges the initializer of two argument lists
// pre:  the types of the arguments in the list should match.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3681
void mergeArguments(ArgumentList *srcAl,ArgumentList *dstAl,bool forceNameOverwrite)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3682 3683 3684
{
  //printf("mergeArguments `%s', `%s'\n",
  //    argListToString(srcAl).data(),argListToString(dstAl).data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3685

Dimitri van Heesch's avatar
Dimitri van Heesch committed
3686 3687 3688 3689 3690 3691 3692 3693 3694
  if (srcAl==0 || dstAl==0 || srcAl->count()!=dstAl->count())
  {
    return; // invalid argument lists -> do not merge
  }

  ArgumentListIterator srcAli(*srcAl),dstAli(*dstAl);
  Argument *srcA,*dstA;
  for (;(srcA=srcAli.current(),dstA=dstAli.current());++srcAli,++dstAli)
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3695
    if (srcA->defval.isEmpty() && !dstA->defval.isEmpty())
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3696 3697 3698 3699
    {
      //printf("Defval changing `%s'->`%s'\n",srcA->defval.data(),dstA->defval.data());
      srcA->defval=dstA->defval.copy();
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3700
    else if (!srcA->defval.isEmpty() && dstA->defval.isEmpty())
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3701 3702 3703 3704
    {
      //printf("Defval changing `%s'->`%s'\n",dstA->defval.data(),srcA->defval.data());
      dstA->defval=srcA->defval.copy();
    }
3705

3706
    // fix wrongly detected const or volatile specifiers before merging.
3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718
    // example: "const A *const" is detected as type="const A *" name="const"
    if (srcA->name=="const" || srcA->name=="volatile")
    {
      srcA->type+=" "+srcA->name;
      srcA->name.resize(0);
    }
    if (dstA->name=="const" || dstA->name=="volatile")
    {
      dstA->type+=" "+dstA->name;
      dstA->name.resize(0);
    }

Dimitri van Heesch's avatar
Dimitri van Heesch committed
3719
    if (srcA->type==dstA->type)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3720
    {
3721
      //printf("1. merging %s:%s <-> %s:%s\n",srcA->type.data(),srcA->name.data(),dstA->type.data(),dstA->name.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737
      if (srcA->name.isEmpty() && !dstA->name.isEmpty())
      {
        //printf("type: `%s':=`%s'\n",srcA->type.data(),dstA->type.data());
        //printf("name: `%s':=`%s'\n",srcA->name.data(),dstA->name.data());
        srcA->type = dstA->type.copy();
        srcA->name = dstA->name.copy();
      }
      else if (!srcA->name.isEmpty() && dstA->name.isEmpty())
      {
        //printf("type: `%s':=`%s'\n",dstA->type.data(),srcA->type.data());
        //printf("name: `%s':=`%s'\n",dstA->name.data(),srcA->name.data());
        dstA->type = srcA->type.copy();
        dstA->name = dstA->name.copy();
      }
      else if (!srcA->name.isEmpty() && !dstA->name.isEmpty())
      {
3738
        //printf("srcA->name=%s dstA->name=%s\n",srcA->name.data(),dstA->name.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3739
        if (forceNameOverwrite)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3740
        {
3741
          srcA->name = dstA->name;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3742
        }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3743
        else
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3744
        {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3745 3746
          if (srcA->docs.isEmpty() && !dstA->docs.isEmpty())
          {
3747
            srcA->name = dstA->name;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3748 3749 3750
          }
          else if (!srcA->docs.isEmpty() && dstA->docs.isEmpty())
          {
3751
            dstA->name = srcA->name;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3752
          }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3753
        }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3754
      }
3755
    }
3756 3757
    else
    {
3758 3759 3760
      //printf("2. merging '%s':'%s' <-> '%s':'%s'\n",srcA->type.data(),srcA->name.data(),dstA->type.data(),dstA->name.data());
      srcA->type=srcA->type.stripWhiteSpace();
      dstA->type=dstA->type.stripWhiteSpace();
3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779
      if (srcA->type+" "+srcA->name==dstA->type) // "unsigned long:int" <-> "unsigned long int:bla"
      {
        srcA->type+=" "+srcA->name;
        srcA->name=dstA->name;
      }
      else if (dstA->type+" "+dstA->name==srcA->type) // "unsigned long int bla" <-> "unsigned long int"
      {
        dstA->type+=" "+dstA->name;
        dstA->name=srcA->name;
      }
      else if (srcA->name.isEmpty() && !dstA->name.isEmpty())
      {
        srcA->name = dstA->name;
      }
      else if (dstA->name.isEmpty() && !srcA->name.isEmpty())
      {
        dstA->name = srcA->name;
      }
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797
    int i1=srcA->type.find("::"),
        i2=dstA->type.find("::"),
        j1=srcA->type.length()-i1-2,
        j2=dstA->type.length()-i2-2;
    if (i1!=-1 && i2==-1 && srcA->type.right(j1)==dstA->type)
    {
      //printf("type: `%s':=`%s'\n",dstA->type.data(),srcA->type.data());
      //printf("name: `%s':=`%s'\n",dstA->name.data(),srcA->name.data());
      dstA->type = srcA->type.left(i1+2)+dstA->type;
      dstA->name = dstA->name.copy();
    }
    else if (i1==-1 && i2!=-1 && dstA->type.right(j2)==srcA->type)
    {
      //printf("type: `%s':=`%s'\n",srcA->type.data(),dstA->type.data());
      //printf("name: `%s':=`%s'\n",dstA->name.data(),srcA->name.data());
      srcA->type = dstA->type.left(i2+2)+srcA->type;
      srcA->name = dstA->name.copy();
    }
3798 3799 3800 3801 3802 3803 3804 3805
    if (srcA->docs.isEmpty() && !dstA->docs.isEmpty())
    {
      srcA->docs = dstA->docs.copy();
    }
    else if (dstA->docs.isEmpty() && !srcA->docs.isEmpty())
    {
      dstA->docs = srcA->docs.copy();
    }
3806
    //printf("Merge argument `%s|%s' `%s|%s'\n",
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3807 3808
    //  srcA->type.data(),srcA->name.data(),
    //  dstA->type.data(),dstA->name.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3809 3810 3811
  }
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
3812 3813 3814 3815 3816
static void findMembersWithSpecificName(MemberName *mn,
                                        const char *args,
                                        bool checkStatics,
                                        FileDef *currentFile,
                                        bool checkCV,
3817
                                        const char *forceTagFile,
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3818 3819
                                        QList<MemberDef> &members)
{
3820 3821
  //printf("  Function with global scope name `%s' args=`%s'\n",
  //       mn->memberName(),args);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3822 3823 3824 3825 3826 3827
  MemberListIterator mli(*mn);
  MemberDef *md;
  for (mli.toFirst();(md=mli.current());++mli)
  {
    FileDef  *fd=md->getFileDef();
    GroupDef *gd=md->getGroupDef();
3828 3829
    //printf("  md->name()=`%s' md->args=`%s' fd=%p gd=%p current=%p ref=%s\n",
    //    md->name().data(),args,fd,gd,currentFile,md->getReference().data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3830
    if (
3831
        ((gd && gd->isLinkable()) || (fd && fd->isLinkable()) || md->isReference()) && 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3832
        md->getNamespaceDef()==0 && md->isLinkable() &&
3833 3834
        (!checkStatics || (!md->isStatic() && !md->isDefine()) || 
         currentFile==0 || fd==currentFile) // statics must appear in the same file
3835
       ) 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3836 3837 3838
    {
      bool match=TRUE;
      ArgumentList *argList=0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3839
      if (args && !md->isDefine() && qstrcmp(args,"()")!=0)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3840 3841
      {
        argList=new ArgumentList;
3842
        ArgumentList *mdAl = md->argumentList();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3843 3844
        stringToArgumentList(args,argList);
        match=matchArguments2(
3845
            md->getOuterScope(),fd,mdAl,
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3846 3847 3848 3849
            Doxygen::globalScope,fd,argList,
            checkCV); 
        delete argList; argList=0;
      }
3850
      if (match && (forceTagFile==0 || md->getReference()==forceTagFile)) 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3851 3852 3853 3854 3855 3856 3857 3858
      {
        //printf("Found match!\n");
        members.append(md);
      }
    }
  }
}

3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880
/*!
 * Searches for a member definition given its name `memberName' as a string.
 * memberName may also include a (partial) scope to indicate the scope
 * in which the member is located.
 *
 * The parameter `scName' is a string representing the name of the scope in 
 * which the link was found.
 *
 * In case of a function args contains a string representation of the 
 * argument list. Passing 0 means the member has no arguments. 
 * Passing "()" means any argument list will do, but "()" is preferred.
 *
 * The function returns TRUE if the member is known and documented or
 * FALSE if it is not.
 * If TRUE is returned parameter `md' contains a pointer to the member 
 * definition. Furthermore exactly one of the parameter `cd', `nd', or `fd' 
 * will be non-zero:
 *   - if `cd' is non zero, the member was found in a class pointed to by cd.
 *   - if `nd' is non zero, the member was found in a namespace pointed to by nd.
 *   - if `fd' is non zero, the member was found in the global namespace of
 *     file fd.
 */
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3881
bool getDefs(const QCString &scName,
3882
             const QCString &mbName, 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893
             const char *args,
             MemberDef *&md, 
             ClassDef *&cd, 
             FileDef *&fd, 
             NamespaceDef *&nd, 
             GroupDef *&gd,
             bool forceEmptyScope,
             FileDef *currentFile,
             bool checkCV,
             const char *forceTagFile
            )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3894
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3895
  fd=0, md=0, cd=0, nd=0, gd=0;
3896
  if (mbName.isEmpty()) return FALSE; /* empty name => nothing to link */
3897

3898
  QCString scopeName=scName;
3899
  QCString memberName=mbName;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3900
  scopeName = substitute(scopeName,"\\","::"); // for PHP
3901
  memberName = substitute(memberName,"\\","::"); // for PHP
3902 3903
  //printf("Search for name=%s args=%s in scope=%s forceEmpty=%d\n",
  //          memberName.data(),args,scopeName.data(),forceEmptyScope);
3904

3905
  int is,im=0,pm=0;
3906 3907
  // strip common part of the scope from the scopeName
  while ((is=scopeName.findRev("::"))!=-1 && 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3908 3909 3910
         (im=memberName.find("::",pm))!=-1 &&
          (scopeName.right(scopeName.length()-is-2)==memberName.mid(pm,im-pm))
        )
3911 3912 3913 3914 3915 3916
  {
    scopeName=scopeName.left(is); 
    pm=im+2;
  }
  //printf("result after scope corrections scope=%s name=%s\n",
  //          scopeName.data(),memberName.data());
3917

3918 3919
  QCString mName=memberName;
  QCString mScope;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3920
  if (memberName.left(9)!="operator " && // treat operator conversion methods
3921
      // as a special case
3922 3923
      (im=memberName.findRev("::"))!=-1 && 
      im<(int)memberName.length()-2 // not A::
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3924
     )
3925 3926 3927 3928
  {
    mScope=memberName.left(im); 
    mName=memberName.right(memberName.length()-im-2);
  }
3929

3930 3931 3932 3933
  // handle special the case where both scope name and member scope are equal
  if (mScope==scopeName) scopeName.resize(0);

  //printf("mScope=`%s' mName=`%s'\n",mScope.data(),mName.data());
3934

3935
  MemberName *mn = Doxygen::memberNameSDict->find(mName);
3936
  //printf("mName=%s mn=%p\n",mName.data(),mn);
3937 3938 3939

  if ((!forceEmptyScope || scopeName.isEmpty()) && // this was changed for bug638856, forceEmptyScope => empty scopeName
      mn && !(scopeName.isEmpty() && mScope.isEmpty()))
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3940
  {
3941
    //printf("  >member name '%s' found\n",mName.data());
3942 3943 3944 3945 3946
    int scopeOffset=scopeName.length();
    do
    {
      QCString className = scopeName.left(scopeOffset);
      if (!className.isEmpty() && !mScope.isEmpty())
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3947
      {
3948
        className+="::"+mScope;
3949 3950 3951
      }
      else if (!mScope.isEmpty())
      {
3952
        className=mScope;
3953 3954
      }

3955 3956 3957
      MemberDef *tmd=0;
      ClassDef *fcd=getResolvedClass(Doxygen::globalScope,0,className,&tmd);
      //printf("Trying class scope %s: fcd=%p tmd=%p\n",className.data(),fcd,tmd);
3958
      // todo: fill in correct fileScope!
3959
      if (fcd &&  // is it a documented class
3960
          fcd->isLinkable() 
3961 3962 3963
         )
      {
        //printf("  Found fcd=%p\n",fcd);
3964 3965
        MemberListIterator mmli(*mn);
        MemberDef *mmd;
3966
        int mdist=maxInheritanceDepth; 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3967 3968 3969 3970 3971 3972
        ArgumentList *argList=0;
        if (args)
        {
          argList=new ArgumentList;
          stringToArgumentList(args,argList);
        }
3973
        for (mmli.toFirst();(mmd=mmli.current());++mmli)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3974
        {
3975
          if (!mmd->isStrongEnumValue())
3976
          {
3977 3978 3979 3980 3981 3982 3983 3984
            ArgumentList *mmdAl = mmd->argumentList();
            bool match=args==0 || 
              matchArguments2(mmd->getOuterScope(),mmd->getFileDef(),mmdAl,
                  fcd,fcd->getFileDef(),argList,
                  checkCV
                  );  
            //printf("match=%d\n",match);
            if (match)
3985
            {
3986 3987
              ClassDef *mcd=mmd->getClassDef();
              if (mcd)
3988
              {
3989 3990 3991 3992 3993 3994 3995
                int m=minClassDistance(fcd,mcd);
                if (m<mdist && mcd->isLinkable())
                {
                  mdist=m;
                  cd=mcd;
                  md=mmd;
                }
3996
              }
3997
            }
3998
          }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3999
        }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4000 4001 4002 4003
        if (argList)
        {
          delete argList; argList=0;
        }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4004
        if (mdist==maxInheritanceDepth && args && qstrcmp(args,"()")==0)
4005
          // no exact match found, but if args="()" an arbitrary member will do
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4006
        {
4007
          //printf("  >Searching for arbitrary member\n");
4008
          for (mmli.toFirst();(mmd=mmli.current());++mmli)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4009
          {
4010 4011
            //if (mmd->isLinkable())
            //{
4012 4013
            ClassDef *mcd=mmd->getClassDef();
            //printf("  >Class %s found\n",mcd->name().data());
4014
            if (mcd)
4015
            {
4016 4017 4018 4019 4020 4021 4022 4023
              int m=minClassDistance(fcd,mcd);
              if (m<mdist /* && mcd->isLinkable()*/ )
              {
                //printf("Class distance %d\n",m);
                mdist=m;
                cd=mcd;
                md=mmd;
              }
4024
            }
4025
            //}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4026 4027
          }
        }
4028
        //printf("  >Succes=%d\n",mdist<maxInheritanceDepth);
4029 4030
        if (mdist<maxInheritanceDepth) 
        {
4031
          if (!md->isLinkable() || md->isStrongEnumValue()) 
4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042
          {
            md=0; // avoid returning things we cannot link to
            cd=0;
            return FALSE; // match found, but was not linkable
          }
          else
          {
            gd=md->getGroupDef();
            if (gd) cd=0;
            return TRUE; /* found match */
          }
4043
        }
4044
      } 
4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060
      if (tmd && tmd->isEnumerate() && tmd->isStrong()) // scoped enum
      {
        //printf("Found scoped enum!\n");
        MemberList *tml = tmd->enumFieldList();
        if (tml)
        {
          MemberListIterator tmi(*tml);
          MemberDef *emd;
          for (;(emd=tmi.current());++tmi)
          {
            if (emd->localName()==mName)
            {
              if (emd->isLinkable())
              {
                cd=tmd->getClassDef();
                md=emd;
4061
                return TRUE;
4062 4063 4064 4065 4066
              }
              else
              {
                cd=0;
                md=0;
4067
                return FALSE;
4068 4069 4070 4071 4072
              }
            }
          }
        }
      }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4073
      /* go to the parent scope */
4074 4075 4076
      if (scopeOffset==0)
      {
        scopeOffset=-1;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4077
      }
4078 4079 4080 4081 4082
      else if ((scopeOffset=scopeName.findRev("::",scopeOffset-1))==-1)
      {
        scopeOffset=0;
      }
    } while (scopeOffset>=0);
4083

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4084
  }
4085 4086
  if (mn && scopeName.isEmpty() && mScope.isEmpty()) // Maybe a related function?
  {
4087
    //printf("Global symbol\n");
4088 4089 4090
    MemberListIterator mmli(*mn);
    MemberDef *mmd, *fuzzy_mmd = 0;
    ArgumentList *argList = 0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4091
    bool hasEmptyArgs = args && qstrcmp(args, "()") == 0;
4092 4093 4094 4095 4096 4097

    if (args)
      stringToArgumentList(args, argList = new ArgumentList);

    for (mmli.toFirst(); (mmd = mmli.current()); ++mmli)
    {
4098 4099
      if (!mmd->isLinkable() || (!mmd->isRelated() && !mmd->isForeign()) ||
           !mmd->getClassDef())
4100 4101 4102 4103 4104 4105
        continue;

      if (!args) break;

      QCString className = mmd->getClassDef()->name();

4106 4107
      ArgumentList *mmdAl = mmd->argumentList();
      if (matchArguments2(mmd->getOuterScope(),mmd->getFileDef(),mmdAl,
4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120
            Doxygen::globalScope,mmd->getFileDef(),argList,
            checkCV
            )
         ) break;

      if (!fuzzy_mmd && hasEmptyArgs)
        fuzzy_mmd = mmd;
    }

    if (argList) delete argList, argList = 0;

    mmd = mmd ? mmd : fuzzy_mmd;

4121
    if (mmd && !mmd->isStrongEnumValue())
4122 4123 4124 4125 4126 4127 4128
    {
      md = mmd;
      cd = mmd->getClassDef();
      return TRUE;
    }
  }

4129 4130

  // maybe an namespace, file or group member ?
4131
  //printf("Testing for global symbol scopeName=`%s' mScope=`%s' :: mName=`%s'\n",
4132
  //              scopeName.data(),mScope.data(),mName.data());
4133
  if ((mn=Doxygen::functionNameSDict->find(mName))) // name is known
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4134
  {
4135
    //printf("  >symbol name found\n");
4136 4137 4138
    NamespaceDef *fnd=0;
    int scopeOffset=scopeName.length();
    do
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4139
    {
4140 4141
      QCString namespaceName = scopeName.left(scopeOffset);
      if (!namespaceName.isEmpty() && !mScope.isEmpty())
4142
      {
4143 4144 4145 4146 4147 4148
        namespaceName+="::"+mScope;
      }
      else if (!mScope.isEmpty())
      {
        namespaceName=mScope.copy();
      }
4149
      //printf("Trying namespace %s\n",namespaceName.data());
4150
      if (!namespaceName.isEmpty() && 
4151
          (fnd=Doxygen::namespaceSDict->find(namespaceName)) &&
4152 4153 4154
          fnd->isLinkable()
         )
      {
4155 4156
        //printf("Symbol inside existing namespace `%s' count=%d\n",
        //    namespaceName.data(),mn->count());
4157
        bool found=FALSE;
4158 4159 4160
        MemberListIterator mmli(*mn);
        MemberDef *mmd;
        for (mmli.toFirst();((mmd=mmli.current()) && !found);++mmli)
4161
        {
4162 4163
          //printf("mmd->getNamespaceDef()=%p fnd=%p\n",
          //    mmd->getNamespaceDef(),fnd);
4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183
          MemberDef *emd = mmd->getEnumScope();
          if (emd && emd->isStrong())
          {
            //printf("yes match %s<->%s!\n",mScope.data(),emd->localName().data());
            if (emd->getNamespaceDef()==fnd && 
                rightScopeMatch(mScope,emd->localName()))
            {
              //printf("found it!\n");
              nd=fnd;
              md=mmd;
              found=TRUE;
            }
            else
            {
              md=0;
              cd=0;
              return FALSE;
            }
          }
          else if (mmd->getNamespaceDef()==fnd /* && mmd->isLinkable() */ )
4184 4185 4186
          { // namespace is found
            bool match=TRUE;
            ArgumentList *argList=0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4187
            if (args && qstrcmp(args,"()")!=0)
4188 4189
            {
              argList=new ArgumentList;
4190
              ArgumentList *mmdAl = mmd->argumentList();
4191
              stringToArgumentList(args,argList);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4192
              match=matchArguments2(
4193
                  mmd->getOuterScope(),mmd->getFileDef(),mmdAl,
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4194 4195
                  fnd,mmd->getFileDef(),argList,
                  checkCV); 
4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207
            }
            if (match)
            {
              nd=fnd;
              md=mmd;
              found=TRUE;
            }
            if (args)
            {
              delete argList; argList=0;
            }
          }
4208
        }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4209
        if (!found && args && !qstrcmp(args,"()")) 
4210 4211
          // no exact match found, but if args="()" an arbitrary 
          // member will do
4212
        {
4213
          for (mmli.toFirst();((mmd=mmli.current()) && !found);++mmli)
4214
          {
4215
            if (mmd->getNamespaceDef()==fnd /*&& mmd->isLinkable() */ )
4216 4217 4218 4219 4220 4221 4222
            {
              nd=fnd;
              md=mmd;
              found=TRUE;
            }
          }
        }
4223 4224
        if (found) 
        {
4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236
          if (!md->isLinkable()) 
          {
            md=0; // avoid returning things we cannot link to
            nd=0;
            return FALSE; // match found but not linkable
          }
          else
          {
            gd=md->getGroupDef();
            if (gd && gd->isLinkable()) nd=0; else gd=0;
            return TRUE;
          }
4237
        }
4238
      }
4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249
      else
      {
        //printf("not a namespace\n");
        bool found=FALSE;
        MemberListIterator mmli(*mn);
        MemberDef *mmd;
        for (mmli.toFirst();((mmd=mmli.current()) && !found);++mmli)
        {
          MemberDef *tmd = mmd->getEnumScope();
          //printf("try member %s tmd=%s\n",mmd->name().data(),tmd?tmd->name().data():"<none>");
          int ni=namespaceName.findRev("::");
4250 4251
          //printf("namespaceName=%s ni=%d\n",namespaceName.data(),ni);
          bool notInNS = tmd && ni==-1 && tmd->getNamespaceDef()==0 && (mScope.isEmpty() || mScope==tmd->name());
4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268
          bool sameNS  = tmd && tmd->getNamespaceDef() && namespaceName.left(ni)==tmd->getNamespaceDef()->name();
          //printf("notInNS=%d sameNS=%d\n",notInNS,sameNS);
          if (tmd && tmd->isStrong() && // C++11 enum class
              (notInNS || sameNS) &&
              namespaceName.length()>0  // enum is part of namespace so this should not be empty
             )
          {
            md=mmd;
            fd=mmd->getFileDef();
            gd=mmd->getGroupDef();
            if (gd && gd->isLinkable()) fd=0; else gd=0;
            //printf("Found scoped enum %s fd=%p gd=%p\n",
            //    mmd->name().data(),fd,gd);
            return TRUE;
          }
        }
      }
4269 4270 4271 4272 4273 4274 4275 4276 4277
      if (scopeOffset==0)
      {
        scopeOffset=-1;
      }
      else if ((scopeOffset=scopeName.findRev("::",scopeOffset-1))==-1)
      {
        scopeOffset=0;
      }
    } while (scopeOffset>=0);
4278 4279 4280 4281

    //else // no scope => global function
    {
      QList<MemberDef> members;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4282
      // search for matches with strict static checking
4283
      findMembersWithSpecificName(mn,args,TRUE,currentFile,checkCV,forceTagFile,members);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4284 4285 4286
      if (members.count()==0) // nothing found
      {
        // search again without strict static checking
4287
        findMembersWithSpecificName(mn,args,FALSE,currentFile,checkCV,forceTagFile,members);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4288
      }
4289
      //printf("found %d members\n",members.count());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4290
      if (members.count()!=1 && args && !qstrcmp(args,"()"))
4291
      {
4292
        // no exact match found, but if args="()" an arbitrary
4293
        // member will do
4294 4295
        MemberListIterator mni(*mn);
        for (mni.toLast();(md=mni.current());--mni)
4296 4297 4298 4299 4300
        {
          //printf("Found member `%s'\n",md->name().data());
          //printf("member is linkable md->name()=`%s'\n",md->name().data());
          fd=md->getFileDef();
          gd=md->getGroupDef();
4301
          MemberDef *tmd = md->getEnumScope();
4302
          if (
4303 4304
              (gd && gd->isLinkable()) || (fd && fd->isLinkable()) ||
              (tmd && tmd->isStrong())
4305 4306 4307 4308
             )
          {
            members.append(md);
          }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4309
        }
4310 4311
      }
      //printf("found %d candidate members\n",members.count());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4312
      if (members.count()>0) // at least one match
4313
      {
4314 4315 4316
        if (currentFile)
        {
          //printf("multiple results; pick one from file:%s\n", currentFile->name().data());
4317 4318
          QListIterator<MemberDef> mit(members);
          for (mit.toFirst();(md=mit.current());++mit)
4319 4320 4321 4322 4323
          {
            if (md->getFileDef() && md->getFileDef()->name() == currentFile->name()) 
            {
              break; // found match in the current file
            }
4324
          }
4325 4326
          if (!md) // member not in the current file
          {
4327
            md=members.getLast();
4328
          }
4329 4330
        }
        else
4331
        {
4332
          md=members.getLast();
4333
        }
4334
      }
4335 4336
      if (md && (md->getEnumScope()==0 || !md->getEnumScope()->isStrong())) 
           // found a matching global member, that is not a scoped enum value (or uniquely matches)
4337 4338 4339 4340 4341 4342
      {
        fd=md->getFileDef();
        gd=md->getGroupDef();
        //printf("fd=%p gd=%p gd->isLinkable()=%d\n",fd,gd,gd->isLinkable());
        if (gd && gd->isLinkable()) fd=0; else gd=0;
        return TRUE;
4343
      }
4344
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4345
  }
4346

4347
  // no nothing found
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4348 4349 4350
  return FALSE;
}

4351 4352
/*!
 * Searches for a scope definition given its name as a string via parameter
4353
 * `scope`. 
4354
 *
4355 4356
 * The parameter `docScope` is a string representing the name of the scope in 
 * which the `scope` string was found.
4357 4358 4359
 *
 * The function returns TRUE if the scope is known and documented or
 * FALSE if it is not.
4360
 * If TRUE is returned exactly one of the parameter `cd`, `nd` 
4361
 * will be non-zero:
4362 4363
 *   - if `cd` is non zero, the scope was a class pointed to by cd.
 *   - if `nd` is non zero, the scope was a namespace pointed to by nd.
4364
 */
4365
static bool getScopeDefs(const char *docScope,const char *scope,
4366
    ClassDef *&cd, NamespaceDef *&nd)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4367
{
4368 4369 4370 4371
  cd=0;nd=0;

  QCString scopeName=scope;
  //printf("getScopeDefs: docScope=`%s' scope=`%s'\n",docScope,scope);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4372
  if (scopeName.isEmpty()) return FALSE;
4373

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4374 4375 4376 4377 4378 4379
  bool explicitGlobalScope=FALSE;
  if (scopeName.at(0)==':' && scopeName.at(1)==':')
  {
    scopeName=scopeName.right(scopeName.length()-2);  
    explicitGlobalScope=TRUE;
  }
4380

4381
  QCString docScopeName=docScope;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4382
  int scopeOffset=explicitGlobalScope ? 0 : docScopeName.length();
4383 4384

  do // for each possible docScope (from largest to and including empty)
4385
  {
4386 4387
    QCString fullName=scopeName.copy();
    if (scopeOffset>0) fullName.prepend(docScopeName.left(scopeOffset)+"::");
4388

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4389
    if (((cd=getClass(fullName)) ||         // normal class
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4390 4391
         (cd=getClass(fullName+"-p")) //||    // ObjC protocol
         //(cd=getClass(fullName+"-g"))       // C# generic
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4392
        ) && cd->isLinkable())
4393 4394 4395
    {
      return TRUE; // class link written => quit 
    }
4396
    else if ((nd=Doxygen::namespaceSDict->find(fullName)) && nd->isLinkable())
4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408
    {
      return TRUE; // namespace link written => quit 
    }
    if (scopeOffset==0)
    {
      scopeOffset=-1;
    }
    else if ((scopeOffset=docScopeName.findRev("::",scopeOffset-1))==-1)
    {
      scopeOffset=0;
    }
  } while (scopeOffset>=0);
4409

4410
  return FALSE;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4411 4412
}

4413 4414
static bool isLowerCase(QCString &s)
{
4415
  uchar *p=(uchar*)s.data();
4416 4417 4418 4419 4420
  if (p==0) return TRUE;
  int c;
  while ((c=*p++)) if (!islower(c)) return FALSE;
  return TRUE; 
}
4421 4422 4423 4424 4425

/*! Returns an object to reference to given its name and context 
 *  @post return value TRUE implies *resContext!=0 or *resMember!=0
 */
bool resolveRef(/* in */  const char *scName,
4426 4427 4428
    /* in */  const char *name,
    /* in */  bool inSeeBlock,
    /* out */ Definition **resContext,
4429
    /* out */ MemberDef  **resMember,
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4430
    bool lookForSpecialization,
4431 4432
    FileDef *currentFile,
    bool checkScope
4433
    )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4434
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4435
  //printf("resolveRef(scope=%s,name=%s,inSeeBlock=%d)\n",scName,name,inSeeBlock);
4436
  QCString tsName = name;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4437
  //bool memberScopeFirst = tsName.find('#')!=-1;
4438
  QCString fullName = substitute(tsName,"#","::");
4439
  if (fullName.find("anonymous_namespace{")==-1)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4440 4441 4442 4443 4444 4445 4446
  {
    fullName = removeRedundantWhiteSpace(substitute(fullName,".","::"));
  }
  else
  {
    fullName = removeRedundantWhiteSpace(fullName);
  }
4447

4448
  int bracePos=findParameterList(fullName);
4449 4450
  int endNamePos=bracePos!=-1 ? bracePos : fullName.length();
  int scopePos=fullName.findRev("::",endNamePos);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4451 4452 4453 4454 4455
  bool explicitScope = fullName.left(2)=="::" &&   // ::scope or #scope
                       (scopePos>2 ||              // ::N::A
                        tsName.left(2)=="::" ||    // ::foo in local scope
                        scName==0                  // #foo  in global scope
                       );
4456 4457 4458 4459 4460

  // default result values
  *resContext=0;
  *resMember=0;

4461
  if (bracePos==-1) // simple name
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4462
  {
4463 4464
    ClassDef *cd=0;
    NamespaceDef *nd=0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4465

4466 4467 4468 4469 4470 4471
    // the following if() was commented out for releases in the range 
    // 1.5.2 to 1.6.1, but has been restored as a result of bug report 594787.
    if (!inSeeBlock && scopePos==-1 && isLowerCase(tsName))
    { // link to lower case only name => do not try to autolink 
      return FALSE;
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4472

4473
    //printf("scName=%s fullName=%s\n",scName,fullName.data());
4474

4475
    // check if this is a class or namespace reference
4476
    if (scName!=fullName && getScopeDefs(scName,fullName,cd,nd))
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4477
    {
4478 4479
      if (cd) // scope matches that of a class
      {
4480
        *resContext = cd;
4481 4482 4483
      }
      else // scope matches that of a namespace
      {
4484 4485
        ASSERT(nd!=0);
        *resContext = nd;
4486
      }
4487
      return TRUE;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4488
    }
4489 4490
    else if (scName==fullName || (!inSeeBlock && scopePos==-1)) 
      // nothing to link => output plain text
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4491
    {
4492 4493 4494
      //printf("found scName=%s fullName=%s scName==fullName=%d "
      //    "inSeeBlock=%d scopePos=%d!\n",
      //    scName,fullName.data(),scName==fullName,inSeeBlock,scopePos);
4495
      return FALSE;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4496
    }
4497
    // continue search...
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4498
  }
4499

4500
  // extract userscope+name
4501
  QCString nameStr=fullName.left(endNamePos);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4502
  if (explicitScope) nameStr=nameStr.mid(2);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4503 4504

  // extract arguments
4505
  QCString argsStr;
4506
  if (bracePos!=-1) argsStr=fullName.right(fullName.length()-bracePos);
4507

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4508 4509 4510
  // strip template specifier
  // TODO: match against the correct partial template instantiation 
  int templPos=nameStr.find('<');
4511
  bool tryUnspecializedVersion = FALSE;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4512 4513 4514
  if (templPos!=-1 && nameStr.find("operator")==-1)
  {
    int endTemplPos=nameStr.findRev('>');
4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525
    if (endTemplPos!=-1)
    {
      if (!lookForSpecialization)
      {
        nameStr=nameStr.left(templPos)+nameStr.right(nameStr.length()-endTemplPos-1);
      }
      else
      {
        tryUnspecializedVersion = TRUE;
      }
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4526
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4527

4528 4529
  QCString scopeStr=scName;

4530 4531 4532
  MemberDef    *md = 0;
  ClassDef     *cd = 0;
  FileDef      *fd = 0;
4533
  NamespaceDef *nd = 0;
4534
  GroupDef     *gd = 0;
4535 4536

  // check if nameStr is a member or global.
4537 4538
  //printf("getDefs(scope=%s,name=%s,args=%s checkScope=%d)\n",
  //    scopeStr.data(),nameStr.data(),argsStr.data(),checkScope);
4539
  if (getDefs(scopeStr,nameStr,argsStr,
4540
        md,cd,fd,nd,gd,
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4541 4542
        //scopePos==0 && !memberScopeFirst, // forceEmptyScope
        explicitScope, // replaces prev line due to bug 600829
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4543
        currentFile,
4544
        TRUE                              // checkCV
4545
        )
4546
     )
4547
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4548 4549
    //printf("after getDefs checkScope=%d nameStr=%s cd=%p nd=%p\n",checkScope,nameStr.data(),cd,nd);
    if (checkScope && md && md->getOuterScope()==Doxygen::globalScope && 
4550
        !md->isStrongEnumValue() &&
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4551
        (!scopeStr.isEmpty() || nameStr.find("::")>0))
4552 4553 4554 4555
    {
      // we did find a member, but it is a global one while we were explicitly 
      // looking for a scoped variable. See bug 616387 for an example why this check is needed.
      // note we do need to support autolinking to "::symbol" hence the >0
4556
      //printf("not global member!\n");
4557 4558 4559 4560
      *resContext=0;
      *resMember=0;
      return FALSE;
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4561
    //printf("after getDefs md=%p cd=%p fd=%p nd=%p gd=%p\n",md,cd,fd,nd,gd);
4562 4563
    if      (md) { *resMember=md; *resContext=md; }
    else if (cd) *resContext=cd;
4564 4565 4566 4567
    else if (nd) *resContext=nd;
    else if (fd) *resContext=fd;
    else if (gd) *resContext=gd;
    else         { *resContext=0; *resMember=0; return FALSE; }
4568 4569
    //printf("member=%s (md=%p) anchor=%s linkable()=%d context=%s\n",
    //    md->name().data(),md,md->anchor().data(),md->isLinkable(),(*resContext)->name().data());
4570 4571
    return TRUE;
  }
4572
  else if (inSeeBlock && !nameStr.isEmpty() && (gd=Doxygen::groupSDict->find(nameStr)))
4573 4574 4575 4576
  { // group link
    *resContext=gd;
    return TRUE;
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4577 4578 4579 4580 4581 4582 4583 4584 4585 4586
  else if (tsName.find('.')!=-1) // maybe a link to a file
  {
    bool ambig;
    fd=findFileDef(Doxygen::inputNameDict,tsName,ambig);
    if (fd && !ambig)
    {
      *resContext=fd;
      return TRUE;
    }
  }
4587

4588 4589
  if (tryUnspecializedVersion)
  {
4590
    return resolveRef(scName,name,inSeeBlock,resContext,resMember,FALSE,0,checkScope);
4591
  }
4592 4593 4594 4595 4596 4597 4598 4599
  if (bracePos!=-1) // Try without parameters as well, could be a contructor invocation
  {
    *resContext=getClass(fullName.left(bracePos));
    if (*resContext)
    {
      return TRUE;
    }
  }
4600
  //printf("resolveRef: %s not found!\n",name);
4601

4602 4603 4604
  return FALSE;
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4605
QCString linkToText(SrcLangExt lang,const char *link,bool isFileName)
4606
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4607
  //static bool optimizeOutputJava = Config_getBool("OPTIMIZE_OUTPUT_JAVA");
4608 4609 4610 4611 4612 4613
  QCString result=link;
  if (!result.isEmpty())
  {
    // replace # by ::
    result=substitute(result,"#","::");
    // replace . by ::
4614
    if (!isFileName && result.find('<')==-1) result=substitute(result,".","::");
4615
    // strip leading :: prefix if present
4616 4617 4618 4619
    if (result.at(0)==':' && result.at(1)==':')
    {
      result=result.right(result.length()-2);
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4620 4621
    QCString sep = getLanguageSpecificSeparator(lang);
    if (sep!="::")
4622
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4623
      result=substitute(result,"::",sep);
4624 4625 4626 4627 4628
    }
  }
  return result;
}

4629
#if 0
4630
/*
4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641
 * generate a reference to a class, namespace or member.
 * `scName' is the name of the scope that contains the documentation 
 * string that is returned.
 * `name' is the name that we want to link to.
 * `name' may have five formats:
 *    1) "ScopeName"
 *    2) "memberName()"    one of the (overloaded) function or define 
 *                         with name memberName.
 *    3) "memberName(...)" a specific (overloaded) function or define 
 *                         with name memberName
 *    4) "::name           a global variable or define
4642
 *    4) "\#memberName     member variable, global variable or define
4643 4644 4645
 *    5) ("ScopeName::")+"memberName()" 
 *    6) ("ScopeName::")+"memberName(...)" 
 *    7) ("ScopeName::")+"memberName" 
4646
 * instead of :: the \# symbol may also be used.
4647 4648 4649
 */

bool generateRef(OutputDocInterface &od,const char *scName,
4650
    const char *name,bool inSeeBlock,const char *rt)
4651
{
4652
  //printf("generateRef(scName=%s,name=%s,inSee=%d,rt=%s)\n",scName,name,inSeeBlock,rt);
4653

4654 4655
  Definition *compound;
  MemberDef *md;
4656

4657
  // create default link text
4658
  QCString linkText = linkToText(rt,FALSE);
4659 4660 4661

  if (resolveRef(scName,name,inSeeBlock,&compound,&md))
  {
4662
    if (md && md->isLinkable()) // link to member
4663
    {
4664
      od.writeObjectLink(md->getReference(),
4665 4666
          md->getOutputFileBase(),
          md->anchor(),linkText);
4667
      // generate the page reference (for LaTeX)
4668
      if (!md->isReference())
4669
      {
4670
        writePageRef(od,md->getOutputFileBase(),md->anchor());
4671
      }
4672
      return TRUE;
4673
    }
4674
    else if (compound && compound->isLinkable()) // link to compound
4675
    {
4676 4677 4678 4679
      if (rt==0 && compound->definitionType()==Definition::TypeGroup)
      {
        linkText=((GroupDef *)compound)->groupTitle();
      }
4680 4681 4682 4683
      if (compound && compound->definitionType()==Definition::TypeFile)
      {
        linkText=linkToText(rt,TRUE);
      }
4684
      od.writeObjectLink(compound->getReference(),
4685 4686
          compound->getOutputFileBase(),
          0,linkText);
4687 4688 4689 4690
      if (!compound->isReference())
      {
        writePageRef(od,compound->getOutputFileBase(),0);
      }
4691
      return TRUE;
4692
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4693
  }
4694 4695
  od.docify(linkText);
  return FALSE;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4696
}
4697
#endif
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4698

4699
bool resolveLink(/* in */ const char *scName,
4700
    /* in */ const char *lr,
4701
    /* in */ bool /*inSeeBlock*/,
4702 4703 4704
    /* out */ Definition **resContext,
    /* out */ QCString &resAnchor
    )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4705
{
4706
  *resContext=0;
4707

4708
  QCString linkRef=lr;
4709
  //printf("ResolveLink linkRef=%s inSee=%d\n",lr,inSeeBlock);
4710
  FileDef  *fd;
4711
  GroupDef *gd;
4712
  PageDef  *pd;
4713
  ClassDef *cd;
4714
  DirDef   *dir;
4715
  NamespaceDef *nd;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4716
  SectionInfo *si=0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4717
  bool ambig;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4718
  if (linkRef.isEmpty()) // no reference name!
4719 4720 4721
  {
    return FALSE;
  }
4722
  else if ((pd=Doxygen::pageSDict->find(linkRef))) // link to a page
4723
  {
4724
    GroupDef *gd = pd->getGroupDef();
4725 4726
    if (gd)
    {
4727
      if (!pd->name().isEmpty()) si=Doxygen::sectionDict->find(pd->name());
4728 4729
      *resContext=gd;
      if (si) resAnchor = si->label;
4730 4731 4732
    }
    else
    {
4733
      *resContext=pd;
4734
    }
4735 4736
    return TRUE;
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4737 4738 4739 4740 4741 4742
  else if ((si=Doxygen::sectionDict->find(linkRef)))
  {
    *resContext=si->definition;
    resAnchor = si->label;
    return TRUE;
  }
4743
  else if ((pd=Doxygen::exampleSDict->find(linkRef))) // link to an example
4744
  {
4745
    *resContext=pd;
4746 4747
    return TRUE;
  }
4748
  else if ((gd=Doxygen::groupSDict->find(linkRef))) // link to a group
4749
  {
4750 4751 4752 4753 4754 4755 4756
    *resContext=gd;
    return TRUE;
  }
  else if ((fd=findFileDef(Doxygen::inputNameDict,linkRef,ambig)) // file link
      && fd->isLinkable())
  {
    *resContext=fd;
4757
    return TRUE;
4758
  }
4759 4760 4761
  else if ((cd=getClass(linkRef))) // class link
  {
    *resContext=cd;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4762
    resAnchor=cd->anchor();
4763 4764 4765
    return TRUE;
  }
  else if ((cd=getClass(linkRef+"-p"))) // Obj-C protocol link
4766 4767
  {
    *resContext=cd;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4768
    resAnchor=cd->anchor();
4769 4770
    return TRUE;
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4771 4772 4773 4774 4775 4776
//  else if ((cd=getClass(linkRef+"-g"))) // C# generic link
//  {
//    *resContext=cd;
//    resAnchor=cd->anchor();
//    return TRUE;
//  }
4777
  else if ((nd=Doxygen::namespaceSDict->find(linkRef)))
4778 4779 4780 4781
  {
    *resContext=nd;
    return TRUE;
  }
4782
  else if ((dir=Doxygen::directories->find(QFileInfo(linkRef).absFilePath().utf8()+"/"))
4783 4784 4785 4786 4787
      && dir->isLinkable()) // TODO: make this location independent like filedefs
  {
    *resContext=dir;
    return TRUE;
  }
4788
  else // probably a member reference
4789
  {
4790
    MemberDef *md;
4791
    bool res = resolveRef(scName,lr,TRUE,resContext,&md);
4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805
    if (md) resAnchor=md->anchor();
    return res;
  }
}


//----------------------------------------------------------------------
// General function that generates the HTML code for a reference to some
// file, class or member from text `lr' within the context of class `clName'. 
// This link has the text 'lt' (if not 0), otherwise `lr' is used as a
// basis for the link's text.
// returns TRUE if a link could be generated.

bool generateLink(OutputDocInterface &od,const char *clName,
4806
    const char *lr,bool inSeeBlock,const char *lt)
4807
{
4808
  //printf("generateLink(clName=%s,lr=%s,lr=%s)\n",clName,lr,lt);
4809
  Definition *compound;
4810
  //PageDef *pageDef=0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4811
  QCString anchor,linkText=linkToText(SrcLangExt_Unknown,lt,FALSE);
4812
  //printf("generateLink linkText=%s\n",linkText.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4813
  if (resolveLink(clName,lr,inSeeBlock,&compound,anchor))
4814
  {
4815
    if (compound) // link to compound
4816
    {
4817 4818 4819
      if (lt==0 && anchor.isEmpty() &&                      /* compound link */
          compound->definitionType()==Definition::TypeGroup /* is group */ 
         )
4820
      {
4821
        linkText=((GroupDef *)compound)->groupTitle(); // use group's title as link
4822
      }
4823 4824
      else if (compound->definitionType()==Definition::TypeFile)
      {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4825
        linkText=linkToText(compound->getLanguage(),lt,TRUE); 
4826
      }
4827
      od.writeObjectLink(compound->getReference(),
4828
          compound->getOutputFileBase(),anchor,linkText);
4829 4830 4831 4832
      if (!compound->isReference())
      {
        writePageRef(od,compound->getOutputFileBase(),anchor);
      }
4833
    }
4834 4835
    else
    {
4836
      err("%s:%d: Internal error: resolveLink successful but no compound found!",__FILE__,__LINE__);
4837
    }
4838 4839
    return TRUE;
  }
4840
  else // link could not be found
4841
  {
4842 4843
    od.docify(linkText);
    return FALSE;
4844
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4845 4846
}

4847
void generateFileRef(OutputDocInterface &od,const char *name,const char *text)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4848
{
4849
  //printf("generateFileRef(%s,%s)\n",name,text);
4850
  QCString linkText = text ? text : name;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4851 4852 4853
  //FileInfo *fi;
  FileDef *fd;
  bool ambig;
4854
  if ((fd=findFileDef(Doxygen::inputNameDict,name,ambig)) && 
4855
      fd->isLinkable()) 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4856
    // link to documented input file
4857
    od.writeObjectLink(fd->getReference(),fd->getOutputFileBase(),0,linkText);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4858
  else
4859
    od.docify(linkText); 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4860 4861 4862 4863
}

//----------------------------------------------------------------------

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4864
#if 0
4865
QCString substituteClassNames(const QCString &s)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4866 4867
{
  int i=0,l,p;
4868
  QCString result;
4869
  if (s.isEmpty()) return result;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4870 4871 4872
  QRegExp r("[a-z_A-Z][a-z_A-Z0-9]*");
  while ((p=r.match(s,i,&l))!=-1)
  {
4873
    QCString *subst;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887
    if (p>i) result+=s.mid(i,p-i);
    if ((subst=substituteDict[s.mid(p,l)]))
    {
      result+=*subst;
    }
    else
    {
      result+=s.mid(p,l);
    }
    i=p+l;
  }
  result+=s.mid(i,s.length()-i);
  return result;
}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4888
#endif
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4889 4890 4891

//----------------------------------------------------------------------

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4892
/** Cache element for the file name to FileDef mapping cache. */
4893 4894 4895 4896 4897 4898 4899 4900 4901
struct FindFileCacheElem
{
  FindFileCacheElem(FileDef *fd,bool ambig) : fileDef(fd), isAmbig(ambig) {}
  FileDef *fileDef;
  bool isAmbig;
};

static QCache<FindFileCacheElem> g_findFileDefCache(5000);

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4902 4903 4904
FileDef *findFileDef(const FileNameDict *fnDict,const char *n,bool &ambig)
{
  ambig=FALSE;
4905 4906 4907 4908 4909 4910 4911 4912
  if (n==0) return 0;

  QCString key;
  key.sprintf("%p:",fnDict);
  key+=n;

  g_findFileDefCache.setAutoDelete(TRUE);
  FindFileCacheElem *cachedResult = g_findFileDefCache.find(key);
4913
  //printf("key=%s cachedResult=%p\n",key.data(),cachedResult);
4914 4915 4916
  if (cachedResult)
  {
    ambig = cachedResult->isAmbig;
4917
    //printf("cached: fileDef=%p\n",cachedResult->fileDef);
4918 4919 4920 4921 4922 4923
    return cachedResult->fileDef;
  }
  else
  {
    cachedResult = new FindFileCacheElem(0,FALSE);
  }
4924

4925
  QCString name=QDir::cleanDirPath(n).utf8();
4926
  QCString path;
4927 4928 4929 4930
  int slashPos;
  FileName *fn;
  if (name.isEmpty()) goto exit;
  slashPos=QMAX(name.findRev('/'),name.findRev('\\'));
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4931 4932 4933 4934
  if (slashPos!=-1)
  {
    path=name.left(slashPos+1);
    name=name.right(name.length()-slashPos-1); 
4935
    //printf("path=%s name=%s\n",path.data(),name.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4936
  }
4937
  if (name.isEmpty()) goto exit;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4938 4939
  if ((fn=(*fnDict)[name]))
  {
4940
    //printf("fn->count()=%d\n",fn->count());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4941 4942
    if (fn->count()==1)
    {
4943
      FileDef *fd = fn->getFirst();
4944 4945 4946 4947 4948 4949
#if defined(_WIN32) || defined(__MACOSX__) // Windows or MacOSX
      bool isSamePath = fd->getPath().right(path.length()).lower()==path.lower();
#else // Unix
      bool isSamePath = fd->getPath().right(path.length())==path;
#endif
      if (path.isEmpty() || isSamePath)
4950
      {
4951 4952
        cachedResult->fileDef = fd;
        g_findFileDefCache.insert(key,cachedResult);
4953
        //printf("=1 ===> add to cache %p\n",fd);
4954 4955
        return fd;
      }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4956
    }
4957
    else // file name alone is ambiguous
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4958 4959
    {
      int count=0;
4960 4961
      FileNameIterator fni(*fn);
      FileDef *fd;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4962
      FileDef *lastMatch=0;
4963
      QCString pathStripped = stripFromIncludePath(path);
4964
      for (fni.toFirst();(fd=fni.current());++fni)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4965
      {
4966
        QCString fdStripPath = stripFromIncludePath(fd->getPath());
4967
        if (path.isEmpty() || fdStripPath.right(pathStripped.length())==pathStripped) 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4968 4969 4970 4971 4972
        { 
          count++; 
          lastMatch=fd; 
        }
      }
4973
      //printf(">1 ===> add to cache %p\n",fd);
4974

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4975
      ambig=(count>1);
4976 4977 4978
      cachedResult->isAmbig = ambig;
      cachedResult->fileDef = lastMatch;
      g_findFileDefCache.insert(key,cachedResult);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4979 4980 4981
      return lastMatch;
    }
  }
4982 4983 4984 4985
  else
  {
    //printf("not found!\n");
  }
4986
exit:
4987
  //printf("0  ===> add to cache %p: %s\n",cachedResult,n);
4988
  g_findFileDefCache.insert(key,cachedResult);
4989
  //delete cachedResult;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4990 4991 4992 4993 4994
  return 0;
}

//----------------------------------------------------------------------

4995
QCString showFileDefMatches(const FileNameDict *fnDict,const char *n)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4996
{
4997
  QCString result;
4998 4999
  QCString name=n;
  QCString path;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5000 5001 5002 5003 5004 5005 5006 5007 5008
  int slashPos=QMAX(name.findRev('/'),name.findRev('\\'));
  if (slashPos!=-1)
  {
    path=name.left(slashPos+1);
    name=name.right(name.length()-slashPos-1); 
  }
  FileName *fn;
  if ((fn=(*fnDict)[name]))
  {
5009 5010 5011
    FileNameIterator fni(*fn);
    FileDef *fd;
    for (fni.toFirst();(fd=fni.current());++fni)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5012
    {
5013
      if (path.isEmpty() || fd->getPath().right(path.length())==path)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5014
      {
5015
        result+="   "+fd->absFilePath()+"\n";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5016 5017 5018
      }
    }
  }
5019
  return result;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5020 5021
}

5022 5023
//----------------------------------------------------------------------

Dimitri van Heesch's avatar
Dimitri van Heesch committed
5024 5025
QCString substituteKeywords(const QCString &s,const char *title,
         const char *projName,const char *projNum,const char *projBrief)
5026
{
5027
  QCString result = s;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5028 5029 5030
  if (title) result = substitute(result,"$title",title);
  result = substitute(result,"$datetime",dateToString(TRUE));
  result = substitute(result,"$date",dateToString(FALSE));
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5031
  result = substitute(result,"$year",yearToString());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5032
  result = substitute(result,"$doxygenversion",versionString);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5033 5034 5035
  result = substitute(result,"$projectname",projName);
  result = substitute(result,"$projectnumber",projNum);
  result = substitute(result,"$projectbrief",projBrief);
5036
  result = substitute(result,"$projectlogo",stripPath(Config_getString("PROJECT_LOGO")));
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5037
  return result;
5038
}
5039

Dimitri van Heesch's avatar
Dimitri van Heesch committed
5040 5041
//----------------------------------------------------------------------

5042
/*! Returns the character index within \a name of the first prefix
5043
 *  in Config_getList("IGNORE_PREFIX") that matches \a name at the left hand side,
5044 5045 5046 5047
 *  or zero if no match was found
 */ 
int getPrefixIndex(const QCString &name)
{
5048
  if (name.isEmpty()) return 0;
5049
  static QStrList &sl = Config_getList("IGNORE_PREFIX");
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5050
  char *s = sl.first();
5051 5052 5053
  while (s)
  {
    const char *ps=s;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5054
    const char *pd=name.data();
5055 5056 5057 5058
    int i=0;
    while (*ps!=0 && *pd!=0 && *ps==*pd) ps++,pd++,i++;
    if (*ps==0 && *pd!=0)
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5059
      return i;
5060
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5061
    s = sl.next();
5062
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5063
  return 0;
5064
}
5065 5066 5067 5068 5069

//----------------------------------------------------------------------------

static void initBaseClassHierarchy(BaseClassList *bcl)
{
5070
  if (bcl==0) return;
5071 5072 5073 5074
  BaseClassListIterator bcli(*bcl);
  for ( ; bcli.current(); ++bcli)
  {
    ClassDef *cd=bcli.current()->classDef;
5075
    if (cd->baseClasses()==0) // no base classes => new root
5076 5077 5078 5079 5080 5081
    {
      initBaseClassHierarchy(cd->baseClasses());
    }
    cd->visited=FALSE;
  }
}
5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109
//----------------------------------------------------------------------------

bool classHasVisibleChildren(ClassDef *cd)
{
  BaseClassList *bcl;

  if (cd->getLanguage()==SrcLangExt_VHDL) // reverse baseClass/subClass relation
  {
    if (cd->baseClasses()==0) return FALSE;
    bcl=cd->baseClasses();
  }
  else 
  {
    if (cd->subClasses()==0) return FALSE;
    bcl=cd->subClasses();
  }

  BaseClassListIterator bcli(*bcl);
  for ( ; bcli.current() ; ++bcli)
  {
    if (bcli.current()->classDef->isVisibleInHierarchy())
    {
      return TRUE;
    }
  }
  return FALSE;
}

5110 5111 5112

//----------------------------------------------------------------------------

Dimitri van Heesch's avatar
Dimitri van Heesch committed
5113
void initClassHierarchy(ClassSDict *cl)
5114
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5115
  ClassSDict::Iterator cli(*cl);
5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127
  ClassDef *cd;
  for ( ; (cd=cli.current()); ++cli)
  {
    cd->visited=FALSE;
    initBaseClassHierarchy(cd->baseClasses());
  }
}

//----------------------------------------------------------------------------

bool hasVisibleRoot(BaseClassList *bcl)
{
5128
  if (bcl)
5129
  {
5130 5131 5132 5133 5134 5135 5136
    BaseClassListIterator bcli(*bcl);
    for ( ; bcli.current(); ++bcli)
    {
      ClassDef *cd=bcli.current()->classDef;
      if (cd->isVisibleInHierarchy()) return TRUE;
      hasVisibleRoot(cd->baseClasses());
    }
5137 5138 5139 5140
  }
  return FALSE;
}

5141 5142
//----------------------------------------------------------------------

5143
// note that this function is not reentrant due to the use of static growBuf!
5144
QCString escapeCharsInString(const char *name,bool allowDots,bool allowUnderscore)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5145
{
5146
  static bool caseSenseNames = Config_getBool("CASE_SENSE_NAMES");
5147
  static bool allowUnicodeNames = Config_getBool("ALLOW_UNICODE_NAMES");
5148 5149
  static GrowBuf growBuf;
  growBuf.clear();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5150 5151 5152 5153 5154 5155
  char c;
  const char *p=name;
  while ((c=*p++)!=0)
  {
    switch(c)
    {
5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178
      case '_': if (allowUnderscore) growBuf.addChar('_'); else growBuf.addStr("__"); break;
      case '-': growBuf.addChar('-');  break;
      case ':': growBuf.addStr("_1"); break;
      case '/': growBuf.addStr("_2"); break;
      case '<': growBuf.addStr("_3"); break;
      case '>': growBuf.addStr("_4"); break;
      case '*': growBuf.addStr("_5"); break;
      case '&': growBuf.addStr("_6"); break;
      case '|': growBuf.addStr("_7"); break;
      case '.': if (allowDots) growBuf.addChar('.'); else growBuf.addStr("_8"); break;
      case '!': growBuf.addStr("_9"); break;
      case ',': growBuf.addStr("_00"); break;
      case ' ': growBuf.addStr("_01"); break;
      case '{': growBuf.addStr("_02"); break;
      case '}': growBuf.addStr("_03"); break;
      case '?': growBuf.addStr("_04"); break;
      case '^': growBuf.addStr("_05"); break;
      case '%': growBuf.addStr("_06"); break;
      case '(': growBuf.addStr("_07"); break;
      case ')': growBuf.addStr("_08"); break;
      case '+': growBuf.addStr("_09"); break;
      case '=': growBuf.addStr("_0A"); break;
      case '$': growBuf.addStr("_0B"); break;
5179
      case '\\': growBuf.addStr("_0C"); break;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5180
      default: 
5181 5182 5183
                if (c<0)
                {
                  char ids[5];
5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233
                  const unsigned char uc = (unsigned char)c;
                  bool doEscape = TRUE;
                  if (allowUnicodeNames && uc <= 0xf7)
                  {
                    const char* pt = p;
                    ids[ 0 ] = c;
                    int l = 0;
                    if ((uc&0xE0)==0xC0)
                    {
                      l=2; // 11xx.xxxx: >=2 byte character
                    }
                    if ((uc&0xF0)==0xE0)
                    {
                      l=3; // 111x.xxxx: >=3 byte character
                    }
                    if ((uc&0xF8)==0xF0)
                    {
                      l=4; // 1111.xxxx: >=4 byte character
                    }
                    doEscape = l==0;
                    for (int m=1; m<l && !doEscape; ++m)
                    {
                      unsigned char ct = (unsigned char)*pt;
                      if (ct==0 || (ct&0xC0)!=0x80) // invalid unicode character
                      {
                        doEscape=TRUE;
                      }
                      else
                      {
                        ids[ m ] = *pt++;
                      }
                    }
                    if ( !doEscape ) // got a valid unicode character
                    {
                      ids[ l ] = 0;
                      growBuf.addStr( ids );
                      p += l - 1;
                    }
                  }
                  if (doEscape) // not a valid unicode char or escaping needed
                  {
                    static char map[] = "0123456789ABCDEF";
                    unsigned char id = (unsigned char)c;
                    ids[0]='_';
                    ids[1]='x';
                    ids[2]=map[id>>4];
                    ids[3]=map[id&0xF];
                    ids[4]=0;
                    growBuf.addStr(ids);
                  }
5234 5235
                }
                else if (caseSenseNames || !isupper(c))
5236
                {
5237
                  growBuf.addChar(c);
5238 5239 5240
                }
                else
                {
5241 5242
                  growBuf.addChar('_');
                  growBuf.addChar(tolower(c)); 
5243 5244
                }
                break;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5245 5246
    }
  }
5247 5248
  growBuf.addChar(0);
  return growBuf.get();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5249 5250
}

5251
/*! This function determines the file name on disk of an item
5252
 *  given its name, which could be a class name with template 
5253 5254
 *  arguments, so special characters need to be escaped.
 */
5255
QCString convertNameToFile(const char *name,bool allowDots,bool allowUnderscore)
5256
{
5257 5258
  static bool shortNames = Config_getBool("SHORT_NAMES");
  static bool createSubdirs = Config_getBool("CREATE_SUBDIRS");
5259
  QCString result;
5260
  if (shortNames) // use short names only
5261
  {
5262 5263
    static QDict<int> usedNames(10007);
    usedNames.setAutoDelete(TRUE);
5264 5265
    static int count=1;

5266
    int *value=usedNames.find(name);
5267 5268 5269
    int num;
    if (value==0)
    {
5270
      usedNames.insert(name,new int(count));
5271 5272 5273 5274
      num = count++;
    }
    else
    {
5275
      num = *value;
5276 5277 5278 5279 5280
    }
    result.sprintf("a%05d",num); 
  }
  else // long names
  {
5281
    result=escapeCharsInString(name,allowDots,allowUnderscore);
5282 5283 5284 5285 5286 5287 5288 5289 5290 5291
    int resultLen = result.length();
    if (resultLen>=128) // prevent names that cannot be created!
    {
      // third algorithm based on MD5 hash
      uchar md5_sig[16];
      QCString sigStr(33);
      MD5Buffer((const unsigned char *)result.data(),resultLen,md5_sig);
      MD5SigToString(md5_sig,sigStr.data(),33);
      result=result.left(128-32)+sigStr; 
    }
5292
  }
5293
  if (createSubdirs)
5294
  {
5295 5296 5297 5298 5299
    int l1Dir=0,l2Dir=0;

#if MAP_ALGO==ALGO_COUNT 
    // old algorithm, has the problem that after regeneration the
    // output can be located in a different dir.
5300 5301 5302 5303 5304 5305 5306 5307 5308 5309
    if (Doxygen::htmlDirMap==0) 
    {
      Doxygen::htmlDirMap=new QDict<int>(100003);
      Doxygen::htmlDirMap->setAutoDelete(TRUE);
    }
    static int curDirNum=0;
    int *dirNum = Doxygen::htmlDirMap->find(result);
    if (dirNum==0) // new name
    {
      Doxygen::htmlDirMap->insert(result,new int(curDirNum)); 
5310 5311
      l1Dir = (curDirNum)&0xf;    // bits 0-3
      l2Dir = (curDirNum>>4)&0xff; // bits 4-11
5312 5313 5314 5315
      curDirNum++;
    }
    else // existing name
    {
5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331
      l1Dir = (*dirNum)&0xf;       // bits 0-3
      l2Dir = ((*dirNum)>>4)&0xff; // bits 4-11
    }
#elif MAP_ALGO==ALGO_CRC16
    // second algorithm based on CRC-16 checksum
    int dirNum = qChecksum(result,result.length());
    l1Dir = dirNum&0xf;
    l2Dir = (dirNum>>4)&0xff;
#elif MAP_ALGO==ALGO_MD5
    // third algorithm based on MD5 hash
    uchar md5_sig[16];
    MD5Buffer((const unsigned char *)result.data(),result.length(),md5_sig);
    l1Dir = md5_sig[14]&0xf;
    l2Dir = md5_sig[15];
#endif
    result.prepend(QCString().sprintf("d%x/d%02x/",l1Dir,l2Dir));
5332
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5333
  //printf("*** convertNameToFile(%s)->%s\n",name,result.data());
5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362
  return result;
}

QCString relativePathToRoot(const char *name)
{
  QCString result;
  if (Config_getBool("CREATE_SUBDIRS"))
  {
    if (name==0)
    {
      return REL_PATH_TO_ROOT;
    }
    else
    {
      QCString n = name;
      int i = n.findRev('/');
      if (i!=-1)
      {
        result=REL_PATH_TO_ROOT;
      }
    }
  }
  return result;
}

void createSubDirs(QDir &d)
{
  if (Config_getBool("CREATE_SUBDIRS"))
  {
5363
    // create 4096 subdirectories
5364
    int l1,l2;
5365
    for (l1=0;l1<16;l1++)
5366
    {
5367 5368
      d.mkdir(QString().sprintf("d%x",l1));
      for (l2=0;l2<256;l2++)
5369
      {
5370
        d.mkdir(QString().sprintf("d%x/d%02x",l1,l2));
5371 5372
      }
    }
5373 5374
  }
}
5375

Dimitri van Heesch's avatar
Dimitri van Heesch committed
5376 5377 5378 5379
/*! Input is a scopeName, output is the scopename split into a
 *  namespace part (as large as possible) and a classname part.
 */
void extractNamespaceName(const QCString &scopeName,
5380 5381
    QCString &className,QCString &namespaceName,
    bool allowEmptyClass)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5382
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5383 5384
  int i,p;
  QCString clName=scopeName;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5385
  NamespaceDef *nd = 0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5386
  if (!clName.isEmpty() && (nd=getResolvedNamespace(clName)) && getClass(clName)==0)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5387
  { // the whole name is a namespace (and not a class)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5388
    namespaceName=nd->name().copy();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5389
    className.resize(0);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5390
    goto done;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5391
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5392
  p=clName.length()-2;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5393 5394 5395
  while (p>=0 && (i=clName.findRev("::",p))!=-1) 
    // see if the first part is a namespace (and not a class)
  {
5396
    //printf("Trying %s\n",clName.left(i).data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5397
    if (i>0 && (nd=getResolvedNamespace(clName.left(i))) && getClass(clName.left(i))==0)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5398
    {
5399
      //printf("found!\n");
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5400
      namespaceName=nd->name().copy();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5401
      className=clName.right(clName.length()-i-2);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5402
      goto done;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5403 5404 5405
    } 
    p=i-2; // try a smaller piece of the scope
  }
5406
  //printf("not found!\n");
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5407 5408

  // not found, so we just have to guess.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5409 5410
  className=scopeName.copy();
  namespaceName.resize(0);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5411 5412

done:
5413
  if (className.isEmpty() && !namespaceName.isEmpty() && !allowEmptyClass)
5414 5415 5416 5417 5418
  {
    // class and namespace with the same name, correct to return the class.
    className=namespaceName.copy();
    namespaceName.resize(0);
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5419 5420
  //printf("extractNamespace `%s' => `%s|%s'\n",scopeName.data(),
  //       className.data(),namespaceName.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5421
  if (/*className.right(2)=="-g" ||*/ className.right(2)=="-p")
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5422 5423 5424
  {
    className = className.left(className.length()-2);
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5425 5426 5427
  return;
}

5428 5429 5430 5431 5432 5433
QCString insertTemplateSpecifierInScope(const QCString &scope,const QCString &templ)
{
  QCString result=scope.copy();
  if (!templ.isEmpty() && scope.find('<')==-1)
  {
    int si,pi=0;
5434 5435
    ClassDef *cd=0;
    while (
5436 5437 5438
        (si=scope.find("::",pi))!=-1 && !getClass(scope.left(si)+templ) && 
        ((cd=getClass(scope.left(si)))==0 || cd->templateArguments()==0) 
        ) 
5439 5440 5441 5442
    { 
      //printf("Tried `%s'\n",(scope.left(si)+templ).data()); 
      pi=si+2; 
    }
5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455
    if (si==-1) // not nested => append template specifier
    {
      result+=templ; 
    }
    else // nested => insert template specifier before after first class name
    {
      result=scope.left(si) + templ + scope.right(scope.length()-si);
    }
  }
  //printf("insertTemplateSpecifierInScope(`%s',`%s')=%s\n",
  //    scope.data(),templ.data(),result.data());
  return result;
}
5456

5457
#if 0 // original version
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5458 5459 5460
/*! Strips the scope from a name. Examples: A::B will return A
 *  and A<T>::B<N::C<D> > will return A<T>.
 */
5461 5462 5463
QCString stripScope(const char *name)
{
  QCString result = name;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5464 5465 5466 5467 5468 5469
  int l=result.length();
  int p=l-1;
  bool done;
  int count;

  while (p>=0)
5470
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489
    char c=result.at(p);
    switch (c)
    {
      case ':': 
        //printf("stripScope(%s)=%s\n",name,result.right(l-p-1).data());
        return result.right(l-p-1);
      case '>':
        count=1;
        done=FALSE;
        //printf("pos < = %d\n",p);
        p--;
        while (p>=0 && !done)
        {
          c=result.at(p--);
          switch (c)
          {
            case '>': count++; break;
            case '<': count--; if (count<=0) done=TRUE; break;
            default: 
5490 5491
                      //printf("c=%c count=%d\n",c,count);
                      break;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5492 5493 5494 5495 5496 5497 5498
          }
        }
        //printf("pos > = %d\n",p+1);
        break;
      default:
        p--;
    }
5499
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5500 5501
  //printf("stripScope(%s)=%s\n",name,name);
  return name;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5502
}
5503
#endif
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5504 5505 5506 5507 5508 5509 5510

// new version by Davide Cesari which also works for Fortran
QCString stripScope(const char *name)
{
  QCString result = name;
  int l=result.length();
  int p;
5511
  bool done = FALSE;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5512 5513
  bool skipBracket=FALSE; // if brackets do not match properly, ignore them altogether
  int count=0;
5514

Dimitri van Heesch's avatar
Dimitri van Heesch committed
5515 5516 5517 5518 5519 5520 5521 5522 5523
  do
  {
    p=l-1; // start at the end of the string
    while (p>=0 && count>=0)
    {
      char c=result.at(p);
      switch (c)
      {
        case ':': 
5524
          // only exit in the case of ::
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5525
          //printf("stripScope(%s)=%s\n",name,result.right(l-p-1).data());
5526 5527 5528
          if (p>0 && result.at(p-1)==':') return result.right(l-p-1);
          p--;
          break;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543
        case '>':
          if (skipBracket) // we don't care about brackets
          {
            p--;
          }
          else // count open/close brackets
          {
            if (p>0 && result.at(p-1)=='>') // skip >> operator
            {
              p-=2;
              break;
            }
            count=1;
            //printf("pos < = %d\n",p);
            p--;
5544 5545
            bool foundMatch=false;
            while (p>=0 && !foundMatch)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562
            {
              c=result.at(p--);
              switch (c)
              {
                case '>': 
                  count++; 
                  break;
                case '<': 
                  if (p>0)
                  {
                    if (result.at(p-1) == '<') // skip << operator
                    {
                      p--;
                      break;
                    }
                  }
                  count--; 
5563
                  foundMatch = count==0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582
                  break;
                default: 
                  //printf("c=%c count=%d\n",c,count);
                  break;
              }
            }
          }
          //printf("pos > = %d\n",p+1);
          break;
        default:
          p--;
      }
    }
    done = count==0 || skipBracket; // reparse if brackets do not match
    skipBracket=TRUE;
  }
  while (!done); // if < > unbalanced repeat ignoring them
  //printf("stripScope(%s)=%s\n",name,name);
  return name;
5583
}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5584

5585

Dimitri van Heesch's avatar
Dimitri van Heesch committed
5586
/*! Converts a string to an XML-encoded string */
5587 5588
QCString convertToXML(const char *s)
{
5589 5590
  static GrowBuf growBuf;
  growBuf.clear();
5591
  if (s==0) return "";
5592 5593 5594 5595 5596 5597
  const char *p=s;
  char c;
  while ((c=*p++))
  {
    switch (c)
    {
5598 5599 5600 5601 5602 5603
      case '<':  growBuf.addStr("&lt;");   break;
      case '>':  growBuf.addStr("&gt;");   break;
      case '&':  growBuf.addStr("&amp;");  break;
      case '\'': growBuf.addStr("&apos;"); break; 
      case '"':  growBuf.addStr("&quot;"); break;
      default:   growBuf.addChar(c);       break;
5604 5605
    }
  }
5606 5607
  growBuf.addChar(0);
  return growBuf.get();
5608
}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5609 5610

/*! Converts a string to a HTML-encoded string */
5611
QCString convertToHtml(const char *s,bool keepEntities)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5612
{
5613 5614
  static GrowBuf growBuf;
  growBuf.clear();
5615
  if (s==0) return "";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5616 5617 5618 5619 5620 5621
  const char *p=s;
  char c;
  while ((c=*p++))
  {
    switch (c)
    {
5622 5623
      case '<':  growBuf.addStr("&lt;");   break;
      case '>':  growBuf.addStr("&gt;");   break;
5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634
      case '&':  if (keepEntities)
                 {
                   const char *e=p;
                   char ce;
                   while ((ce=*e++))
                   {
                     if (ce==';' || (!(isId(ce) || ce=='#'))) break;
                   }
                   if (ce==';') // found end of an entity
                   {
                     // copy entry verbatim
5635 5636
                     growBuf.addChar(c);
                     while (p<e) growBuf.addChar(*p++);
5637 5638 5639
                   }
                   else
                   {
5640
                     growBuf.addStr("&amp;");
5641 5642 5643 5644
                   }
                 }
                 else
                 {
5645
                   growBuf.addStr("&amp;");  
5646 5647
                 }
                 break;
5648 5649 5650
      case '\'': growBuf.addStr("&#39;");  break; 
      case '"':  growBuf.addStr("&quot;"); break;
      default:   growBuf.addChar(c);       break;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5651 5652
    }
  }
5653 5654
  growBuf.addChar(0);
  return growBuf.get();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5655 5656
}

5657 5658
QCString convertToJSString(const char *s)
{
5659 5660
  static GrowBuf growBuf;
  growBuf.clear();
5661 5662 5663 5664 5665 5666 5667
  if (s==0) return "";
  const char *p=s;
  char c;
  while ((c=*p++))
  {
    switch (c)
    {
5668 5669 5670
      case '"':  growBuf.addStr("\\\""); break;
      case '\\': growBuf.addStr("\\\\"); break;
      default:   growBuf.addChar(c);   break;
5671 5672
    }
  }
5673
  growBuf.addChar(0);
5674
  return convertCharEntitiesToUTF8(growBuf.get());
5675 5676 5677
}


5678 5679
QCString convertCharEntitiesToUTF8(const QCString &s)
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5680
  static QDict<char> entityMap(127);
5681 5682 5683 5684 5685 5686
  static bool init=TRUE;
  QCString result;
  static QRegExp entityPat("&[a-zA-Z]+;");

  if (init)
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817
    entityMap.insert("copy",       "\xC2\xA9");
    entityMap.insert("tm",         "\xE2\x84\xA2");
    entityMap.insert("trade",      "\xE2\x84\xA2");
    entityMap.insert("reg",        "\xC2\xAE");
    entityMap.insert("lsquo",      "\xE2\x80\x98");
    entityMap.insert("rsquo",      "\xE2\x80\x99");
    entityMap.insert("ldquo",      "\xE2\x80\x9C");
    entityMap.insert("rdquo",      "\xE2\x80\x9D");
    entityMap.insert("ndash",      "\xE2\x80\x93");
    entityMap.insert("mdash",      "\xE2\x80\x94");
    entityMap.insert("Auml",       "\xC3\x84");
    entityMap.insert("Euml",       "\xC3\x8B");
    entityMap.insert("Iuml",       "\xC3\x8F");
    entityMap.insert("Ouml",       "\xC3\x96");
    entityMap.insert("Uuml",       "\xC3\x9C");
    entityMap.insert("Yuml",       "\xC5\xB8");
    entityMap.insert("auml",       "\xC3\xA4");
    entityMap.insert("euml",       "\xC3\xAB");
    entityMap.insert("iuml",       "\xC3\xAF");
    entityMap.insert("ouml",       "\xC3\xB6");
    entityMap.insert("uuml",       "\xC3\xBC");
    entityMap.insert("yuml",       "\xC3\xBF");
    entityMap.insert("Aacute",     "\xC3\x81");
    entityMap.insert("Eacute",     "\xC3\x89");
    entityMap.insert("Iacute",     "\xC3\x8D");
    entityMap.insert("Oacute",     "\xC3\x93");
    entityMap.insert("Uacute",     "\xC3\x9A");
    entityMap.insert("aacute",     "\xC3\xA1");
    entityMap.insert("eacute",     "\xC3\xA9");
    entityMap.insert("iacute",     "\xC3\xAD");
    entityMap.insert("oacute",     "\xC3\xB3");
    entityMap.insert("uacute",     "\xC3\xBA");
    entityMap.insert("Agrave",     "\xC3\x80");
    entityMap.insert("Egrave",     "\xC3\x88");
    entityMap.insert("Igrave",     "\xC3\x8C");
    entityMap.insert("Ograve",     "\xC3\x92");
    entityMap.insert("Ugrave",     "\xC3\x99");
    entityMap.insert("agrave",     "\xC3\xA0");
    entityMap.insert("egrave",     "\xC3\xA8");
    entityMap.insert("igrave",     "\xC3\xAC");
    entityMap.insert("ograve",     "\xC3\xB2");
    entityMap.insert("ugrave",     "\xC3\xB9");
    entityMap.insert("Acirc",      "\xC3\x82");
    entityMap.insert("Ecirc",      "\xC3\x8A");
    entityMap.insert("Icirc",      "\xC3\x8E");
    entityMap.insert("Ocirc",      "\xC3\x94");
    entityMap.insert("Ucirc",      "\xC3\x9B");
    entityMap.insert("acirc",      "\xC3\xA2");
    entityMap.insert("ecirc",      "\xC3\xAA");
    entityMap.insert("icirc",      "\xC3\xAE");
    entityMap.insert("ocirc",      "\xC3\xB4");
    entityMap.insert("ucirc",      "\xC3\xBB");
    entityMap.insert("Atilde",     "\xC3\x83");
    entityMap.insert("Ntilde",     "\xC3\x91");
    entityMap.insert("Otilde",     "\xC3\x95");
    entityMap.insert("atilde",     "\xC3\xA3");
    entityMap.insert("ntilde",     "\xC3\xB1");
    entityMap.insert("otilde",     "\xC3\xB5");
    entityMap.insert("szlig",      "\xC3\x9F");
    entityMap.insert("Ccedil",     "\xC3\x87");
    entityMap.insert("ccedil",     "\xC3\xA7");
    entityMap.insert("Aring",      "\xC3\x85");
    entityMap.insert("aring",      "\xC3\xA5");
    entityMap.insert("nbsp",       "\xC2\xA0");
    entityMap.insert("Gamma",      "\xCE\x93");
    entityMap.insert("Delta",      "\xCE\x94");
    entityMap.insert("Theta",      "\xCE\x98");
    entityMap.insert("Lambda",     "\xCE\x9B");
    entityMap.insert("Xi",         "\xCE\x9E");
    entityMap.insert("Pi",         "\xCE\xA0");
    entityMap.insert("Sigma",      "\xCE\xA3");
    entityMap.insert("Upsilon",    "\xCE\xA5");
    entityMap.insert("Phi",        "\xCE\xA6");
    entityMap.insert("Psi",        "\xCE\xA8");
    entityMap.insert("Omega",      "\xCE\xA9");
    entityMap.insert("alpha",      "\xCE\xB1");
    entityMap.insert("beta",       "\xCE\xB2");
    entityMap.insert("gamma",      "\xCE\xB3");
    entityMap.insert("delta",      "\xCE\xB4");
    entityMap.insert("epsilon",    "\xCE\xB5");
    entityMap.insert("zeta",       "\xCE\xB6");
    entityMap.insert("eta",        "\xCE\xB8");
    entityMap.insert("theta",      "\xCE\xB8");
    entityMap.insert("iota",       "\xCE\xB9");
    entityMap.insert("kappa",      "\xCE\xBA");
    entityMap.insert("lambda",     "\xCE\xBB");
    entityMap.insert("mu",         "\xCE\xBC");
    entityMap.insert("nu",         "\xCE\xBD");
    entityMap.insert("xi",         "\xCE\xBE");
    entityMap.insert("pi",         "\xCF\x80");
    entityMap.insert("rho",        "\xCF\x81");
    entityMap.insert("sigma",      "\xCF\x83");
    entityMap.insert("tau",        "\xCF\x84");
    entityMap.insert("upsilon",    "\xCF\x85");
    entityMap.insert("phi",        "\xCF\x86");
    entityMap.insert("chi",        "\xCF\x87");
    entityMap.insert("psi",        "\xCF\x88");
    entityMap.insert("omega",      "\xCF\x89");
    entityMap.insert("sigmaf",     "\xCF\x82");
    entityMap.insert("sect",       "\xC2\xA7");
    entityMap.insert("deg",        "\xC2\xB0");
    entityMap.insert("prime",      "\xE2\x80\xB2");
    entityMap.insert("Prime",      "\xE2\x80\xB2");
    entityMap.insert("infin",      "\xE2\x88\x9E");
    entityMap.insert("empty",      "\xE2\x88\x85");
    entityMap.insert("plusmn",     "\xC2\xB1");
    entityMap.insert("times",      "\xC3\x97");
    entityMap.insert("minus",      "\xE2\x88\x92");
    entityMap.insert("sdot",       "\xE2\x8B\x85");
    entityMap.insert("part",       "\xE2\x88\x82");
    entityMap.insert("nabla",      "\xE2\x88\x87");
    entityMap.insert("radic",      "\xE2\x88\x9A");
    entityMap.insert("perp",       "\xE2\x8A\xA5");
    entityMap.insert("sum",        "\xE2\x88\x91");
    entityMap.insert("int",        "\xE2\x88\xAB");
    entityMap.insert("prod",       "\xE2\x88\x8F");
    entityMap.insert("sim",        "\xE2\x88\xBC");
    entityMap.insert("asymp",      "\xE2\x89\x88");
    entityMap.insert("ne",         "\xE2\x89\xA0");
    entityMap.insert("equiv",      "\xE2\x89\xA1");
    entityMap.insert("prop",       "\xE2\x88\x9D");
    entityMap.insert("le",         "\xE2\x89\xA4");
    entityMap.insert("ge",         "\xE2\x89\xA5");
    entityMap.insert("larr",       "\xE2\x86\x90");
    entityMap.insert("rarr",       "\xE2\x86\x92");
    entityMap.insert("isin",       "\xE2\x88\x88");
    entityMap.insert("notin",      "\xE2\x88\x89");
    entityMap.insert("lceil",      "\xE2\x8C\x88");
    entityMap.insert("rceil",      "\xE2\x8C\x89");
    entityMap.insert("lfloor",     "\xE2\x8C\x8A");
    entityMap.insert("rfloor",     "\xE2\x8C\x8B");
5818 5819 5820
    init=FALSE;
  }

5821 5822 5823
  if (s.length()==0) return result;
  static GrowBuf growBuf;
  growBuf.clear();
5824 5825 5826
  int p,i=0,l;
  while ((p=entityPat.match(s,i,&l))!=-1)
  {
5827 5828 5829 5830
    if (p>i) 
    {
      growBuf.addStr(s.mid(i,p-i));
    }
5831 5832 5833 5834
    QCString entity = s.mid(p+1,l-2);
    char *code = entityMap.find(entity);
    if (code)
    {
5835
      growBuf.addStr(code);
5836 5837 5838
    }
    else
    {
5839
      growBuf.addStr(s.mid(p,l));
5840 5841 5842
    }
    i=p+l;
  }
5843 5844
  growBuf.addStr(s.mid(i,s.length()-i));
  growBuf.addChar(0);
5845
  //printf("convertCharEntitiesToUTF8(%s)->%s\n",s.data(),growBuf.get());
5846
  return growBuf.get();
5847 5848
}

5849 5850 5851
/*! Returns the standard string that is generated when the \\overload
 * command is used.
 */
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5852
QCString getOverloadDocs()
5853
{
5854 5855 5856 5857
  return theTranslator->trOverloadText();
  //"This is an overloaded member function, "
  //       "provided for convenience. It differs from the above "
  //       "function only in what argument(s) it accepts.";
5858
}
5859

Dimitri van Heesch's avatar
Dimitri van Heesch committed
5860
void addMembersToMemberGroup(MemberList *ml,
5861 5862
    MemberGroupSDict **ppMemberGroupSDict,
    Definition *context)
5863
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5864
  ASSERT(context!=0);
5865
  //printf("addMemberToMemberGroup()\n");
5866
  if (ml==0) return;
5867 5868 5869 5870 5871
  MemberListIterator mli(*ml);
  MemberDef *md;
  uint index;
  for (index=0;(md=mli.current());)
  {
5872 5873
    if (md->isEnumerate()) // insert enum value of this enum into groups
    {
5874
      MemberList *fmdl=md->enumFieldList();
5875
      if (fmdl!=0)
5876
      {
5877 5878 5879
        MemberListIterator fmli(*fmdl);
        MemberDef *fmd;
        for (fmli.toFirst();(fmd=fmli.current());++fmli)
5880 5881 5882 5883
        {
          int groupId=fmd->getMemberGroupId();
          if (groupId!=-1)
          {
5884 5885 5886 5887
            MemberGroupInfo *info = Doxygen::memGrpInfoDict[groupId];
            //QCString *pGrpHeader = Doxygen::memberHeaderDict[groupId];
            //QCString *pDocs      = Doxygen::memberDocDict[groupId];
            if (info)
5888
            {
5889 5890 5891 5892 5893 5894
              if (*ppMemberGroupSDict==0)
              {
                *ppMemberGroupSDict = new MemberGroupSDict;
                (*ppMemberGroupSDict)->setAutoDelete(TRUE);
              }
              MemberGroup *mg = (*ppMemberGroupSDict)->find(groupId);
5895 5896
              if (mg==0)
              {
5897
                mg = new MemberGroup(
5898 5899 5900 5901 5902 5903
                    context,
                    groupId,
                    info->header,
                    info->doc,
                    info->docFile
                    );
5904
                (*ppMemberGroupSDict)->append(groupId,mg);
5905
              }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5906
              mg->insertMember(fmd); // insert in member group
5907 5908 5909 5910 5911 5912
              fmd->setMemberGroup(mg);
            }
          }
        }
      }
    }
5913 5914 5915
    int groupId=md->getMemberGroupId();
    if (groupId!=-1)
    {
5916 5917 5918 5919
      MemberGroupInfo *info = Doxygen::memGrpInfoDict[groupId];
      //QCString *pGrpHeader = Doxygen::memberHeaderDict[groupId];
      //QCString *pDocs      = Doxygen::memberDocDict[groupId];
      if (info)
5920
      {
5921 5922 5923 5924 5925 5926
        if (*ppMemberGroupSDict==0)
        {
          *ppMemberGroupSDict = new MemberGroupSDict;
          (*ppMemberGroupSDict)->setAutoDelete(TRUE);
        }
        MemberGroup *mg = (*ppMemberGroupSDict)->find(groupId);
5927 5928
        if (mg==0)
        {
5929
          mg = new MemberGroup(
5930 5931 5932 5933 5934 5935
              context,
              groupId,
              info->header,
              info->doc,
              info->docFile
              );
5936
          (*ppMemberGroupSDict)->append(groupId,mg);
5937
        }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5938
        md = ml->take(index); // remove from member list
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5939
        mg->insertMember(md); // insert in member group
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5940
        mg->setRefItems(info->m_sli);
5941
        md->setMemberGroup(mg);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5942
        continue;
5943 5944
      }
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5945
    ++mli;++index;
5946 5947
  }
}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5948 5949

/*! Extracts a (sub-)string from \a type starting at \a pos that
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5950 5951 5952
 *  could form a class. The index of the match is returned and the found
 *  class \a name and a template argument list \a templSpec. If -1 is returned
 *  there are no more matches.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5953
 */
5954
int extractClassNameFromType(const QCString &type,int &pos,QCString &name,QCString &templSpec,SrcLangExt lang)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5955
{
5956 5957 5958 5959
  static const QRegExp re_norm("[a-z_A-Z\\x80-\\xFF][a-z_A-Z0-9:\\x80-\\xFF]*");
  static const QRegExp re_ftn("[a-z_A-Z\\x80-\\xFF][()=_a-z_A-Z0-9:\\x80-\\xFF]*");
  QRegExp re;

5960 5961 5962 5963 5964
  name.resize(0);
  templSpec.resize(0);
  int i,l;
  int typeLen=type.length();
  if (typeLen>0)
5965
  {
5966
    if (lang == SrcLangExt_Fortran)
5967
    {
5968 5969 5970 5971 5972 5973 5974 5975 5976
      if (type.at(pos)==',') return -1;
      if (type.left(4).lower()=="type")
      {
        re = re_norm;
      }
      else
      {
        re = re_ftn;
      }
5977 5978 5979
    }
    else
    {
5980
      re = re_norm;
5981 5982
    }

Dimitri van Heesch's avatar
Dimitri van Heesch committed
5983 5984 5985 5986
    if ((i=re.match(type,pos,&l))!=-1) // for each class name in the type
    {
      int ts=i+l;
      int te=ts;
5987 5988
      int tl=0;
      while (type.at(ts)==' ' && ts<typeLen) ts++,tl++; // skip any whitespace
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007
      if (type.at(ts)=='<') // assume template instance
      {
        // locate end of template
        te=ts+1;
        int brCount=1;
        while (te<typeLen && brCount!=0)
        {
          if (type.at(te)=='<') 
          {
            if (te<typeLen-1 && type.at(te+1)=='<') te++; else brCount++;
          }
          if (type.at(te)=='>') 
          {
            if (te<typeLen-1 && type.at(te+1)=='>') te++; else brCount--;
          }
          te++;
        }
      }
      name = type.mid(i,l);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6008 6009 6010 6011 6012 6013 6014 6015 6016
      if (te>ts) 
      {
        templSpec = type.mid(ts,te-ts),tl+=te-ts;
        pos=i+l+tl;
      }
      else // no template part
      {
        pos=i+l;
      }
6017 6018
      //printf("extractClassNameFromType([in] type=%s,[out] pos=%d,[out] name=%s,[out] templ=%s)=TRUE\n",
      //    type.data(),pos,name.data(),templSpec.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6019
      return i;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6020 6021
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6022
  pos = typeLen;
6023 6024
  //printf("extractClassNameFromType([in] type=%s,[out] pos=%d,[out] name=%s,[out] templ=%s)=FALSE\n",
  //       type.data(),pos,name.data(),templSpec.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6025
  return -1;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6026 6027
}

6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083
QCString normalizeNonTemplateArgumentsInString(
       const QCString &name,
       Definition *context,
       const ArgumentList * formalArgs)
{
  // skip until <
  int p=name.find('<');
  if (p==-1) return name;
  p++;
  QCString result = name.left(p);

  static QRegExp re("[a-z_A-Z\\x80-\\xFF][a-z_A-Z0-9\\x80-\\xFF]*");
  int l,i;
  // for each identifier in the template part (e.g. B<T> -> T)
  while ((i=re.match(name,p,&l))!=-1)
  {
    result += name.mid(p,i-p);
    QCString n = name.mid(i,l);
    bool found=FALSE;
    if (formalArgs) // check that n is not a formal template argument
    {
      ArgumentListIterator formAli(*formalArgs);
      Argument *formArg;
      for (formAli.toFirst();
          (formArg=formAli.current()) && !found;
          ++formAli
          )
      {
        found = formArg->name==n;
      }
    }
    if (!found)
    {
      // try to resolve the type
      ClassDef *cd = getResolvedClass(context,0,n);
      if (cd)
      {
        result+=cd->name();
      }
      else
      {
        result+=n;
      }
    }
    else
    {
      result+=n;
    }
    p=i+l;
  }
  result+=name.right(name.length()-p);
  //printf("normalizeNonTemplateArgumentInString(%s)=%s\n",name.data(),result.data());
  return removeRedundantWhiteSpace(result);
}


6084 6085 6086
/*! Substitutes any occurrence of a formal argument from argument list
 *  \a formalArgs in \a name by the corresponding actual argument in
 *  argument list \a actualArgs. The result after substitution
6087
 *  is returned as a string. The argument \a name is used to
6088
 *  prevent recursive substitution.
6089 6090
 */
QCString substituteTemplateArgumentsInString(
6091 6092 6093
    const QCString &name,
    ArgumentList *formalArgs,
    ArgumentList *actualArgs)
6094
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6095 6096
  //printf("substituteTemplateArgumentsInString(name=%s formal=%s actualArg=%s)\n",
  //    name.data(),argListToString(formalArgs).data(),argListToString(actualArgs).data());
6097 6098
  if (formalArgs==0) return name;
  QCString result;
6099
  static QRegExp re("[a-z_A-Z\\x80-\\xFF][a-z_A-Z0-9\\x80-\\xFF]*");
6100 6101 6102 6103 6104 6105 6106
  int p=0,l,i;
  // for each identifier in the base class name (e.g. B<T> -> B and T)
  while ((i=re.match(name,p,&l))!=-1)
  {
    result += name.mid(p,i-p);
    QCString n = name.mid(i,l);
    ArgumentListIterator formAli(*formalArgs);
6107
    ArgumentListIterator actAli(*actualArgs);
6108
    Argument *formArg;
6109
    Argument *actArg;
6110 6111 6112 6113 6114

    // if n is a template argument, then we substitute it
    // for its template instance argument.
    bool found=FALSE;
    for (formAli.toFirst();
6115 6116
        (formArg=formAli.current()) && !found && (actArg=actAli.current());
        ++formAli,++actAli
6117 6118
        )
    {
6119 6120 6121 6122 6123 6124 6125 6126 6127 6128
      if (formArg->type.left(6)=="class " && formArg->name.isEmpty())
      {
        formArg->name = formArg->type.mid(6);
        formArg->type = "class";
      }
      if (formArg->type.left(9)=="typename " && formArg->name.isEmpty())
      {
        formArg->name = formArg->type.mid(9);
        formArg->type = "typename";
      }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6129
      if (formArg->type=="class" || formArg->type=="typename" || formArg->type.left(8)=="template")
6130
      {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6131
        //printf("n=%s formArg->type='%s' formArg->name='%s' formArg->defval='%s'\n",
6132
        //  n.data(),formArg->type.data(),formArg->name.data(),formArg->defval.data());
6133 6134 6135
        //printf(">> formArg->name='%s' actArg->type='%s' actArg->name='%s'\n",
        //    formArg->name.data(),actArg->type.data(),actArg->name.data()
        //    );
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6136 6137 6138
        if (formArg->name==n && actArg && !actArg->type.isEmpty()) // base class is a template argument
        {
          // replace formal argument with the actual argument of the instance
6139 6140 6141 6142 6143 6144
          if (!leftScopeMatch(actArg->type,n)) 
            // the scope guard is to prevent recursive lockup for 
            // template<class A> class C : public<A::T>, 
            // where A::T would become A::T::T here, 
            // since n==A and actArg->type==A::T
            // see bug595833 for an example
6145
          {
6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157
            if (actArg->name.isEmpty())
            {
              result += actArg->type+" "; 
              found=TRUE;
            }
            else 
              // for case where the actual arg is something like "unsigned int"
              // the "int" part is in actArg->name.
            {
              result += actArg->type+" "+actArg->name+" "; 
              found=TRUE;
            }
6158
          }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6159
        }
6160 6161 6162 6163
        else if (formArg->name==n && 
                 actArg==0 && 
                 !formArg->defval.isEmpty() &&
                 formArg->defval!=name /* to prevent recursion */
6164
            )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6165
        {
6166
          result += substituteTemplateArgumentsInString(formArg->defval,formalArgs,actualArgs)+" ";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6167 6168
          found=TRUE;
        }
6169
      }
6170 6171 6172 6173 6174
      else if (formArg->name==n && 
               actArg==0 && 
               !formArg->defval.isEmpty() &&
               formArg->defval!=name /* to prevent recursion */
              )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6175 6176 6177 6178
      {
        result += substituteTemplateArgumentsInString(formArg->defval,formalArgs,actualArgs)+" ";
        found=TRUE;
      }
6179
    }
6180 6181 6182 6183
    if (!found) 
    {
      result += n;
    }
6184 6185 6186 6187 6188
    p=i+l;
  }
  result+=name.right(name.length()-p);
  //printf("      Inheritance relation %s -> %s\n",
  //    name.data(),result.data());
6189
  return result.stripWhiteSpace();
6190 6191
}

6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203
/*! Makes a deep copy of the list of argument lists \a srcLists. 
 *  Will allocate memory, that is owned by the caller.
 */
QList<ArgumentList> *copyArgumentLists(const QList<ArgumentList> *srcLists)
{
  ASSERT(srcLists!=0);
  QList<ArgumentList> *dstLists = new QList<ArgumentList>;
  dstLists->setAutoDelete(TRUE);
  QListIterator<ArgumentList> sli(*srcLists);
  ArgumentList *sl;
  for (;(sl=sli.current());++sli)
  {
6204
    dstLists->append(sl->deepCopy());
6205 6206 6207 6208 6209 6210 6211 6212
  }
  return dstLists;
}

/*! Strips template specifiers from scope \a fullName, except those 
 *  that make up specialized classes. The switch \a parentOnly 
 *  determines whether or not a template "at the end" of a scope 
 *  should be considered, e.g. with \a parentOnly is \c TRUE, A<T>::B<S> will 
6213
 *  try to strip \<T\> and not \<S\>, while \a parentOnly is \c FALSE will 
6214 6215 6216
 *  strip both unless A<T> or B<S> are specialized template classes. 
 */
QCString stripTemplateSpecifiersFromScope(const QCString &fullName,
6217 6218
    bool parentOnly,
    QCString *pLastScopeStripped)
6219 6220 6221 6222 6223
{
  QCString result;
  int p=0;
  int l=fullName.length();
  int i=fullName.find('<');
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6224
  while (i!=-1)
6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242
  {
    //printf("1:result+=%s\n",fullName.mid(p,i-p).data());
    int e=i+1;
    bool done=FALSE;
    int count=1;
    while (e<l && !done)
    {
      char c=fullName.at(e++);
      if (c=='<') 
      {
        count++;
      }
      else if (c=='>') 
      {
        count--;
        done = count==0;
      }
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6243 6244 6245
    int si= fullName.find("::",e);

    if (parentOnly && si==-1) break; 
6246
    // we only do the parent scope, so we stop here if needed
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6247 6248

    result+=fullName.mid(p,i-p);
6249
    //printf("  trying %s\n",(result+fullName.mid(i,e-i)).data());
6250
    if (getClass(result+fullName.mid(i,e-i))!=0)
6251 6252
    {
      result+=fullName.mid(i,e-i);
6253
      //printf("  2:result+=%s\n",fullName.mid(i,e-i-1).data());
6254
    }
6255 6256
    else if (pLastScopeStripped)
    {
6257
      //printf("  last stripped scope '%s'\n",fullName.mid(i,e-i).data());
6258 6259
      *pLastScopeStripped=fullName.mid(i,e-i);
    }
6260 6261 6262 6263 6264 6265 6266
    p=e;
    i=fullName.find('<',p);
  }
  result+=fullName.right(l-p);
  //printf("3:result+=%s\n",fullName.right(l-p).data());
  return result;
}
6267

Dimitri van Heesch's avatar
Dimitri van Heesch committed
6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356
/*! Merges two scope parts together. The parts may (partially) overlap.
 *  Example1: \c A::B and \c B::C will result in \c A::B::C <br>
 *  Example2: \c A and \c B will be \c A::B <br>
 *  Example3: \c A::B and B will be \c A::B
 *  
 *  @param leftScope the left hand part of the scope.
 *  @param rightScope the right hand part of the scope.
 *  @returns the merged scope. 
 */
QCString mergeScopes(const QCString &leftScope,const QCString &rightScope)
{
  // case leftScope=="A" rightScope=="A::B" => result = "A::B"
  if (leftScopeMatch(rightScope,leftScope)) return rightScope;
  QCString result;
  int i=0,p=leftScope.length();

  // case leftScope=="A::B" rightScope=="B::C" => result = "A::B::C"
  // case leftScope=="A::B" rightScope=="B" => result = "A::B"
  bool found=FALSE;
  while ((i=leftScope.findRev("::",p))!=-1)
  {
    if (leftScopeMatch(rightScope,leftScope.right(leftScope.length()-i-2)))
    {
      result = leftScope.left(i+2)+rightScope;
      found=TRUE;
    }
    p=i-1;
  }
  if (found) return result;

  // case leftScope=="A" rightScope=="B" => result = "A::B"
  result=leftScope.copy();
  if (!result.isEmpty() && !rightScope.isEmpty()) result+="::";
  result+=rightScope;
  return result;
}

/*! Returns a fragment from scope \a s, starting at position \a p.
 *
 *  @param s the scope name as a string.
 *  @param p the start position (0 is the first).
 *  @param l the resulting length of the fragment.
 *  @returns the location of the fragment, or -1 if non is found.
 */
int getScopeFragment(const QCString &s,int p,int *l)
{
  int sl=s.length();
  int sp=p;
  int count=0;
  bool done;
  if (sp>=sl) return -1;
  while (sp<sl)
  {
    char c=s.at(sp);
    if (c==':') sp++,p++; else break;
  }
  while (sp<sl)
  {
    char c=s.at(sp);
    switch (c)
    {
      case ':': // found next part
        goto found;
      case '<': // skip template specifier
        count=1;sp++;
        done=FALSE;
        while (sp<sl && !done)
        {
          // TODO: deal with << and >> operators!
          char c=s.at(sp++);
          switch(c)
          {
            case '<': count++; break;
            case '>': count--; if (count==0) done=TRUE; break;
            default: break;
          }
        }
        break;
      default:
        sp++;
        break;
    }
  }
found:
  *l=sp-p;
  //printf("getScopeFragment(%s,%d)=%s\n",s.data(),p,s.mid(p,*l).data());
  return p;
}

6357 6358
//----------------------------------------------------------------------------

6359
PageDef *addRelatedPage(const char *name,const QCString &ptitle,
6360 6361 6362 6363 6364
    const QCString &doc,
    QList<SectionInfo> * /*anchors*/,
    const char *fileName,int startLine,
    const QList<ListItemInfo> *sli,
    GroupDef *gd,
6365 6366
    TagInfo *tagInfo,
    SrcLangExt lang
6367
    )
6368
{
6369
  PageDef *pd=0;
6370
  //printf("addRelatedPage(name=%s gd=%p)\n",name,gd);
6371
  if ((pd=Doxygen::pageSDict->find(name)) && !tagInfo)
6372 6373
  {
    // append documentation block to the page.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6374
    pd->setDocumentation(doc,fileName,startLine);
6375
    //printf("Adding page docs `%s' pi=%p name=%s\n",doc.data(),pi,name);
6376 6377 6378 6379 6380 6381
  }
  else // new page
  {
    QCString baseName=name;
    if (baseName.right(4)==".tex") 
      baseName=baseName.left(baseName.length()-4);
6382 6383
    else if (baseName.right(Doxygen::htmlFileExtension.length())==Doxygen::htmlFileExtension)
      baseName=baseName.left(baseName.length()-Doxygen::htmlFileExtension.length());
6384

6385
    QCString title=ptitle.stripWhiteSpace();
6386
    pd=new PageDef(fileName,startLine,baseName,doc,title);
6387

6388
    pd->setRefItems(sli);
6389
    pd->setLanguage(lang);
6390

6391 6392
    if (tagInfo)
    {
6393
      pd->setReference(tagInfo->tagName);
6394
      pd->setFileName(tagInfo->fileName,TRUE);
6395 6396 6397
    }
    else
    {
6398
      pd->setFileName(convertNameToFile(pd->name(),FALSE,TRUE),FALSE);
6399 6400
    }

6401
    //printf("Appending page `%s'\n",baseName.data());
6402
    Doxygen::pageSDict->append(baseName,pd);
6403

6404
    if (gd) gd->addPage(pd);
6405

6406
    if (!pd->title().isEmpty())
6407 6408 6409 6410
    {
      //outputList->writeTitle(pi->name,pi->title);

      // a page name is a label as well!
6411
      QCString file;
6412 6413
      if (gd)
      {
6414
        file=gd->getOutputFileBase();
6415
      }
6416
      else 
6417
      {
6418
        file=pd->getOutputFileBase();
6419
      }
6420
      SectionInfo *si=new SectionInfo(
6421
          file,pd->name(),pd->title(),SectionInfo::Page,0,pd->getReference());
6422 6423 6424 6425
      //printf("si->label=`%s' si->definition=%s si->fileName=`%s'\n",
      //      si->label.data(),si->definition?si->definition->name().data():"<none>",
      //      si->fileName.data());
      //printf("  SectionInfo: sec=%p sec->fileName=%s\n",si,si->fileName.data());
6426
      //printf("Adding section key=%s si->fileName=%s\n",pageName.data(),si->fileName.data());
6427
      Doxygen::sectionDict->append(pd->name(),si);
6428 6429
    }
  }
6430
  return pd;
6431 6432 6433 6434
}

//----------------------------------------------------------------------------

6435
void addRefItem(const QList<ListItemInfo> *sli,
6436
    const char *key, 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6437
    const char *prefix, const char *name,const char *title,const char *args)
6438
{
6439
  //printf("addRefItem(sli=%p,key=%s,prefix=%s,name=%s,title=%s,args=%s)\n",sli,key,prefix,name,title,args);
6440
  if (sli && key && key[0]!='@') // check for @ to skip anonymous stuff (see bug427012)
6441 6442 6443 6444 6445
  {
    QListIterator<ListItemInfo> slii(*sli);
    ListItemInfo *lii;
    for (slii.toFirst();(lii=slii.current());++slii)
    {
6446
      RefList *refList = Doxygen::xrefLists->find(lii->type);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6447 6448
      if (refList
          &&
6449 6450
          (
           // either not a built-in list or the list is enabled
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6451 6452 6453
           (lii->type!="todo"       || Config_getBool("GENERATE_TODOLIST")) &&
           (lii->type!="test"       || Config_getBool("GENERATE_TESTLIST")) &&
           (lii->type!="bug"        || Config_getBool("GENERATE_BUGLIST"))  &&
6454
           (lii->type!="deprecated" || Config_getBool("GENERATE_DEPRECATEDLIST"))
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6455
          )
6456
         )
6457 6458 6459
      {
        RefItem *item = refList->getRefItem(lii->itemId);
        ASSERT(item!=0);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6460 6461 6462 6463 6464 6465

        item->prefix = prefix;
        item->name   = name;
        item->title  = title;
        item->args   = args;

6466
        refList->insertIntoList(key,item);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6467

6468 6469
      }
    }
6470 6471 6472
  }
}

6473 6474
void addGroupListToTitle(OutputList &ol,Definition *d)
{
6475 6476
  GroupList *groups = d->partOfGroups();
  if (groups) // write list of group to which this definition belongs
6477 6478 6479
  {
    ol.pushGeneratorState();
    ol.disableAllBut(OutputGenerator::Html);
6480
    ol.writeString("<div class=\"ingroups\">");
6481
    GroupListIterator gli(*groups);
6482 6483 6484 6485
    GroupDef *gd;
    bool first=TRUE;
    for (gli.toFirst();(gd=gli.current());++gli)
    {
6486
      if (!first) { ol.writeString(" &#124; "); } else first=FALSE; 
6487
      ol.writeObjectLink(gd->getReference(),
6488
          gd->getOutputFileBase(),0,gd->groupTitle());
6489
    }
6490
    ol.writeString("</div>");
6491 6492 6493
    ol.popGeneratorState();
  }
}
6494

6495
void filterLatexString(FTextStream &t,const char *str,
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6496
    bool insideTabbing,bool insidePre,bool insideItem)
6497
{
6498
  if (str==0) return;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6499 6500
  //printf("filterLatexString(%s)\n",str);
  //if (strlen(str)<2) stackTrace();
6501 6502 6503 6504
  const unsigned char *p=(const unsigned char *)str;
  unsigned char c;
  unsigned char pc='\0';
  while (*p)
6505
  {
6506
    c=*p++;
6507

6508 6509 6510
    if (insidePre)
    {
      switch(c)
6511
      {
6512 6513 6514 6515 6516 6517
        case '\\': t << "\\(\\backslash\\)"; break;
        case '{':  t << "\\{"; break;
        case '}':  t << "\\}"; break;
        case '_':  t << "\\_"; break;
        default: 
                   t << (char)c;
6518
      }
6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529
    }
    else
    {
      switch(c)
      {
        case '#':  t << "\\#";           break;
        case '$':  t << "\\$";           break;
        case '%':  t << "\\%";           break;
        case '^':  t << "$^\\wedge$";    break;
        case '&':  t << "\\&";           break;
        case '*':  t << "$\\ast$";       break;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6530 6531
        case '_':  if (!insideTabbing) t << "\\-";  
                   t << "\\_"; 
6532 6533 6534 6535 6536 6537
                   if (!insideTabbing) t << "\\-";  
                   break;
        case '{':  t << "\\{";           break;
        case '}':  t << "\\}";           break;
        case '<':  t << "$<$";           break;
        case '>':  t << "$>$";           break;
6538
        case '|':  t << "$\\vert$";      break;
6539 6540 6541 6542 6543 6544 6545 6546 6547
        case '~':  t << "$\\sim$";       break;
        case '[':  if (Config_getBool("PDF_HYPERLINKS") || insideItem) 
                     t << "\\mbox{[}"; 
                   else
                     t << "[";
                   break;
        case ']':  if (pc=='[') t << "$\\,$";
                     if (Config_getBool("PDF_HYPERLINKS") || insideItem)
                       t << "\\mbox{]}";
6548
                     else
6549 6550 6551 6552 6553 6554 6555 6556 6557
                       t << "]";             
                   break;
        case '-':  t << "-\\/";
                   break;
        case '\\': if (*p=='<') 
                   { t << "$<$"; p++; }
                   else if (*p=='>')
                   { t << "$>$"; p++; } 
                   else  
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6558
                   { t << "\\textbackslash{}"; }
6559 6560 6561 6562 6563
                   break;           
        case '"':  { t << "\\char`\\\"{}"; }
                   break;

        default:   
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6564 6565
                   //if (!insideTabbing && forceBreaks && c!=' ' && *p!=' ')
                   if (!insideTabbing && 
6566
                       ((c>='A' && c<='Z' && pc!=' ' && pc!='\0') || (c==':' && pc!=':') || (pc=='.' && isId(c)))
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6567
                      )
6568 6569 6570
                   {
                     t << "\\-";
                   }
6571
                   t << (char)c;
6572 6573
      }
    }
6574
    pc = c;
6575 6576
  }
}
6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593


QCString rtfFormatBmkStr(const char *name)
{
  static QCString g_nextTag( "AAAAAAAAAA" );
  static QDict<QCString> g_tagDict( 5003 );

  g_tagDict.setAutoDelete(TRUE);

  // To overcome the 40-character tag limitation, we
  // substitute a short arbitrary string for the name
  // supplied, and keep track of the correspondence
  // between names and strings.
  QCString key( name );
  QCString* tag = g_tagDict.find( key );
  if ( !tag )
  {
6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613
    // This particular name has not yet been added
    // to the list. Add it, associating it with the
    // next tag value, and increment the next tag.
    tag = new QCString( g_nextTag.copy() ); // Make sure to use a deep copy!
    g_tagDict.insert( key, tag );

    // This is the increment part
    char* nxtTag = g_nextTag.data() + g_nextTag.length() - 1;
    for ( unsigned int i = 0; i < g_nextTag.length(); ++i, --nxtTag )
    {
      if ( ( ++(*nxtTag) ) > 'Z' )
      {
        *nxtTag = 'A';
      }
      else
      {
        // Since there was no carry, we can stop now
        break;
      }
    }
6614
  }
6615

6616 6617 6618
  return *tag;
}

6619 6620 6621 6622 6623 6624 6625 6626 6627 6628
QCString stripExtension(const char *fName)
{
  QCString result=fName;
  if (result.right(Doxygen::htmlFileExtension.length())==Doxygen::htmlFileExtension)
  {
    result=result.left(result.length()-Doxygen::htmlFileExtension.length());
  }
  return result;
}

6629

6630 6631 6632 6633
void replaceNamespaceAliases(QCString &scope,int i)
{
  while (i>0)
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6634 6635
    QCString ns = scope.left(i);
    QCString *s = Doxygen::namespaceAliasDict[ns];
6636 6637 6638 6639 6640
    if (s)
    {
      scope=*s+scope.right(scope.length()-i);
      i=s->length();
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6641
    if (i>0 && ns==scope.left(i)) break;
6642 6643
  }
}
6644

6645 6646 6647 6648 6649 6650 6651 6652
QCString stripPath(const char *s)
{
  QCString result=s;
  int i=result.findRev('/');
  if (i!=-1)
  {
    result=result.mid(i+1);
  }
6653 6654 6655 6656 6657
  i=result.findRev('\\');
  if (i!=-1)
  {
    result=result.mid(i+1);
  }
6658 6659
  return result;
}
6660 6661 6662 6663

/** returns \c TRUE iff string \a s contains word \a w */
bool containsWord(const QCString &s,const QCString &word)
{
6664
  static QRegExp wordExp("[a-z_A-Z\\x80-\\xFF]+");
6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675
  int p=0,i,l;
  while ((i=wordExp.match(s,p,&l))!=-1)
  {
    if (s.mid(i,l)==word) return TRUE;
    p=i+l;
  }
  return FALSE;
}

bool findAndRemoveWord(QCString &s,const QCString &word)
{
6676
  static QRegExp wordExp("[a-z_A-Z\\x80-\\xFF]+");
6677 6678 6679 6680 6681
  int p=0,i,l;
  while ((i=wordExp.match(s,p,&l))!=-1)
  {
    if (s.mid(i,l)==word) 
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6682
      if (i>0 && isspace((uchar)s.at(i-1))) 
6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693
        i--,l++;
      else if (i+l<(int)s.length() && isspace(s.at(i+l))) 
        l++;
      s = s.left(i)+s.mid(i+l); // remove word + spacing
      return TRUE;
    }
    p=i+l;
  }
  return FALSE;
}

6694
/** Special version of QCString::stripWhiteSpace() that only strips
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6695 6696 6697 6698 6699 6700
 *  completely blank lines.
 *  @param s the string to be stripped
 *  @param docLine the line number corresponding to the start of the
 *         string. This will be adjusted based on the number of lines stripped
 *         from the start.
 *  @returns The stripped string.
6701
 */
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6702
QCString stripLeadingAndTrailingEmptyLines(const QCString &s,int &docLine)
6703 6704 6705 6706 6707 6708 6709 6710 6711 6712
{
  const char *p = s.data();
  if (p==0) return 0;

  // search for leading empty lines
  int i=0,li=-1,l=s.length();
  char c;
  while ((c=*p++))
  {
    if (c==' ' || c=='\t' || c=='\r') i++;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6713
    else if (c=='\n') i++,li=i,docLine++;
6714 6715 6716 6717 6718 6719 6720 6721
    else break;
  }

  // search for trailing empty lines
  int b=l-1,bi=-1;
  p=s.data()+b;
  while (b>=0)
  {
6722
    c=*p; p--;
6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737
    if (c==' ' || c=='\t' || c=='\r') b--;
    else if (c=='\n') bi=b,b--;
    else break;
  }

  // return whole string if no leading or trailing lines where found
  if (li==-1 && bi==-1) return s;

  // return substring
  if (bi==-1) bi=l;
  if (li==-1) li=0;
  if (bi<=li) return 0; // only empty lines
  return s.mid(li,bi-li);
}

6738
#if 0
6739
void stringToSearchIndex(const QCString &docBaseUrl,const QCString &title,
6740
    const QCString &str,bool priority,const QCString &anchor)
6741 6742 6743 6744 6745
{
  static bool searchEngine = Config_getBool("SEARCHENGINE");
  if (searchEngine)
  {
    Doxygen::searchIndex->setCurrentDoc(title,docBaseUrl,anchor);
6746
    static QRegExp wordPattern("[a-z_A-Z\\x80-\\xFF][a-z_A-Z0-9\\x80-\\xFF]*");
6747 6748 6749 6750 6751 6752 6753 6754
    int i,p=0,l;
    while ((i=wordPattern.match(str,p,&l))!=-1)
    {
      Doxygen::searchIndex->addWord(str.mid(i,l),priority);
      p=i+l;
    }
  }
}
6755
#endif
6756

6757 6758 6759 6760 6761 6762 6763
//--------------------------------------------------------------------------

static QDict<int> g_extLookup;

static struct Lang2ExtMap
{
  const char *langName;
6764
  const char *parserName;
6765 6766 6767 6768
  SrcLangExt parserId;
} 
g_lang2extMap[] =
{
6769
//  language       parser     parser option
6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785
  { "idl",         "c",       SrcLangExt_IDL      },
  { "java",        "c",       SrcLangExt_Java     },
  { "javascript",  "c",       SrcLangExt_JS       },
  { "csharp",      "c",       SrcLangExt_CSharp   },
  { "d",           "c",       SrcLangExt_D        },
  { "php",         "c",       SrcLangExt_PHP      },
  { "objective-c", "c",       SrcLangExt_ObjC     },
  { "c",           "c",       SrcLangExt_Cpp      },
  { "c++",         "c",       SrcLangExt_Cpp      },
  { "python",      "python",  SrcLangExt_Python   },
  { "fortran",     "fortran", SrcLangExt_Fortran  },
  { "vhdl",        "vhdl",    SrcLangExt_VHDL     },
  { "dbusxml",     "dbusxml", SrcLangExt_XML      },
  { "tcl",         "tcl",     SrcLangExt_Tcl      },
  { "md",          "md",      SrcLangExt_Markdown },
  { 0,             0,        (SrcLangExt)0        }
6786 6787
};

6788
bool updateLanguageMapping(const QCString &extension,const QCString &language)
6789 6790
{
  const Lang2ExtMap *p = g_lang2extMap;
6791
  QCString langName = language.lower();
6792 6793 6794 6795 6796 6797 6798
  while (p->langName)
  {
    if (langName==p->langName) break;
    p++;
  }
  if (!p->langName) return FALSE;

6799
  // found the language
6800
  SrcLangExt parserId = p->parserId;
6801
  QCString extName = extension.lower();
6802 6803
  if (extName.isEmpty()) return FALSE;
  if (extName.at(0)!='.') extName.prepend(".");
6804
  if (g_extLookup.find(extension)!=0) // language was already register for this ext
6805 6806 6807
  {
    g_extLookup.remove(extension);
  }
6808 6809
  //printf("registering extension %s\n",extName.data());
  g_extLookup.insert(extName,new int(parserId));
6810 6811 6812 6813 6814 6815 6816 6817 6818 6819
  if (!Doxygen::parserManager->registerExtension(extName,p->parserName))
  {
    err("Failed to assign extension %s to parser %s for language %s\n",
        extName.data(),p->parserName,language.data());
  }
  else
  {
    //msg("Registered extension %s to language parser %s...\n",
    //    extName.data(),language.data());
  }
6820 6821 6822
  return TRUE;
}

6823 6824 6825
void initDefaultExtensionMapping()
{
  g_extLookup.setAutoDelete(TRUE);
6826
  //                  extension      parser id
6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853
  updateLanguageMapping(".idl",      "idl"); 
  updateLanguageMapping(".ddl",      "idl"); 
  updateLanguageMapping(".odl",      "idl"); 
  updateLanguageMapping(".java",     "java");
  updateLanguageMapping(".as",       "javascript"); 
  updateLanguageMapping(".js",       "javascript");
  updateLanguageMapping(".cs",       "csharp");
  updateLanguageMapping(".d",        "d");
  updateLanguageMapping(".php",      "php"); 
  updateLanguageMapping(".php4",     "php");
  updateLanguageMapping(".php5",     "php");
  updateLanguageMapping(".inc",      "php");
  updateLanguageMapping(".phtml",    "php");
  updateLanguageMapping(".m",        "objective-c");
  updateLanguageMapping(".M",        "objective-c");
  updateLanguageMapping(".mm",       "objective-c");
  updateLanguageMapping(".py",       "python");
  updateLanguageMapping(".f",        "fortran");
  updateLanguageMapping(".for",      "fortran");
  updateLanguageMapping(".f90",      "fortran");
  updateLanguageMapping(".vhd",      "vhdl");
  updateLanguageMapping(".vhdl",     "vhdl");
  updateLanguageMapping(".tcl",      "tcl");
  updateLanguageMapping(".ucf",      "vhdl");
  updateLanguageMapping(".qsf",      "vhdl");
  updateLanguageMapping(".md",       "md");
  updateLanguageMapping(".markdown", "md");
6854

Dimitri van Heesch's avatar
Dimitri van Heesch committed
6855
  //updateLanguageMapping(".xml",   "dbusxml");
6856 6857
}

6858 6859 6860 6861 6862
SrcLangExt getLanguageFromFileName(const QCString fileName)
{
  int i = fileName.findRev('.');
  if (i!=-1) // name has an extension
  {
6863
    QCString extStr=fileName.right(fileName.length()-i).lower();
6864 6865
    if (!extStr.isEmpty()) // non-empty extension
    {
6866
      int *pVal=g_extLookup.find(extStr);
6867 6868
      if (pVal) // listed extension
      {
6869
        //printf("getLanguageFromFileName(%s)=%x\n",extStr.data(),*pVal);
6870
        return (SrcLangExt)*pVal; 
6871 6872 6873
      }
    }
  }
6874
  //printf("getLanguageFromFileName(%s) not found!\n",fileName.data());
6875 6876 6877
  return SrcLangExt_Cpp; // not listed => assume C-ish language.
}

6878 6879
//--------------------------------------------------------------------------

6880 6881
MemberDef *getMemberFromSymbol(Definition *scope,FileDef *fileScope, 
                                const char *n)
6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893
{
  if (scope==0 ||
      (scope->definitionType()!=Definition::TypeClass &&
       scope->definitionType()!=Definition::TypeNamespace
      )
     )
  {
    scope=Doxygen::globalScope;
  }

  QCString name = n;
  if (name.isEmpty())
6894
    return 0; // no name was given
6895

6896 6897
  DefinitionIntf *di = Doxygen::symbolMap->find(name);
  if (di==0)
6898
    return 0; // could not find any matching symbols
6899 6900 6901 6902 6903 6904 6905 6906 6907 6908

  // mostly copied from getResolvedClassRec()
  QCString explicitScopePart;
  int qualifierIndex = computeQualifiedIndex(name);
  if (qualifierIndex!=-1)
  {
    explicitScopePart = name.left(qualifierIndex);
    replaceNamespaceAliases(explicitScopePart,explicitScopePart.length());
    name = name.mid(qualifierIndex+2);
  }
6909
  //printf("explicitScopePart=%s\n",explicitScopePart.data());
6910

6911 6912
  int minDistance = 10000;
  MemberDef *bestMatch = 0;
6913 6914

  if (di->definitionType()==DefinitionIntf::TypeSymbolList)
6915
  {
6916
    //printf("multiple matches!\n");
6917 6918 6919 6920
    // find the closest closest matching definition
    DefinitionListIterator dli(*(DefinitionList*)di);
    Definition *d;
    for (dli.toFirst();(d=dli.current());++dli)
6921
    {
6922
      if (d->definitionType()==Definition::TypeMember)
6923
      {
6924 6925 6926 6927 6928 6929
        g_visitedNamespaces.clear();
        int distance = isAccessibleFromWithExpScope(scope,fileScope,d,explicitScopePart);
        if (distance!=-1 && distance<minDistance)
        {
          minDistance = distance;
          bestMatch = (MemberDef *)d;
6930
          //printf("new best match %s distance=%d\n",bestMatch->qualifiedName().data(),distance);
6931
        }
6932 6933 6934
      }
    }
  }
6935 6936
  else if (di->definitionType()==Definition::TypeMember)
  {
6937
    //printf("unique match!\n");
6938 6939 6940 6941 6942 6943 6944
    Definition *d = (Definition *)di;
    g_visitedNamespaces.clear();
    int distance = isAccessibleFromWithExpScope(scope,fileScope,d,explicitScopePart);
    if (distance!=-1 && distance<minDistance)
    {
      minDistance = distance;
      bestMatch = (MemberDef *)d;
6945
      //printf("new best match %s distance=%d\n",bestMatch->qualifiedName().data(),distance);
6946 6947
    }
  }
6948 6949 6950 6951 6952 6953 6954
  return bestMatch;
}

/*! Returns true iff the given name string appears to be a typedef in scope. */
bool checkIfTypedef(Definition *scope,FileDef *fileScope,const char *n)
{
  MemberDef *bestMatch = getMemberFromSymbol(scope,fileScope,n);
6955 6956 6957 6958 6959 6960

  if (bestMatch && bestMatch->isTypedef())
    return TRUE; // closest matching symbol is a typedef
  else
    return FALSE;
}
6961

6962 6963 6964 6965 6966 6967
const char *writeUtf8Char(FTextStream &t,const char *s)
{
  char c=*s++;
  t << c;
  if (c<0) // multibyte character
  {
6968 6969 6970 6971 6972
    if (((uchar)c&0xE0)==0xC0)
    {
      t << *s++; // 11xx.xxxx: >=2 byte character
    }
    if (((uchar)c&0xF0)==0xE0)
6973 6974 6975
    {
      t << *s++; // 111x.xxxx: >=3 byte character
    }
6976 6977 6978 6979 6980 6981 6982 6983 6984
    if (((uchar)c&0xF8)==0xF0)
    {
      t << *s++; // 1111.xxxx: >=4 byte character
    }
    if (((uchar)c&0xFC)==0xF8)
    {
      t << *s++; // 1111.1xxx: >=5 byte character
    }
    if (((uchar)c&0xFE)==0xFC)
6985
    {
6986
      t << *s++; // 1111.1xxx: 6 byte character
6987 6988 6989 6990
    }
  }
  return s;
}
6991

Dimitri van Heesch's avatar
Dimitri van Heesch committed
6992 6993 6994 6995 6996 6997 6998
int nextUtf8CharPosition(const QCString &utf8Str,int len,int startPos)
{
  int bytes=1;
  if (startPos>=len) return len;
  char c = utf8Str[startPos];
  if (c<0) // multibyte utf-8 character
  {
6999 7000 7001 7002 7003
    if (((uchar)c&0xE0)==0xC0)
    {
      bytes++; // 11xx.xxxx: >=2 byte character
    }
    if (((uchar)c&0xF0)==0xE0)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7004 7005 7006
    {
      bytes++; // 111x.xxxx: >=3 byte character
    }
7007 7008 7009 7010 7011 7012 7013 7014 7015
    if (((uchar)c&0xF8)==0xF0)
    {
      bytes++; // 1111.xxxx: >=4 byte character
    }
    if (((uchar)c&0xFC)==0xF8)
    {
      bytes++; // 1111.1xxx: >=5 byte character
    }
    if (((uchar)c&0xFE)==0xFC)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7016
    {
7017
      bytes++; // 1111.1xxx: 6 byte character
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7018 7019
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035
  else if (c=='&') // skip over character entities
  {
    static QRegExp re1("&#[0-9]+;");     // numerical entity
    static QRegExp re2("&[A-Z_a-z]+;");  // named entity
    int l1,l2;
    int i1 = re1.match(utf8Str,startPos,&l1);
    int i2 = re2.match(utf8Str,startPos,&l2);
    if (i1!=-1)
    {
      bytes=l1;
    }
    else if (i2!=-1)
    {
      bytes=l2;
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7036 7037 7038
  return startPos+bytes;
}

7039
QCString parseCommentAsText(const Definition *scope,const MemberDef *md,
7040
    const QCString &doc,const QCString &fileName,int lineNr)
7041
{
7042 7043 7044
  QGString s;
  if (doc.isEmpty()) return s.data();
  FTextStream t(&s);
7045 7046
  DocNode *root = validatingParseDoc(fileName,lineNr,
      (Definition*)scope,(MemberDef*)md,doc,FALSE,FALSE);
7047 7048 7049 7050
  TextDocVisitor *visitor = new TextDocVisitor(t);
  root->accept(visitor);
  delete visitor;
  delete root;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7051
  QCString result = convertCharEntitiesToUTF8(s.data());
7052
  int i=0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7053 7054 7055 7056
  int charCnt=0;
  int l=result.length();
  bool addEllipsis=FALSE;
  while ((i=nextUtf8CharPosition(result,l,i))<l)
7057
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7058 7059 7060 7061 7062 7063
    charCnt++;
    if (charCnt>=80) break;
  }
  if (charCnt>=80) // try to truncate the string
  {
    while ((i=nextUtf8CharPosition(result,l,i))<l && charCnt<100)
7064
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7065
      charCnt++;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7066
      if (result.at(i)>=0 && isspace(result.at(i)))
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7067 7068 7069 7070 7071 7072
      {
        addEllipsis=TRUE;
      }
      else if (result.at(i)==',' || 
               result.at(i)=='.' || 
               result.at(i)=='?')
7073 7074 7075 7076 7077
      {
        break;
      }
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7078
  if (addEllipsis || charCnt==100) result=result.left(i)+"...";
7079 7080 7081
  return result.data();
}

7082 7083 7084 7085
//--------------------------------------------------------------------------------------

static QDict<void> aliasesProcessed;

7086
static QCString expandAliasRec(const QCString s,bool allowRecursion=FALSE);
7087 7088 7089 7090 7091 7092 7093 7094

struct Marker
{
  Marker(int p, int n,int s) : pos(p),number(n),size(s) {}
  int pos; // position in the string
  int number; // argument number
  int size; // size of the marker
};
7095

7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123
/** For a string \a s that starts with a command name, returns the character 
 *  offset within that string representing the first character after the 
 *  command. For an alias with argument, this is the offset to the
 *  character just after the argument list.
 *
 *  Examples:
 *  - s=="a b"      returns 1
 *  - s=="a{2,3} b" returns 6
 *  = s=="#"        returns 0
 */
static int findEndOfCommand(const char *s)
{
  const char *p = s;
  char c;
  int i=0;
  if (p)
  {
    while ((c=*p) && isId(c)) p++;
    if (c=='{')
    {
      QCString args = extractAliasArgs(p,0);
      i+=args.length();
    }
    i+=p-s;
  }
  return i;
}

7124 7125 7126 7127
/** Replaces the markers in an alias definition \a aliasValue 
 *  with the corresponding values found in the comma separated argument 
 *  list \a argList and the returns the result after recursive alias expansion.
 */
7128 7129
static QCString replaceAliasArguments(const QCString &aliasValue,const QCString &argList)
{
7130 7131 7132
  //printf("----- replaceAliasArguments(val=[%s],args=[%s])\n",aliasValue.data(),argList.data());

  // first make a list of arguments from the comma separated argument list
7133
  QList<QCString> args;
7134 7135 7136
  args.setAutoDelete(TRUE);
  int i,l=(int)argList.length();
  int s=0;
7137 7138
  for (i=0;i<l;i++)
  {
7139 7140
    char c = argList.at(i);
    if (c==',' && (i==0 || argList.at(i-1)!='\\')) 
7141 7142 7143 7144
    {
      args.append(new QCString(argList.mid(s,i-s)));
      s=i+1; // start of next argument
    }
7145 7146 7147 7148 7149
    else if (c=='@' || c=='\\')
    {
      // check if this is the start of another aliased command (see bug704172)
      i+=findEndOfCommand(argList.data()+i+1);
    }
7150
  }
7151 7152 7153 7154 7155 7156 7157 7158 7159 7160
  if (l>s) args.append(new QCString(argList.right(l-s)));
  //printf("found %d arguments\n",args.count());

  // next we look for the positions of the markers and add them to a list
  QList<Marker> markerList;
  markerList.setAutoDelete(TRUE);
  l = aliasValue.length();
  int markerStart=0;
  int markerEnd=0;
  for (i=0;i<l;i++)
7161
  {
7162 7163 7164 7165 7166 7167 7168 7169 7170 7171
    if (markerStart==0 && aliasValue.at(i)=='\\') // start of a \xx marker
    {
      markerStart=i+1;
    }
    else if (markerStart>0 && aliasValue.at(i)>='0' && aliasValue.at(i)<='9')
    {
      // read digit that make up the marker number
      markerEnd=i+1;
    }
    else
7172
    {
7173 7174 7175 7176 7177 7178 7179 7180 7181 7182
      if (markerStart>0 && markerEnd>markerStart) // end of marker
      {
        int markerLen = markerEnd-markerStart;
        markerList.append(new Marker(markerStart-1, // include backslash
                    atoi(aliasValue.mid(markerStart,markerLen)),markerLen+1));
        //printf("found marker at %d with len %d and number %d\n",
        //    markerStart-1,markerLen+1,atoi(aliasValue.mid(markerStart,markerLen)));
      }
      markerStart=0; // outside marker
      markerEnd=0;
7183 7184
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196
  if (markerStart>0)
  {
    markerEnd=l;
  }
  if (markerStart>0 && markerEnd>markerStart)
  {
     int markerLen = markerEnd-markerStart;
     markerList.append(new Marker(markerStart-1, // include backslash
                 atoi(aliasValue.mid(markerStart,markerLen)),markerLen+1));
     //printf("found marker at %d with len %d and number %d\n",
     //    markerStart-1,markerLen+1,atoi(aliasValue.mid(markerStart,markerLen)));
  }
7197 7198 7199 7200 7201

  // then we replace the markers with the corresponding arguments in one pass
  QCString result;
  int p=0;
  for (i=0;i<(int)markerList.count();i++)
7202
  {
7203 7204 7205 7206 7207
    Marker *m = markerList.at(i);
    result+=aliasValue.mid(p,m->pos-p);
    //printf("part before marker %d: '%s'\n",i,aliasValue.mid(p,m->pos-p).data());
    if (m->number>0 && m->number<=(int)args.count()) // valid number
    {
7208
      result+=expandAliasRec(*args.at(m->number-1),TRUE);
7209 7210 7211 7212
      //printf("marker index=%d pos=%d number=%d size=%d replacement %s\n",i,m->pos,m->number,m->size,
      //    args.at(m->number-1)->data());
    }
    p=m->pos+m->size; // continue after the marker
7213
  }
7214 7215
  result+=aliasValue.right(l-p); // append remainder
  //printf("string after replacement of markers: '%s'\n",result.data());
7216

7217 7218 7219 7220 7221
  // expand the result again
  result = substitute(result,"\\{","{");
  result = substitute(result,"\\}","}");
  result = expandAliasRec(substitute(result,"\\,",","));

7222 7223 7224
  return result;
}

7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246
static QCString escapeCommas(const QCString &s)
{
  QGString result;
  const char *p = s.data();
  char c,pc=0;
  while ((c=*p++))
  {
    if (c==',' && pc!='\\')
    {
      result+="\\,";
    }
    else
    {
      result+=c;
    }
    pc=c;
  }
  result+='\0';
  //printf("escapeCommas: '%s'->'%s'\n",s.data(),result.data());
  return result.data();
}

7247
static QCString expandAliasRec(const QCString s,bool allowRecursion)
7248 7249 7250 7251 7252 7253 7254 7255 7256 7257
{
  QCString result;
  static QRegExp cmdPat("[\\\\@][a-z_A-Z][a-z_A-Z0-9]*");
  QCString value=s;
  int i,p=0,l;
  while ((i=cmdPat.match(value,p,&l))!=-1)
  {
    result+=value.mid(p,i-p);
    QCString args = extractAliasArgs(value,i+l);
    bool hasArgs = !args.isEmpty();            // found directly after command
7258 7259 7260 7261
    int argsLen = args.length();
    QCString cmd = value.mid(i+1,l-1);
    QCString cmdNoArgs = cmd;
    int numArgs=0;
7262 7263
    if (hasArgs)
    {
7264 7265
      numArgs = countAliasArguments(args);
      cmd += QCString().sprintf("{%d}",numArgs);  // alias name + {n}
7266 7267
    }
    QCString *aliasText=Doxygen::aliasDict.find(cmd);
7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279
    if (numArgs>1 && aliasText==0) 
    { // in case there is no command with numArgs parameters, but there is a command with 1 parameter, 
      // we also accept all text as the argument of that command (so you don't have to escape commas)
      aliasText=Doxygen::aliasDict.find(cmdNoArgs+"{1}");
      if (aliasText)
      {
        cmd = cmdNoArgs+"{1}";
        args = escapeCommas(args); // escape , so that everything is seen as one argument
      }
    }
    //printf("Found command s='%s' cmd='%s' numArgs=%d args='%s' aliasText=%s\n",
    //    s.data(),cmd.data(),numArgs,args.data(),aliasText?aliasText->data():"<none>");
7280
    if ((allowRecursion || aliasesProcessed.find(cmd)==0) && aliasText) // expand the alias
7281 7282
    {
      //printf("is an alias!\n");
7283
      if (!allowRecursion) aliasesProcessed.insert(cmd,(void *)0x8);
7284 7285 7286 7287 7288 7289 7290 7291
      QCString val = *aliasText;
      if (hasArgs)
      {
        val = replaceAliasArguments(val,args);
        //printf("replace '%s'->'%s' args='%s'\n",
        //       aliasText->data(),val.data(),args.data());
      }
      result+=expandAliasRec(val);
7292
      if (!allowRecursion) aliasesProcessed.remove(cmd);
7293
      p=i+l;
7294
      if (hasArgs) p+=argsLen+2;
7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308
    }
    else // command is not an alias
    {
      //printf("not an alias!\n");
      result+=value.mid(i,l);
      p=i+l;
    }
  }
  result+=value.right(value.length()-p);

  //printf("expandAliases '%s'->'%s'\n",s.data(),result.data());
  return result;
}

7309

7310 7311 7312 7313 7314 7315 7316
int countAliasArguments(const QCString argList)
{
  int count=1;
  int l = argList.length();
  int i;
  for (i=0;i<l;i++) 
  {
7317 7318 7319 7320 7321 7322 7323
    char c = argList.at(i);
    if (c==',' && (i==0 || argList.at(i-1)!='\\')) count++;
    else if (c=='@' || c=='\\')
    {
      // check if this is the start of another aliased command (see bug704172)
      i+=findEndOfCommand(argList.data()+i+1);
    }
7324
  }
7325
  //printf("countAliasArguments=%d\n",count);
7326 7327 7328 7329 7330 7331 7332
  return count;
}

QCString extractAliasArgs(const QCString &args,int pos)
{
  int i;
  int bc=0;
7333
  char prevChar=0;
7334 7335 7336 7337
  if (args.at(pos)=='{') // alias has argument
  {
    for (i=pos;i<(int)args.length();i++)
    {
7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348
      if (prevChar!='\\')
      {
        if (args.at(i)=='{') bc++;
        if (args.at(i)=='}') bc--;
        prevChar=args.at(i);
      }
      else
      {
        prevChar=0;
      }

7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381
      if (bc==0) 
      {
        //printf("extractAliasArgs('%s')->'%s'\n",args.data(),args.mid(pos+1,i-pos-1).data());
        return args.mid(pos+1,i-pos-1);
      }
    }
  }
  return "";
}

QCString resolveAliasCmd(const QCString aliasCmd)
{
  QCString result;
  aliasesProcessed.clear();
  //printf("Expanding: '%s'\n",aliasCmd.data());
  result = expandAliasRec(aliasCmd);
  //printf("Expanding result: '%s'->'%s'\n",aliasCmd.data(),result.data());
  return result;
}

QCString expandAlias(const QCString &aliasName,const QCString &aliasValue)
{
  QCString result;
  aliasesProcessed.clear();
  // avoid expanding this command recursively
  aliasesProcessed.insert(aliasName,(void *)0x8);
  // expand embedded commands
  //printf("Expanding: '%s'->'%s'\n",aliasName.data(),aliasValue.data());
  result = expandAliasRec(aliasValue);
  //printf("Expanding result: '%s'->'%s'\n",aliasName.data(),result.data());
  return result;
}

7382 7383 7384
void writeTypeConstraints(OutputList &ol,Definition *d,ArgumentList *al)
{
  if (al==0) return;
7385
  ol.startConstraintList(theTranslator->trTypeConstraints()); 
7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396
  ArgumentListIterator ali(*al);
  Argument *a;
  for (;(a=ali.current());++ali)
  {
    ol.startConstraintParam();
    ol.parseText(a->name);
    ol.endConstraintParam();
    ol.startConstraintType();
    linkifyText(TextGeneratorOLImpl(ol),d,0,0,a->type);
    ol.endConstraintType();
    ol.startConstraintDocs();
7397
    ol.generateDoc(d->docFile(),d->docLine(),d,0,a->docs,TRUE,FALSE);
7398 7399 7400 7401
    ol.endConstraintDocs();
  }
  ol.endConstraintList();
}
7402

7403
//----------------------------------------------------------------------------
7404

7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431
void stackTrace()
{
#ifdef TRACINGSUPPORT
  void *backtraceFrames[128];
  int frameCount = backtrace(backtraceFrames, 128);
  static char cmd[40960];
  char *p = cmd;
  p += sprintf(p,"/usr/bin/atos -p %d ", (int)getpid());
  for (int x = 0; x < frameCount; x++) 
  {
    p += sprintf(p,"%p ", backtraceFrames[x]);
  }
  fprintf(stderr,"========== STACKTRACE START ==============\n");
  if (FILE *fp = popen(cmd, "r"))
  {
    char resBuf[512];
    while (size_t len = fread(resBuf, 1, sizeof(resBuf), fp))
    {
      fwrite(resBuf, 1, len, stderr);
    }
    pclose(fp);
  }
  fprintf(stderr,"============ STACKTRACE END ==============\n");
  //fprintf(stderr,"%s\n", frameStrings[x]);
#endif
}

7432
static int transcodeCharacterBuffer(const char *fileName,BufStr &srcBuf,int size,
7433 7434 7435 7436 7437 7438 7439
           const char *inputEncoding,const char *outputEncoding)
{
  if (inputEncoding==0 || outputEncoding==0) return size;
  if (qstricmp(inputEncoding,outputEncoding)==0) return size;
  void *cd = portable_iconv_open(outputEncoding,inputEncoding);
  if (cd==(void *)(-1)) 
  {
7440
    err("unsupported character conversion: '%s'->'%s': %s\n"
7441 7442 7443 7444 7445 7446 7447 7448
        "Check the INPUT_ENCODING setting in the config file!\n",
        inputEncoding,outputEncoding,strerror(errno));
    exit(1);
  }
  int tmpBufSize=size*4+1;
  BufStr tmpBuf(tmpBufSize);
  size_t iLeft=size;
  size_t oLeft=tmpBufSize;
7449
  char *srcPtr = srcBuf.data();
7450 7451 7452 7453
  char *dstPtr = tmpBuf.data();
  uint newSize=0;
  if (!portable_iconv(cd, &srcPtr, &iLeft, &dstPtr, &oLeft))
  {
7454
    newSize = tmpBufSize-(int)oLeft;
7455 7456 7457 7458 7459 7460
    srcBuf.shrink(newSize);
    strncpy(srcBuf.data(),tmpBuf.data(),newSize);
    //printf("iconv: input size=%d output size=%d\n[%s]\n",size,newSize,srcBuf.data());
  }
  else
  {
7461
    err("%s: failed to translate characters from %s to %s: check INPUT_ENCODING\n",
7462
        fileName,inputEncoding,outputEncoding);
7463 7464 7465 7466 7467 7468 7469
    exit(1);
  }
  portable_iconv_close(cd);
  return newSize;
}

//! read a file name \a fileName and optionally filter and transcode it
7470
bool readInputFile(const char *fileName,BufStr &inBuf,bool filter,bool isSourceCode)
7471 7472 7473 7474 7475 7476 7477 7478
{
  // try to open file
  int size=0;
  //uint oldPos = dest.curPos();
  //printf(".......oldPos=%d\n",oldPos);

  QFileInfo fi(fileName);
  if (!fi.exists()) return FALSE;
7479 7480
  QCString filterName = getFileFilter(fileName,isSourceCode);
  if (filterName.isEmpty() || !filter)
7481 7482 7483 7484
  {
    QFile f(fileName);
    if (!f.open(IO_ReadOnly))
    {
7485
      err("could not open file %s\n",fileName);
7486 7487 7488 7489 7490 7491 7492
      return FALSE;
    }
    size=fi.size();
    // read the file
    inBuf.skip(size);
    if (f.readBlock(inBuf.data()/*+oldPos*/,size)!=size)
    {
7493
      err("problems while reading file %s\n",fileName);
7494 7495 7496 7497 7498 7499 7500 7501 7502 7503
      return FALSE;
    }
  }
  else
  {
    QCString cmd=filterName+" \""+fileName+"\"";
    Debug::print(Debug::ExtCmd,0,"Executing popen(`%s`)\n",cmd.data());
    FILE *f=portable_popen(cmd,"r");
    if (!f)
    {
7504
      err("could not execute filter %s\n",filterName.data());
7505 7506 7507 7508 7509
      return FALSE;
    }
    const int bufSize=1024;
    char buf[bufSize];
    int numRead;
7510
    while ((numRead=(int)fread(buf,1,bufSize,f))>0)
7511 7512 7513 7514 7515
    {
      //printf(">>>>>>>>Reading %d bytes\n",numRead);
      inBuf.addArray(buf,numRead),size+=numRead;
    }
    portable_pclose(f);
7516 7517 7518
    inBuf.at(inBuf.curPos()) ='\0';
    Debug::print(Debug::FilterOutput, 0, "Filter output\n");
    Debug::print(Debug::FilterOutput,0,"-------------\n%s\n-------------\n",inBuf.data());
7519 7520
  }

7521
  int start=0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7522
  if (size>=2 &&
7523 7524 7525 7526 7527
      ((inBuf.at(0)==-1 && inBuf.at(1)==-2) || // Litte endian BOM
       (inBuf.at(0)==-2 && inBuf.at(1)==-1)    // big endian BOM
      )
     ) // UCS-2 encoded file
  {
7528
    transcodeCharacterBuffer(fileName,inBuf,inBuf.curPos(),
7529 7530
        "UCS-2","UTF-8");
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7531
  else if (size>=3 &&
7532 7533 7534
           (uchar)inBuf.at(0)==0xEF &&
           (uchar)inBuf.at(1)==0xBB &&
           (uchar)inBuf.at(2)==0xBF
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7535
     ) // UTF-8 encoded file
7536 7537 7538
  {
    inBuf.dropFromStart(3); // remove UTF-8 BOM: no translation needed
  }
7539 7540 7541
  else // transcode according to the INPUT_ENCODING setting
  {
    // do character transcoding if needed.
7542
    transcodeCharacterBuffer(fileName,inBuf,inBuf.curPos(),
7543 7544 7545
        Config_getString("INPUT_ENCODING"),"UTF-8");
  }

7546
  //inBuf.addChar('\n'); /* to prevent problems under Windows ? */
7547 7548

  // and translate CR's
7549 7550
  size=inBuf.curPos()-start;
  int newSize=filterCRLF(inBuf.data()+start,size);
7551 7552 7553 7554 7555 7556
  //printf("filter char at %p size=%d newSize=%d\n",dest.data()+oldPos,size,newSize);
  if (newSize!=size) // we removed chars
  {
    inBuf.shrink(newSize); // resize the array
    //printf(".......resizing from %d to %d result=[%s]\n",oldPos+size,oldPos+newSize,dest.data());
  }
7557
  inBuf.addChar(0);
7558 7559 7560
  return TRUE;
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575
// Replace %word by word in title
QCString filterTitle(const QCString &title)
{
  QCString tf;
  static QRegExp re("%[A-Z_a-z]");
  int p=0,i,l;
  while ((i=re.match(title,p,&l))!=-1)
  {
    tf+=title.mid(p,i-p);
    tf+=title.mid(i+1,l-1); // skip %
    p=i+l;
  }
  tf+=title.right(title.length()-p);
  return tf;
}
7576

7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599
//----------------------------------------------------------------------------
// returns TRUE if the name of the file represented by `fi' matches
// one of the file patterns in the `patList' list.

bool patternMatch(const QFileInfo &fi,const QStrList *patList)
{
  bool found=FALSE;
  if (patList)
  { 
    QStrListIterator it(*patList);
    QCString pattern;
    for (it.toFirst();(pattern=it.current());++it)
    {
      if (!pattern.isEmpty() && !found)
      {
        int i=pattern.find('=');
        if (i!=-1) pattern=pattern.left(i); // strip of the extension specific filter name

#if defined(_WIN32) || defined(__MACOSX__) // Windows or MacOSX
        QRegExp re(pattern,FALSE,TRUE); // case insensitive match 
#else                // unix
        QRegExp re(pattern,TRUE,TRUE);  // case sensitive match
#endif
7600 7601 7602
        found = found || re.match(fi.fileName().data())!=-1 || 
                         re.match(fi.filePath().data())!=-1 ||
                         re.match(fi.absFilePath().data())!=-1;
7603 7604 7605 7606 7607 7608 7609 7610
        //printf("Matching `%s' against pattern `%s' found=%d\n",
        //    fi->fileName().data(),pattern.data(),found);
      }
    }
  }
  return found;
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
7611
#if 0 // move to HtmlGenerator::writeSummaryLink
7612
void writeSummaryLink(OutputList &ol,const char *label,const char *title,
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7613
                      bool &first,const char *file)
7614 7615 7616 7617 7618 7619 7620 7621 7622 7623
{
  if (first)
  {
    ol.writeString("  <div class=\"summary\">\n");
    first=FALSE;
  }
  else
  {
    ol.writeString(" &#124;\n");
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634
  if (file)
  {
    ol.writeString("<a href=\"");
    ol.writeString(file);
    ol.writeString(Doxygen::htmlFileExtension);
  }
  else
  {
    ol.writeString("<a href=\"#");
    ol.writeString(label);
  }
7635 7636 7637 7638
  ol.writeString("\">");
  ol.writeString(title);
  ol.writeString("</a>");
}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7639
#endif
7640

7641 7642 7643 7644 7645
QCString externalLinkTarget()
{
  static bool extLinksInWindow = Config_getBool("EXT_LINKS_IN_WINDOW");
  if (extLinksInWindow) return "target=\"_blank\" "; else return "";
}
7646

7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661
QCString externalRef(const QCString &relPath,const QCString &ref,bool href)
{
  QCString result;
  if (!ref.isEmpty())
  {
    QCString *dest = Doxygen::tagDestinationDict[ref];
    if (dest)
    {
      result = *dest;
      int l = result.length();
      if (!relPath.isEmpty() && l>0 && result.at(0)=='.')
      { // relative path -> prepend relPath.
        result.prepend(relPath);
      }
      if (!href) result.prepend("doxygen=\""+ref+":");
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7662
      if (l>0 && result.at(l-1)!='/') result+='/';
7663 7664 7665 7666 7667 7668 7669 7670 7671
      if (!href) result.append("\" ");
    }
  }
  else
  {
    result = relPath;
  }
  return result;
}
7672

Dimitri van Heesch's avatar
Dimitri van Heesch committed
7673 7674 7675
/** Writes the intensity only bitmap representated by \a data as an image to 
 *  directory \a dir using the colors defined by HTML_COLORSTYLE_*.
 */
7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695
void writeColoredImgData(const char *dir,ColoredImgDataItem data[])
{
  static int hue   = Config_getInt("HTML_COLORSTYLE_HUE");
  static int sat   = Config_getInt("HTML_COLORSTYLE_SAT");
  static int gamma = Config_getInt("HTML_COLORSTYLE_GAMMA");
  while (data->name)
  {
    QCString fileName;
    fileName=(QCString)dir+"/"+data->name;
    QFile f(fileName);
    if (f.open(IO_WriteOnly))
    {
      ColoredImage img(data->width,data->height,data->content,data->alpha,
                       sat,hue,gamma);
      img.save(fileName);
    }
    else
    {
      fprintf(stderr,"Warning: Cannot open file %s for writing\n",data->name);
    }
7696
    Doxygen::indexList->addImageFile(data->name);
7697 7698 7699 7700
    data++;
  }
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
7701 7702 7703 7704 7705
/** Replaces any markers of the form \#\#AA in input string \a str
 *  by new markers of the form \#AABBCC, where \#AABBCC represents a 
 *  valid color, based on the intensity represented by hex number AA 
 *  and the current HTML_COLORSTYLE_* settings.
 */
7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749
QCString replaceColorMarkers(const char *str)
{
  QCString result;
  QCString s=str;
  if (s.isEmpty()) return result;
  static QRegExp re("##[0-9A-Fa-f][0-9A-Fa-f]");
  static const char hex[] = "0123456789ABCDEF";
  static int hue   = Config_getInt("HTML_COLORSTYLE_HUE");
  static int sat   = Config_getInt("HTML_COLORSTYLE_SAT");
  static int gamma = Config_getInt("HTML_COLORSTYLE_GAMMA");
  int i,l,sl=s.length(),p=0;
  while ((i=re.match(s,p,&l))!=-1)
  {
    result+=s.mid(p,i-p);
    QCString lumStr = s.mid(i+2,l-2);
#define HEXTONUM(x) (((x)>='0' && (x)<='9') ? ((x)-'0') :       \
                     ((x)>='a' && (x)<='f') ? ((x)-'a'+10) :    \
                     ((x)>='A' && (x)<='F') ? ((x)-'A'+10) : 0)
    
    double r,g,b;
    int red,green,blue;
    int level = HEXTONUM(lumStr[0])*16+HEXTONUM(lumStr[1]);
    ColoredImage::hsl2rgb(hue/360.0,sat/255.0,
                          pow(level/255.0,gamma/100.0),&r,&g,&b);
    red   = (int)(r*255.0);
    green = (int)(g*255.0);
    blue  = (int)(b*255.0);
    char colStr[8];
    colStr[0]='#';
    colStr[1]=hex[red>>4];
    colStr[2]=hex[red&0xf];
    colStr[3]=hex[green>>4];
    colStr[4]=hex[green&0xf];
    colStr[5]=hex[blue>>4];
    colStr[6]=hex[blue&0xf];
    colStr[7]=0;
    //printf("replacing %s->%s (level=%d)\n",lumStr.data(),colStr,level);
    result+=colStr;
    p=i+l;
  }
  result+=s.right(sl-p);
  return result;
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
7750 7751 7752
/** Copies the contents of file with name \a src to the newly created 
 *  file with name \a dest. Returns TRUE if successful.
 */
7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769
bool copyFile(const QCString &src,const QCString &dest)
{
  QFile sf(src);
  if (sf.open(IO_ReadOnly))
  {
    QFileInfo fi(src);
    QFile df(dest);
    if (df.open(IO_WriteOnly))
    {
      char *buffer = new char[fi.size()];
      sf.readBlock(buffer,fi.size());
      df.writeBlock(buffer,fi.size());
      df.flush();
      delete[] buffer;
    }
    else
    {
7770
      err("could not write to file %s\n",dest.data());
7771 7772 7773 7774 7775
      return FALSE;
    }
  }
  else
  {
7776
    err("could not open user specified file %s\n",src.data());
7777 7778 7779 7780 7781
    return FALSE;
  }
  return TRUE;
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804
/** Returns the section of text, in between a pair of markers. 
 *  Full lines are returned, excluding the lines on which the markers appear.
 */
QCString extractBlock(const QCString text,const QCString marker)
{
  QCString result;
  int p=0,i;
  bool found=FALSE;

  // find the character positions of the markers
  int m1 = text.find(marker);
  if (m1==-1) return result;
  int m2 = text.find(marker,m1+marker.length());
  if (m2==-1) return result;

  // find start and end line positions for the markers
  int l1=-1,l2=-1;
  while (!found && (i=text.find('\n',p))!=-1)
  {
    found = (p<=m1 && m1<i); // found the line with the start marker
    p=i+1;
  }
  l1=p;
7805
  int lp=i;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7806 7807 7808 7809 7810 7811 7812 7813 7814 7815
  if (found)
  {
    while ((i=text.find('\n',p))!=-1)
    {
      if (p<=m2 && m2<i) // found the line with the end marker
      {
        l2=p;
        break;
      }
      p=i+1;
7816
      lp=i;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7817 7818
    }
  }
7819 7820 7821 7822
  if (l2==-1) // marker at last line without newline (see bug706874)
  {
    l2=lp;
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7823
  //printf("text=[%s]\n",text.mid(l1,l2-l1).data());
7824
  return l2>l1 ? text.mid(l1,l2-l1) : QCString();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7825 7826 7827 7828 7829 7830 7831
}

/** Returns a string representation of \a lang. */
QCString langToString(SrcLangExt lang)
{
  switch(lang)
  {
7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846
    case SrcLangExt_Unknown:  return "Unknown";
    case SrcLangExt_IDL:      return "IDL";
    case SrcLangExt_Java:     return "Java";
    case SrcLangExt_CSharp:   return "C#";
    case SrcLangExt_D:        return "D";
    case SrcLangExt_PHP:      return "PHP";
    case SrcLangExt_ObjC:     return "Objective-C";
    case SrcLangExt_Cpp:      return "C++";
    case SrcLangExt_JS:       return "Javascript";
    case SrcLangExt_Python:   return "Python";
    case SrcLangExt_Fortran:  return "Fortran";
    case SrcLangExt_VHDL:     return "VHDL";
    case SrcLangExt_XML:      return "XML";
    case SrcLangExt_Tcl:      return "Tcl";
    case SrcLangExt_Markdown: return "Markdown";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7847 7848 7849 7850 7851
  }
  return "Unknown";
}

/** Returns the scope separator to use given the programming language \a lang */
7852
QCString getLanguageSpecificSeparator(SrcLangExt lang,bool classScope)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7853
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7854
  if (lang==SrcLangExt_Java || lang==SrcLangExt_CSharp || lang==SrcLangExt_VHDL || lang==SrcLangExt_Python)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7855 7856 7857
  {
    return ".";
  }
7858
  else if (lang==SrcLangExt_PHP && !classScope)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7859 7860 7861 7862 7863 7864 7865 7866 7867
  {
    return "\\";
  }
  else
  {
    return "::";
  }
}

7868 7869 7870 7871 7872 7873 7874 7875
/** Corrects URL \a url according to the relative path \a relPath.
 *  Returns the corrected URL. For absolute URLs no correction will be done.
 */
QCString correctURL(const QCString &url,const QCString &relPath)
{
  QCString result = url;
  if (!relPath.isEmpty() && 
      url.left(5)!="http:" && url.left(6)!="https:" && 
7876
      url.left(4)!="ftp:"  && url.left(5)!="file:")
7877 7878 7879 7880 7881 7882
  {
    result.prepend(relPath);
  }
  return result;
}

7883
//---------------------------------------------------------------------------
7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894

bool protectionLevelVisible(Protection prot)
{
  static bool extractPrivate = Config_getBool("EXTRACT_PRIVATE");
  static bool extractPackage = Config_getBool("EXTRACT_PACKAGE");

  return (prot!=Private && prot!=Package)  || 
         (prot==Private && extractPrivate) || 
         (prot==Package && extractPackage);
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975
//---------------------------------------------------------------------------

QCString stripIndentation(const QCString &s)
{
  if (s.isEmpty()) return s; // empty string -> we're done

  //printf("stripIndentation:\n%s\n------\n",s.data());
  // compute minimum indentation over all lines
  const char *p=s.data();
  char c;
  int indent=0;
  int minIndent=1000000; // "infinite"
  bool searchIndent=TRUE;
  static int tabSize=Config_getInt("TAB_SIZE");
  while ((c=*p++))
  {
    if      (c=='\t') indent+=tabSize - (indent%tabSize);
    else if (c=='\n') indent=0,searchIndent=TRUE;
    else if (c==' ')  indent++;
    else if (searchIndent) 
    {
      searchIndent=FALSE;
      if (indent<minIndent) minIndent=indent;
    }
  }

  // no indent to remove -> we're done
  if (minIndent==0) return s;

  // remove minimum indentation for each line
  QGString result;
  p=s.data();
  indent=0;
  while ((c=*p++))
  {
    if (c=='\n') // start of new line
    {
      indent=0;
      result+=c;
    }
    else if (indent<minIndent) // skip until we reach minIndent
    {
      if (c=='\t')
      {
        int newIndent = indent+tabSize-(indent%tabSize);
        int i=newIndent;
        while (i>minIndent) // if a tab crosses the minIndent boundary fill the rest with spaces
        {
          result+=' ';
          i--;
        }
        indent=newIndent;
      }
      else // space
      {
        indent++;
      }
    }
    else // copy anything until the end of the line
    {
      result+=c;
    }
  }

  result+='\0';
  return result.data();
}


bool fileVisibleInIndex(FileDef *fd,bool &genSourceFile)
{
  static bool allExternals = Config_getBool("ALLEXTERNALS");
  bool isDocFile = fd->isDocumentationFile();
  genSourceFile = !isDocFile && fd->generateSourceFile();
  return ( ((allExternals && fd->isLinkable()) ||
            fd->isLinkableInProject()
           ) && 
           !isDocFile
         );
}

7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018
void addDocCrossReference(MemberDef *src,MemberDef *dst)
{
  static bool referencedByRelation = Config_getBool("REFERENCED_BY_RELATION");
  static bool referencesRelation   = Config_getBool("REFERENCES_RELATION");
  static bool callerGraph          = Config_getBool("CALLER_GRAPH");
  static bool callGraph            = Config_getBool("CALL_GRAPH");

  //printf("--> addDocCrossReference src=%s,dst=%s\n",src->name().data(),dst->name().data());
  if (dst->isTypedef() || dst->isEnumerate()) return; // don't add types
  if ((referencedByRelation || callerGraph || dst->hasCallerGraph()) && 
      src->showInCallGraph()
     )
  {
    dst->addSourceReferencedBy(src);
    MemberDef *mdDef = dst->memberDefinition();
    if (mdDef)
    {
      mdDef->addSourceReferencedBy(src);
    }
    MemberDef *mdDecl = dst->memberDeclaration();
    if (mdDecl)
    {
      mdDecl->addSourceReferencedBy(src);
    }
  }
  if ((referencesRelation || callGraph || src->hasCallGraph()) && 
      src->showInCallGraph()
     )
  {
    src->addSourceReferences(dst);
    MemberDef *mdDef = src->memberDefinition();
    if (mdDef)
    {
      mdDef->addSourceReferences(dst);
    }
    MemberDef *mdDecl = src->memberDeclaration();
    if (mdDecl)
    {
      mdDecl->addSourceReferences(dst);
    }
  }
}

8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087
//--------------------------------------------------------------------------------------

/*! @brief Get one unicode character as an unsigned integer from utf-8 string
 *
 * @param s utf-8 encoded string
 * @param idx byte position of given string \a s.
 * @return the unicode codepoint, 0 - MAX_UNICODE_CODEPOINT
 * @see getNextUtf8OrToLower()
 * @see getNextUtf8OrToUpper()
 */
uint getUtf8Code( const QCString& s, int idx )
{
  const int length = s.length();
  if (idx >= length) { return 0; }
  const uint c0 = (uchar)s.at(idx);
  if ( c0 < 0xC2 || c0 >= 0xF8 ) // 1 byte character
  {
    return c0;
  }
  if (idx+1 >= length) { return 0; }
  const uint c1 = ((uchar)s.at(idx+1)) & 0x3f;
  if ( c0 < 0xE0 ) // 2 byte character
  {
    return ((c0 & 0x1f) << 6) | c1;
  }
  if (idx+2 >= length) { return 0; }
  const uint c2 = ((uchar)s.at(idx+2)) & 0x3f;
  if ( c0 < 0xF0 ) // 3 byte character
  {
    return ((c0 & 0x0f) << 12) | (c1 << 6) | c2;
  }
  if (idx+3 >= length) { return 0; }
  // 4 byte character
  const uint c3 = ((uchar)s.at(idx+3)) & 0x3f;
  return ((c0 & 0x07) << 18) | (c1 << 12) | (c2 << 6) | c3;
}


/*! @brief Returns one unicode character as an unsigned integer 
 *  from utf-8 string, making the character lower case if it was upper case.
 *
 * @param s utf-8 encoded string
 * @param idx byte position of given string \a s.
 * @return the unicode codepoint, 0 - MAX_UNICODE_CODEPOINT, excludes 'A'-'Z'
 * @see getNextUtf8Code()
*/
uint getUtf8CodeToLower( const QCString& s, int idx )
{
  const uint v = getUtf8Code( s, idx );
  return v < 0x7f ? tolower( v ) : v;
}


/*! @brief Returns one unicode character as ian unsigned interger 
 *  from utf-8 string, making the character upper case if it was lower case.
 *
 * @param s utf-8 encoded string
 * @param idx byte position of given string \a s.
 * @return the unicode codepoint, 0 - MAX_UNICODE_CODEPOINT, excludes 'A'-'Z'
 * @see getNextUtf8Code()
 */
uint getUtf8CodeToUpper( const QCString& s, int idx )
{
  const uint v = getUtf8Code( s, idx );
  return v < 0x7f ? toupper( v ) : v;
}

//--------------------------------------------------------------------------------------

8088 8089 8090 8091 8092 8093 8094 8095
bool namespaceHasVisibleChild(NamespaceDef *nd,bool includeClasses)
{
  if (nd->getNamespaceSDict())
  {
    NamespaceSDict::Iterator cnli(*nd->getNamespaceSDict());
    NamespaceDef *cnd;
    for (cnli.toFirst();(cnd=cnli.current());++cnli)
    {
8096
      if (cnd->isLinkableInProject() && cnd->localName().find('@')==-1)
8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128
      {
        return TRUE;
      }
      else if (namespaceHasVisibleChild(cnd,includeClasses))
      {
        return TRUE;
      }
    }
  }
  if (includeClasses && nd->getClassSDict())
  {
    ClassSDict::Iterator cli(*nd->getClassSDict());
    ClassDef *cd;
    for (;(cd=cli.current());++cli)
    {
      if (cd->isLinkableInProject() && cd->templateMaster()==0) 
      { 
        return TRUE;
      }
    }
  }
  return FALSE;
}

//----------------------------------------------------------------------------

bool classVisibleInIndex(ClassDef *cd)
{
  static bool allExternals = Config_getBool("ALLEXTERNALS");
  return (allExternals && cd->isLinkable()) || cd->isLinkableInProject();
}

8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151
//----------------------------------------------------------------------------

QCString extractDirection(QCString &docs)
{
  QRegExp re("\\[[^\\]]+\\]"); // [...]
  int l=0;
  if (re.match(docs,0,&l)==0)
  {
    int  inPos  = docs.find("in", 1,FALSE);
    int outPos  = docs.find("out",1,FALSE);
    bool input  =  inPos!=-1 &&  inPos<l;
    bool output = outPos!=-1 && outPos<l;
    if (input || output) // in,out attributes
    {
      docs = docs.mid(l); // strip attributes
      if (input && output) return "[in,out]";
      else if (input)      return "[in]";
      else if (output)     return "[out]";
    }
  }
  return QCString();
}

8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341
//-----------------------------------------------------------

/** Computes for a given list type \a inListType, which are the
 *  the corresponding list type(s) in the base class that are to be
 *  added to this list.
 *
 *  So for public inheritance, the mapping is 1-1, so outListType1=inListType
 *  Private members are to be hidden completely.
 *
 *  For protected inheritance, both protected and public members of the
 *  base class should be joined in the protected member section.
 *
 *  For private inheritance, both protected and public members of the
 *  base class should be joined in the private member section.
 */
void convertProtectionLevel(
                   MemberListType inListType,
                   Protection inProt,
                   int *outListType1,
                   int *outListType2
                  )
{
  static bool extractPrivate = Config_getBool("EXTRACT_PRIVATE");
  // default representing 1-1 mapping
  *outListType1=inListType;
  *outListType2=-1;
  if (inProt==Public)
  {
    switch (inListType) // in the private section of the derived class,
                        // the private section of the base class should not
                        // be visible
    {
      case MemberListType_priMethods:
      case MemberListType_priStaticMethods:
      case MemberListType_priSlots:
      case MemberListType_priAttribs:
      case MemberListType_priStaticAttribs:
      case MemberListType_priTypes:
        *outListType1=-1;
        *outListType2=-1;
        break;
      default:
        break;
    }
  }
  else if (inProt==Protected) // Protected inheritance
  {
    switch (inListType) // in the protected section of the derived class,
                        // both the public and protected members are shown
                        // as protected
    {
      case MemberListType_pubMethods:
      case MemberListType_pubStaticMethods:
      case MemberListType_pubSlots:
      case MemberListType_pubAttribs:
      case MemberListType_pubStaticAttribs:
      case MemberListType_pubTypes:
      case MemberListType_priMethods:
      case MemberListType_priStaticMethods:
      case MemberListType_priSlots:
      case MemberListType_priAttribs:
      case MemberListType_priStaticAttribs:
      case MemberListType_priTypes:
        *outListType1=-1;
        *outListType2=-1;
        break;

      case MemberListType_proMethods:
        *outListType2=MemberListType_pubMethods;
        break;
      case MemberListType_proStaticMethods:
        *outListType2=MemberListType_pubStaticMethods;
        break;
      case MemberListType_proSlots:
        *outListType2=MemberListType_pubSlots;
        break;
      case MemberListType_proAttribs:
        *outListType2=MemberListType_pubAttribs;
        break;
      case MemberListType_proStaticAttribs:
        *outListType2=MemberListType_pubStaticAttribs;
        break;
      case MemberListType_proTypes:
        *outListType2=MemberListType_pubTypes;
        break;
      default:
        break;
    }
  }
  else if (inProt==Private)
  {
    switch (inListType) // in the private section of the derived class,
                        // both the public and protected members are shown
                        // as private
    {
      case MemberListType_pubMethods:
      case MemberListType_pubStaticMethods:
      case MemberListType_pubSlots:
      case MemberListType_pubAttribs:
      case MemberListType_pubStaticAttribs:
      case MemberListType_pubTypes:
      case MemberListType_proMethods:
      case MemberListType_proStaticMethods:
      case MemberListType_proSlots:
      case MemberListType_proAttribs:
      case MemberListType_proStaticAttribs:
      case MemberListType_proTypes:
        *outListType1=-1;
        *outListType2=-1;
        break;

      case MemberListType_priMethods:
        if (extractPrivate)
        {
          *outListType1=MemberListType_pubMethods;
          *outListType2=MemberListType_proMethods;
        }
        else
        {
          *outListType1=-1;
          *outListType2=-1;
        }
        break;
      case MemberListType_priStaticMethods:
        if (extractPrivate)
        {
          *outListType1=MemberListType_pubStaticMethods;
          *outListType2=MemberListType_proStaticMethods;
        }
        else
        {
          *outListType1=-1;
          *outListType2=-1;
        }
        break;
      case MemberListType_priSlots:
        if (extractPrivate)
        {
          *outListType1=MemberListType_pubSlots;
          *outListType1=MemberListType_proSlots;
        }
        else
        {
          *outListType1=-1;
          *outListType2=-1;
        }
        break;
      case MemberListType_priAttribs:
        if (extractPrivate)
        {
          *outListType1=MemberListType_pubAttribs;
          *outListType2=MemberListType_proAttribs;
        }
        else
        {
          *outListType1=-1;
          *outListType2=-1;
        }
        break;
      case MemberListType_priStaticAttribs:
        if (extractPrivate)
        {
          *outListType1=MemberListType_pubStaticAttribs;
          *outListType2=MemberListType_proStaticAttribs;
        }
        else
        {
          *outListType1=-1;
          *outListType2=-1;
        }
        break;
      case MemberListType_priTypes:
        if (extractPrivate)
        {
          *outListType1=MemberListType_pubTypes;
          *outListType2=MemberListType_proTypes;
        }
        else
        {
          *outListType1=-1;
          *outListType2=-1;
        }
        break;
      default:
        break;
    }
  }
  //printf("convertProtectionLevel(type=%d prot=%d): %d,%d\n",
  //    inListType,inProt,*outListType1,*outListType2);
}