util.cpp 242 KB
Newer Older
1
/*****************************************************************************
2
 * 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3
 *
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4
 * Copyright (C) 1997-2014 by Dimitri van Heesch.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5 6 7 8 9 10 11
 *
 * 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
12 13
 * 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
14 15 16 17 18
 *
 */

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

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

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

Dimitri van Heesch's avatar
Dimitri van Heesch committed
30 31 32 33 34 35 36 37 38
#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"
39
#include "htmlhelp.h"
40
#include "example.h"
41
#include "version.h"
Dimitri van Heesch's avatar
Dimitri van Heesch committed
42
#include "groupdef.h"
43
#include "reflist.h"
44
#include "pagedef.h"
45
#include "debug.h"
46
#include "searchindex.h"
47
#include "doxygen.h"
48
#include "textdocvisitor.h"
49
#include "portable.h"
50
#include "parserintf.h"
51
#include "bufstr.h"
52
#include "image.h"
53
#include "growbuf.h"
54 55
#include "entry.h"
#include "arguments.h"
56 57 58 59 60 61 62
#include "memberlist.h"
#include "classlist.h"
#include "namespacedef.h"
#include "membername.h"
#include "filename.h"
#include "membergroup.h"
#include "dirdef.h"
63
#include "htmlentity.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;
1670
  char c;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1671
  for (i=0;i<l;i++)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1672
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1673
nextChar:
1674
    c=s.at(i);
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697

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

1840 1841 1842 1843
/**
 * Returns the position in the string where a function parameter list
 * begins, or -1 if one is not found.
 */
1844
int findParameterList(const QCString &name)
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
{
  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;
      }
1859
      else if (nextClosePos!=-1)
1860 1861 1862 1863
      {
        --templateDepth;
        pos=nextClosePos-1;
      }
1864 1865 1866 1867
      else // more >'s than <'s, see bug701295
      {
        return -1;
      }
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879
    }
    else
    {
      int lastAnglePos=name.findRev('>', pos);
      int bracePos=name.findRev('(', pos);
      if (lastAnglePos!=-1 && lastAnglePos>bracePos)
      {
        ++templateDepth;
        pos=lastAnglePos-1;
      }
      else
      {
1880
        int bp = bracePos>0 ? name.findRev('(',bracePos-1) : -1;
1881 1882
        // bp test is to allow foo(int(&)[10]), but we need to make an exception for operator()
        return bp==-1 || (bp>=8 && name.mid(bp-8,10)=="operator()") ? bracePos : bp;
1883 1884 1885 1886 1887 1888
      }
    }
  } while (pos!=-1);
  return -1;
}

1889
bool rightScopeMatch(const QCString &scope, const QCString &name)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1890
{
1891 1892
  int sl=scope.length();
  int nl=name.length();
1893
  return (name==scope || // equal 
1894 1895 1896 1897
          (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
1898 1899
}

1900
bool leftScopeMatch(const QCString &scope, const QCString &name)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1901
{
1902 1903
  int sl=scope.length();
  int nl=name.length();
1904
  return (name==scope || // equal 
1905 1906 1907 1908
          (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
1909 1910
}

1911

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

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

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

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

2064 2065
      //printf("ScopeName=%s\n",scopeName.data());
      //if (!found) printf("Trying to link %s in %s\n",word.data(),scopeName.data()); 
2066
      if (!found && 
2067
          getDefs(scopeName,matchWord,0,md,cd,fd,nd,gd) && 
2068 2069 2070
          //(md->isTypedef() || md->isEnumerate() || 
          // md->isReference() || md->isVariable()
          //) && 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2071
          (external ? md->isLinkable() : md->isLinkableInProject()) 
2072
         )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2073
      {
2074
        //printf("Found ref scope=%s\n",d?d->name().data():"<global>");
2075 2076
        //ol.writeObjectLink(d->getReference(),d->getOutputFileBase(),
        //                       md->anchor(),word);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2077 2078 2079 2080 2081 2082 2083 2084
        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
2085 2086
      }
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2087 2088

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


Dimitri van Heesch's avatar
Dimitri van Heesch committed
2102
void writeExample(OutputList &ol,ExampleSDict *ed)
2103
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2104
  QCString exampleLine=theTranslator->trWriteList(ed->count());
2105

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2106 2107 2108
  //bool latexEnabled = ol.isEnabled(OutputGenerator::Latex);
  //bool manEnabled   = ol.isEnabled(OutputGenerator::Man);
  //bool htmlEnabled  = ol.isEnabled(OutputGenerator::Html);
2109 2110 2111 2112 2113 2114
  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;
2115
    ol.parseText(exampleLine.mid(index,newIndex-index));
2116
    uint entryIndex = exampleLine.mid(newIndex+1,matchLen-1).toUInt(&ok);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2117
    Example *e=ed->at(entryIndex);
2118 2119
    if (ok && e) 
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2120 2121 2122 2123
      ol.pushGeneratorState();
      //if (latexEnabled) ol.disable(OutputGenerator::Latex);
      ol.disable(OutputGenerator::Latex);
      ol.disable(OutputGenerator::RTF);
2124
      // link for Html / man
2125
      //printf("writeObjectLink(file=%s)\n",e->file.data());
2126
      ol.writeObjectLink(0,e->file,e->anchor,e->name);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2127
      ol.popGeneratorState();
2128

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2129 2130 2131 2132
      ol.pushGeneratorState();
      //if (latexEnabled) ol.enable(OutputGenerator::Latex);
      ol.disable(OutputGenerator::Man);
      ol.disable(OutputGenerator::Html);
2133 2134 2135
      // 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
2136 2137 2138
      //if (manEnabled) ol.enable(OutputGenerator::Man);
      //if (htmlEnabled) ol.enable(OutputGenerator::Html);
      ol.popGeneratorState();
2139
    }
2140 2141
    index=newIndex+matchLen;
  } 
2142
  ol.parseText(exampleLine.right(exampleLine.length()-index));
2143 2144 2145 2146
  ol.writeString(".");
}


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

2193
QCString tempArgListToString(ArgumentList *al,SrcLangExt lang)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2194
{
2195
  QCString result;
2196
  if (al==0) return result;
2197
  result="<";
2198 2199
  ArgumentListIterator ali(*al);
  Argument *a=ali.current();
2200
  while (a)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2201
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2202
    if (!a->name.isEmpty()) // add template argument name
2203
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2204 2205 2206 2207 2208 2209 2210 2211
      if (a->type.left(4)=="out") // C# covariance
      {
        result+="out ";
      }
      else if (a->type.left(3)=="in") // C# contravariance
      {
        result+="in ";
      }
2212 2213 2214 2215
      if (lang==SrcLangExt_Java || lang==SrcLangExt_CSharp)
      {
        result+=a->type+" ";
      }
2216 2217 2218 2219 2220 2221 2222 2223 2224 2225
      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);
      }
2226 2227 2228 2229
      else // nothing found -> take whole name
      {
        result+=a->type;
      }
2230
    }
2231 2232
    ++ali;
    a=ali.current();
2233
    if (a) result+=", ";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2234
  }
2235
  result+=">";
2236
  return removeRedundantWhiteSpace(result);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2237 2238 2239 2240
}


// compute the HTML anchors for a list of members
2241
void setAnchors(MemberList *ml)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2242
{
2243
  //int count=0;
2244
  if (ml==0) return;
2245 2246 2247
  MemberListIterator mli(*ml);
  MemberDef *md;
  for (;(md=mli.current());++mli)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2248
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2249 2250
    if (!md->isReference())
    {
2251 2252 2253 2254 2255 2256 2257
      //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();
2258 2259
      //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
2260
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2261 2262 2263 2264 2265
  }
}

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

2266
/*! takes the \a buf of the given length \a len and converts CR LF (DOS)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2267 2268 2269 2270
 * 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).
 */
2271 2272
int filterCRLF(char *buf,int len)
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2273 2274 2275 2276 2277
  int src = 0;    // source index
  int dest = 0;   // destination index
  char c;         // current character

  while (src<len)
2278
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2279 2280
    c = buf[src++];            // Remember the processed character.
    if (c == '\r')             // CR to be solved (MAC, DOS)
2281
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2282 2283 2284
      c = '\n';                // each CR to LF
      if (src<len && buf[src] == '\n')
        ++src;                 // skip LF just after CR (DOS) 
2285
    }
2286 2287 2288 2289
    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
2290
    buf[dest++] = c;           // copy the (modified) character to dest
2291
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2292
  return dest;                 // length of the valid part of the buf
2293 2294
}

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

  // no match
  return "";
}

2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
/*! 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);
  }
2346
  if (!found && filterName.isEmpty())
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359
  { // 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;
  }
}

2360 2361 2362

QCString transcodeCharacterStringToUTF8(const QCString &input)
{
2363
  bool error=FALSE;
2364 2365 2366 2367 2368 2369 2370 2371 2372
  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)) 
  {
2373
    err("unsupported character conversion: '%s'->'%s'\n",
2374
        inputEncoding.data(),outputEncoding);
2375
    error=TRUE;
2376
  }
2377
  if (!error)
2378
  {
2379 2380
    size_t iLeft=inputSize;
    size_t oLeft=outputSize;
2381
    char *inputPtr = input.data();
2382 2383 2384
    char *outputPtr = output.data();
    if (!portable_iconv(cd, &inputPtr, &iLeft, &outputPtr, &oLeft))
    {
2385
      outputSize-=(int)oLeft;
2386 2387 2388 2389 2390 2391
      output.resize(outputSize+1);
      output.at(outputSize)='\0';
      //printf("iconv: input size=%d output size=%d\n[%s]\n",size,newSize,srcBuf.data());
    }
    else
    {
2392
      err("failed to translate characters from %s to %s: check INPUT_ENCODING\ninput=[%s]\n",
2393 2394 2395
          inputEncoding.data(),outputEncoding,input.data());
      error=TRUE;
    }
2396 2397
  }
  portable_iconv_close(cd);
2398
  return error ? input : output;
2399 2400
}

2401 2402 2403 2404
/*! 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. 
 */
2405
QCString fileToString(const char *name,bool filter,bool isSourceCode)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2406 2407
{
  if (name==0 || name[0]==0) return 0;
2408 2409 2410 2411
  QFile f;

  bool fileOpened=FALSE;
  if (name[0]=='-' && name[1]==0) // read from stdin
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2412
  {
2413
    fileOpened=f.open(IO_ReadOnly,stdin);
2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
    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); 
      }
2425
      totalSize = filterCRLF(contents.data(),totalSize+size)+2;
2426 2427 2428 2429 2430
      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
2431
  }
2432
  else // read from file
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2433
  {
2434 2435 2436
    QFileInfo fi(name);
    if (!fi.exists() || !fi.isFile())
    {
2437
      err("file `%s' not found\n",name);
2438
      return "";
2439
    }
2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451
    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();
    }
2452 2453 2454
  }
  if (!fileOpened)  
  {
2455
    err("cannot open file `%s' for reading\n",name);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2456
  }
2457
  return "";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2458 2459
}

2460
QCString dateToString(bool includeTime)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2461
{
2462 2463 2464 2465 2466 2467 2468 2469 2470
  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
2471 2472
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2473 2474 2475 2476 2477 2478 2479 2480
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
2481 2482 2483 2484
//----------------------------------------------------------------------
// recursive function that returns the number of branches in the 
// inheritance tree that the base class `bcd' is below the class `cd'

2485
int minClassDistance(const ClassDef *cd,const ClassDef *bcd,int level)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2486
{
2487
  if (bcd->categoryOf()) // use class that is being extended in case of 
2488
    // an Objective-C category
2489 2490 2491
  {
    bcd=bcd->categoryOf();
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2492
  if (cd==bcd) return level; 
2493 2494
  if (level==256)
  {
2495
    warn_uncond("class %s seem to have a recursive "
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2496
        "inheritance relation!\n",cd->name().data());
2497 2498
    return -1;
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2499
  int m=maxInheritanceDepth; 
2500
  if (cd->baseClasses())
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2501
  {
2502 2503 2504
    BaseClassListIterator bcli(*cd->baseClasses());
    BaseClassDef *bcdi;
    for (;(bcdi=bcli.current());++bcli)
2505 2506 2507 2508 2509
    {
      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
2510 2511 2512 2513
  }
  return m;
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
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)
  {
2527
    err("Internal inconsistency: found class %s seem to have a recursive "
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2528 2529 2530 2531
        "inheritance relation! Please send a bug report to dimitri@stack.nl\n",cd->name().data());
  }
  else if (cd->baseClasses())
  {
2532 2533 2534
    BaseClassListIterator bcli(*cd->baseClasses());
    BaseClassDef *bcdi;
    for (;(bcdi=bcli.current()) && prot!=Private;++bcli)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545
    {
      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
2546 2547 2548 2549 2550 2551 2552 2553
//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
2554
//    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
2555 2556 2557 2558
//  }
//  printf(")");
//}

2559
#ifndef NEWMATCH
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2560
// strip any template specifiers that follow className in string s
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2561
static QCString trimTemplateSpecifiers(
2562 2563 2564 2565
    const QCString &namespaceName,
    const QCString &className,
    const QCString &s
    )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2566
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2567 2568 2569 2570
  //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
2571

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2572 2573 2574
  QCString result=s;

  int i=className.length()-1;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2575
  if (i>=0 && className.at(i)=='>') // template specialization
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601
  {
    // 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());
2602

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2603 2604
  QCString qualName=cd->qualifiedNameWithTemplateParameters();
  //printf("QualifiedName = %s\n",qualName.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2605
  // We strip the template arguments following className (if any)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2606
  if (!qualName.isEmpty()) // there is a class name
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2607
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2608 2609 2610 2611
    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
2612
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2613 2614 2615 2616 2617 2618 2619 2620 2621
      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
2622 2623
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2624
  //printf("result=%s\n",result.data());
2625

2626
  return result.stripWhiteSpace();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2627 2628
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2629 2630 2631 2632 2633 2634 2635 2636
/*!
 * @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,
2637
    int p,int *len)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
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 2682 2683 2684 2685 2686 2687 2688 2689 2690
{
  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;
}
2691

2692
static QCString trimScope(const QCString &name,const QCString &s)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2693
{
2694 2695 2696
  int scopeOffset=name.length();
  QCString result=s;
  do // for each scope
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2697
  {
2698 2699 2700
    QCString tmp;
    QCString scope=name.left(scopeOffset)+"::";
    //printf("Trying with scope=`%s'\n",scope.data());
2701

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2702 2703
    int i,p=0,l;
    while ((i=findScopePattern(scope,result,p,&l))!=-1) // for each occurrence
2704 2705
    {
      tmp+=result.mid(p,i-p); // add part before pattern
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2706
      p=i+l;
2707 2708 2709 2710 2711 2712
    }
    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
2713
  //printf("trimScope(name=%s,scope=%s)=%s\n",name.data(),s.data(),result.data());
2714
  return result;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2715
}
2716
#endif
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2717

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

2740
#if 0
2741 2742 2743 2744
/*! 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
2745
static void trimNamespaceScope(QCString &t1,QCString &t2,const QCString &nsName)
2746 2747 2748 2749 2750
{
  int p1=t1.length();
  int p2=t2.length();
  for (;;)
  {
2751 2752
    int i1=p1==0 ? -1 : t1.findRev("::",p1);
    int i2=p2==0 ? -1 : t2.findRev("::",p2);
2753 2754 2755 2756 2757 2758 2759
    if (i1==-1 && i2==-1)
    {
      return;
    }
    if (i1!=-1 && i2==-1) // only t1 has a scope
    {
      QCString scope=t1.left(i1);
2760
      replaceNamespaceAliases(scope,i1);
2761

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

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

2817 2818 2819 2820 2821
static void stripIrrelevantString(QCString &target,const QCString &str)
{
  if (target==str) { target.resize(0); return; }
  int i,p=0;
  int l=str.length();
2822
  bool changed=FALSE;
2823 2824 2825
  while ((i=target.find(str,p))!=-1)
  {
    bool isMatch = (i==0 || !isId(target.at(i-1))) && // not a character before str
2826
      (i+l==(int)target.length() || !isId(target.at(i+l))); // not a character after str
2827 2828 2829 2830 2831 2832 2833 2834
    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); 
2835
        changed=TRUE;
2836 2837 2838 2839 2840 2841
        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);
2842
        changed=TRUE;
2843 2844 2845 2846 2847
        i++;
      }
    }
    p = i+l;
  }
2848
  if (changed) target=target.stripWhiteSpace();
2849 2850
}

2851 2852
/*! According to the C++ spec and Ivan Vecerina:

2853 2854
  Parameter declarations  that differ only in the presence or absence
  of const and/or volatile are equivalent.
2855

2856 2857
  So the following example, show what is stripped by this routine
  for const. The same is done for volatile.
2858

2859 2860 2861 2862 2863 2864
  \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
2865 2866 2867
 */
void stripIrrelevantConstVolatile(QCString &s)
{
2868
  //printf("stripIrrelevantConstVolatile(%s)=",s.data());
2869 2870
  stripIrrelevantString(s,"const");
  stripIrrelevantString(s,"volatile");
2871
  //printf("%s\n",s.data());
2872 2873
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2874

2875 2876 2877 2878 2879 2880
// 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__);

2881
#ifndef NEWMATCH
2882
static bool matchArgument(const Argument *srcA,const Argument *dstA,
2883 2884 2885 2886
    const QCString &className,
    const QCString &namespaceName,
    NamespaceSDict *usingNamespaces,
    SDict<Definition> *usingClasses)
2887
{
2888
  //printf("match argument start `%s|%s' <-> `%s|%s' using nsp=%p class=%p\n",
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2889
  //    srcA->type.data(),srcA->name.data(),
2890 2891 2892
  //    dstA->type.data(),dstA->name.data(),
  //    usingNamespaces,
  //    usingClasses);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2893 2894 2895 2896 2897

  // 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
2898 2899 2900

  QCString srcAType=trimTemplateSpecifiers(namespaceName,className,srcA->type);
  QCString dstAType=trimTemplateSpecifiers(namespaceName,className,dstA->type);
2901 2902
  QCString srcAName=srcA->name.stripWhiteSpace();
  QCString dstAName=dstA->name.stripWhiteSpace();
2903 2904
  srcAType.stripPrefix("class ");
  dstAType.stripPrefix("class ");
2905

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

2931 2932 2933
  stripIrrelevantConstVolatile(srcAType);
  stripIrrelevantConstVolatile(dstAType);

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2934
  // strip typename keyword
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2935
  if (qstrncmp(srcAType,"typename ",9)==0)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2936 2937 2938
  {
    srcAType = srcAType.right(srcAType.length()-9); 
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2939
  if (qstrncmp(dstAType,"typename ",9)==0)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2940 2941 2942
  {
    dstAType = dstAType.right(dstAType.length()-9); 
  }
2943

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2944 2945 2946
  srcAType = removeRedundantWhiteSpace(srcAType);
  dstAType = removeRedundantWhiteSpace(dstAType);

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2947 2948 2949
  //srcAType=stripTemplateSpecifiersFromScope(srcAType,FALSE);
  //dstAType=stripTemplateSpecifiersFromScope(dstAType,FALSE);

2950 2951
  //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
2952

2953 2954 2955
  if (srcA->array!=dstA->array) // nomatch for char[] against char
  {
    NOMATCH
2956
      return FALSE;
2957 2958 2959 2960 2961 2962
  }
  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)
2963 2964 2965
    //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());
2966

2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980
    //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);
2981
      if (cd && cd->baseClasses())
2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992
      {
        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);
    }
2993
    //printf("#usingNamespace=%d\n",usingNamespaces->count());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2994
    if (usingNamespaces && usingNamespaces->count()>0)
2995
    {
2996
      NamespaceSDict::Iterator nli(*usingNamespaces);
2997 2998 2999 3000 3001 3002 3003
      NamespaceDef *nd;
      for (;(nd=nli.current());++nli)
      {
        srcAType=trimScope(nd->name(),srcAType);
        dstAType=trimScope(nd->name(),dstAType);
      }
    }
3004
    //printf("#usingClasses=%d\n",usingClasses->count());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3005 3006
    if (usingClasses && usingClasses->count()>0)
    {
3007 3008
      SDict<Definition>::Iterator cli(*usingClasses);
      Definition *cd;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3009 3010 3011 3012 3013 3014
      for (;(cd=cli.current());++cli)
      {
        srcAType=trimScope(cd->name(),srcAType);
        dstAType=trimScope(cd->name(),dstAType);
      }
    }
3015

3016 3017
    //printf("2. srcA=%s|%s dstA=%s|%s\n",srcAType.data(),srcAName.data(),
    //    dstAType.data(),dstAName.data());
3018

3019 3020
    if (!srcAName.isEmpty() && !dstA->type.isEmpty() &&
        (srcAType+" "+srcAName)==dstAType)
3021 3022
    {
      MATCH
3023
      return TRUE;
3024
    }
3025 3026
    else if (!dstAName.isEmpty() && !srcA->type.isEmpty() &&
        (dstAType+" "+dstAName)==srcAType)
3027 3028
    {
      MATCH
3029
      return TRUE;
3030
    }
3031

3032 3033 3034 3035 3036 3037 3038 3039

    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++; 
    }
3040 3041 3042
    uint srcATypeLen=srcAType.length();
    uint dstATypeLen=dstAType.length();
    if (srcPos<srcATypeLen && dstPos<dstATypeLen)
3043 3044 3045 3046 3047 3048
    {
      // 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
3049
        return FALSE;
3050 3051 3052
      }
      if (isId(srcAType.at(srcPos)) && isId(dstAType.at(dstPos)))
      {
3053
        //printf("partial match srcPos=%d dstPos=%d!\n",srcPos,dstPos);
3054
        // check if a name if already found -> if no then there is no match
3055
        if (!srcAName.isEmpty() || !dstAName.isEmpty()) 
3056 3057
        {
          NOMATCH
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3058
          return FALSE;
3059
        }
3060 3061 3062 3063 3064 3065 3066
        // 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)
           ) 
3067 3068
        {
          NOMATCH
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3069
          return FALSE;
3070 3071 3072 3073 3074
        }
      }
      else
      {
        // otherwise we assume that a name starts at the current position.
3075 3076
        while (srcPos<srcATypeLen && isId(srcAType.at(srcPos))) srcPos++;
        while (dstPos<dstATypeLen && isId(dstAType.at(dstPos))) dstPos++;
3077

3078 3079 3080 3081 3082
        // 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.

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


/*!
 * 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
3157
bool matchArguments(ArgumentList *srcAl,ArgumentList *dstAl,
3158 3159 3160
    const char *cl,const char *ns,bool checkCV,
    NamespaceSDict *usingNamespaces,
    SDict<Definition> *usingClasses)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3161
{
3162 3163 3164
  QCString className=cl;
  QCString namespaceName=ns;

3165
  // strip template specialization from class name if present
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3166 3167 3168 3169 3170
  //int til=className.find('<'),tir=className.find('>');
  //if (til!=-1 && tir!=-1 && tir>til) 
  //{
  //  className=className.left(til)+className.right(className.length()-tir-1);
  //}
3171

Dimitri van Heesch's avatar
Dimitri van Heesch committed
3172
  //printf("matchArguments(%s,%s) className=%s namespaceName=%s checkCV=%d usingNamespaces=%d usingClasses=%d\n",
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3173 3174
  //    srcAl ? argListToString(srcAl).data() : "",
  //    dstAl ? argListToString(dstAl).data() : "",
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3175 3176 3177 3178
  //    cl,ns,checkCV,
  //    usingNamespaces?usingNamespaces->count():0,
  //    usingClasses?usingClasses->count():0
  //    );
3179

Dimitri van Heesch's avatar
Dimitri van Heesch committed
3180 3181
  if (srcAl==0 || dstAl==0)
  {
3182 3183 3184 3185
    bool match = srcAl==dstAl; // at least one of the members is not a function
    if (match)
    {
      MATCH
3186
      return TRUE;
3187 3188 3189 3190
    }
    else
    {
      NOMATCH
3191
      return FALSE;
3192
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3193
  }
3194

3195
  // handle special case with void argument
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3196
  if ( srcAl->count()==0 && dstAl->count()==1 && 
3197
      dstAl->getFirst()->type=="void" )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3198 3199 3200 3201
  { // special case for finding match between func() and func(void)
    Argument *a=new Argument;
    a->type = "void";
    srcAl->append(a);
3202
    MATCH
3203
    return TRUE;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3204 3205
  }
  if ( dstAl->count()==0 && srcAl->count()==1 &&
3206
      srcAl->getFirst()->type=="void" )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3207 3208 3209 3210
  { // special case for finding match between func(void) and func()
    Argument *a=new Argument;
    a->type = "void";
    dstAl->append(a);
3211
    MATCH
3212
    return TRUE;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3213
  }
3214

Dimitri van Heesch's avatar
Dimitri van Heesch committed
3215 3216
  if (srcAl->count() != dstAl->count())
  {
3217
    NOMATCH
3218
    return FALSE; // different number of arguments -> no match
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3219
  }
3220 3221

  if (checkCV)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3222
  {
3223 3224
    if (srcAl->constSpecifier != dstAl->constSpecifier) 
    {
3225
      NOMATCH
3226
      return FALSE; // one member is const, the other not -> no match
3227 3228 3229
    }
    if (srcAl->volatileSpecifier != dstAl->volatileSpecifier)
    {
3230
      NOMATCH
3231
      return FALSE; // one member is volatile, the other not -> no match
3232
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3233 3234 3235 3236 3237 3238 3239
  }

  // 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)
3240
  { 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3241 3242
    if (!matchArgument(srcA,dstA,className,namespaceName,
          usingNamespaces,usingClasses))
3243
    {
3244
      NOMATCH
3245
      return FALSE;
3246
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3247
  }
3248
  MATCH
3249
  return TRUE; // all arguments match 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3250 3251
}

3252 3253
#endif

Dimitri van Heesch's avatar
Dimitri van Heesch committed
3254
#if 0
3255 3256 3257 3258 3259
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
3260
    // to resolve it
3261 3262 3263 3264 3265
  {
    MemberDef *md = 0;
    ClassDef *cd = newResolveTypedef(fs,(MemberDef*)symbol,&md,&templSpec);
    if (cd)
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3266
      return cd->qualifiedName()+templSpec;
3267 3268 3269 3270 3271 3272 3273 3274
    }
    else if (md)
    {
      return md->qualifiedName();
    }
  }
  return symbol->qualifiedName();
}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288
#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;
}
3289

3290 3291 3292
// forward decl for circular dependencies
static QCString extractCanonicalType(Definition *d,FileDef *fs,QCString type);

3293
QCString getCanonicalTemplateSpec(Definition *d,FileDef *fs,const QCString& spec)
3294
{
3295
  
3296
  QCString templSpec = spec.stripWhiteSpace();
3297 3298 3299 3300 3301 3302 3303
  // 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);
3304 3305 3306 3307 3308 3309
  if (!resolvedType.isEmpty()) // not known as a typedef either
  {
    templSpec = resolvedType;
  }
  //printf("getCanonicalTemplateSpec(%s)=%s\n",spec.data(),templSpec.data());
  return templSpec;
3310 3311 3312
}


3313
static QCString getCanonicalTypeForIdentifier(
3314
    Definition *d,FileDef *fs,const QCString &word,
3315
    QCString *tSpec,int count=0)
3316
{
3317 3318
  if (count>10) return word; // oops recursion

3319
  QCString symName,scope,result,templSpec,tmpName;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3320
  //DefinitionList *defList=0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3321 3322
  if (tSpec && !tSpec->isEmpty()) 
    templSpec = stripDeclKeywords(getCanonicalTemplateSpec(d,fs,*tSpec));
3323

3324
  if (word.findRev("::")!=-1 && !(tmpName=stripScope(word)).isEmpty())
3325
  {
3326
    symName=tmpName; // name without scope
3327 3328 3329 3330 3331
  }
  else
  {
    symName=word;
  }
3332 3333
  //printf("getCanonicalTypeForIdentifier(%s,[%s->%s]) start\n",
  //    word.data(),tSpec?tSpec->data():"<none>",templSpec.data());
3334

3335 3336 3337
  ClassDef *cd = 0;
  MemberDef *mType = 0;
  QCString ts;
3338
  QCString resolvedType;
3339 3340

  // lookup class / class template instance
3341
  cd = getResolvedClass(d,fs,word+templSpec,&mType,&ts,TRUE,TRUE,&resolvedType);
3342 3343
  bool isTemplInst = cd && !templSpec.isEmpty();
  if (!cd && !templSpec.isEmpty())
3344
  {
3345
    // class template specialization not known, look up class template
3346
    cd = getResolvedClass(d,fs,word,&mType,&ts,TRUE,TRUE,&resolvedType);
3347
  }
3348
  if (cd && cd->isUsedOnly()) cd=0; // ignore types introduced by usage relations
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3349

3350
  //printf("cd=%p mtype=%p\n",cd,mType);
3351
  //printf("  getCanonicalTypeForIdentifer: symbol=%s word=%s cd=%s d=%s fs=%s cd->isTemplate=%d\n",
3352 3353 3354 3355
  //    symName.data(),
  //    word.data(),
  //    cd?cd->name().data():"<none>",
  //    d?d->name().data():"<none>",
3356 3357
  //    fs?fs->name().data():"<none>",
  //    cd?cd->isTemplate():-1
3358
  //   );
3359

3360
  //printf("  >>>> word '%s' => '%s' templSpec=%s ts=%s tSpec=%s isTemplate=%d resolvedType=%s\n",
3361
  //    (word+templSpec).data(),
3362
  //    cd?cd->qualifiedName().data():"<none>",
3363 3364
  //    templSpec.data(),ts.data(),
  //    tSpec?tSpec->data():"<null>",
3365 3366 3367 3368
  //    cd?cd->isTemplate():FALSE,
  //    resolvedType.data());

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

3370
  if (cd) // resolves to a known class type
3371
  {
3372 3373
    if (cd==d && tSpec) *tSpec="";

3374
    if (mType && mType->isTypedef()) // but via a typedef
3375
    {
3376
      result = resolvedType+ts; // the +ts was added for bug 685125
3377
    }
3378
    else
3379
    {
3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390
      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));
      }
3391

3392
      result = removeRedundantWhiteSpace(cd->qualifiedName() + templSpec);
3393

3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412
      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="";
      }
3413
    }
3414 3415 3416 3417 3418
  }
  else if (mType && mType->isEnumerate()) // an enum
  {
    result = mType->qualifiedName();
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3419 3420
  else if (mType && mType->isTypedef()) // a typedef
  {
3421
    //result = mType->qualifiedName(); // changed after 1.7.2
3422
    //result = mType->typeString();
3423
    //printf("word=%s typeString=%s\n",word.data(),mType->typeString());
3424 3425
    if (word!=mType->typeString())
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3426
      result = getCanonicalTypeForIdentifier(d,fs,mType->typeString(),tSpec,count+1);
3427 3428 3429 3430 3431
    }
    else
    {
      result = mType->typeString();
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3432
  }
3433
  else // fallback
3434
  {
3435
    resolvedType = resolveTypeDef(d,word);
3436
    //printf("typedef [%s]->[%s]\n",word.data(),resolvedType.data());
3437
    if (resolvedType.isEmpty()) // not known as a typedef either
3438
    {
3439
      result = word;
3440
    }
3441
    else
3442
    {
3443
      result = resolvedType;
3444 3445
    }
  }
3446
  //printf("getCanonicalTypeForIdentifier [%s]->[%s]\n",word.data(),result.data());
3447 3448
  return result;
}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3449

3450
static QCString extractCanonicalType(Definition *d,FileDef *fs,QCString type)
3451
{
3452
  type = type.stripWhiteSpace();
3453

3454
  // strip const and volatile keywords that are not relevant for the type
3455
  stripIrrelevantConstVolatile(type);
3456

3457
  // strip leading keywords
3458 3459 3460 3461 3462
  type.stripPrefix("class ");
  type.stripPrefix("struct ");
  type.stripPrefix("union ");
  type.stripPrefix("enum ");
  type.stripPrefix("typename ");
3463

3464
  type = removeRedundantWhiteSpace(type);
3465
  //printf("extractCanonicalType(type=%s) start: def=%s file=%s\n",type.data(),
3466
  //    d ? d->name().data() : "<null>",fs ? fs->name().data() : "<null>");
3467

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

3470 3471
  QCString canType;
  QCString templSpec,word;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3472 3473
  int i,p=0,pp=0;
  while ((i=extractClassNameFromType(type,p,word,templSpec))!=-1)
3474
    // foreach identifier in the type
3475
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3476
    //printf("     i=%d p=%d\n",i,p);
3477
    if (i>pp) canType += type.mid(pp,i-pp);
3478

3479

3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492
    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;
    }
3493 3494
    //printf(" word=%s templSpec=%s canType=%s ct=%s\n",
    //    word.data(),templSpec.data(),canType.data(),ct.data());
3495
    if (!templSpec.isEmpty()) // if we didn't use up the templSpec already
3496 3497
                              // (i.e. type is not a template specialization)
                              // then resolve any identifiers inside. 
3498
    {
3499
      static QRegExp re("[a-z_A-Z\\x80-\\xFF][a-z_A-Z0-9\\x80-\\xFF]*");
3500
      int tp=0,tl,ti;
3501
      // for each identifier template specifier
3502
      //printf("adding resolved %s to %s\n",templSpec.data(),canType.data());
3503
      while ((ti=re.match(templSpec,tp,&tl))!=-1)
3504
      {
3505 3506 3507
        canType += templSpec.mid(tp,ti-tp);
        canType += getCanonicalTypeForIdentifier(d,fs,templSpec.mid(ti,tl),0);
        tp=ti+tl;
3508
      }
3509
      canType+=templSpec.right(templSpec.length()-tp);
3510
    }
3511

Dimitri van Heesch's avatar
Dimitri van Heesch committed
3512
    pp=p;
3513
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3514
  canType += type.right(type.length()-pp);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3515
  //printf("extractCanonicalType = '%s'->'%s'\n",type.data(),canType.data());
3516

3517 3518 3519
  return removeRedundantWhiteSpace(canType);
}

3520 3521 3522 3523
static QCString extractCanonicalArgType(Definition *d,FileDef *fs,const Argument *arg)
{
  QCString type = arg->type.stripWhiteSpace();
  QCString name = arg->name;
3524
  //printf("----- extractCanonicalArgType(type=%s,name=%s)\n",type.data(),name.data());
3525 3526 3527 3528 3529 3530 3531 3532 3533 3534
  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
3535 3536 3537 3538
  if (!arg->array.isEmpty())
  {
    type+=arg->array;
  }
3539 3540 3541 3542

  return extractCanonicalType(d,fs,type);
}

3543
static bool matchArgument2(
3544 3545 3546
    Definition *srcScope,FileDef *srcFileScope,Argument *srcA,
    Definition *dstScope,FileDef *dstFileScope,Argument *dstA
    )
3547
{
3548 3549 3550 3551 3552
  //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());
3553

Dimitri van Heesch's avatar
Dimitri van Heesch committed
3554 3555 3556 3557 3558
  //if (srcA->array!=dstA->array) // nomatch for char[] against char
  //{
  //  NOMATCH
  //  return FALSE;
  //}
3559 3560 3561 3562 3563 3564 3565 3566 3567
  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()))
3568 3569 3570
  { // case "unsigned int" <-> "unsigned int i"
    srcA->type+=sSrcName;
    srcA->name="";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3571
    srcA->canType=""; // invalidate cached type value
3572
  }
3573
  else if (sDstName==srcType.right(sDstName.length()))
3574 3575 3576
  { // case "unsigned int i" <-> "unsigned int"
    dstA->type+=sDstName;
    dstA->name="";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3577
    dstA->canType=""; // invalidate cached type value
3578
  }
3579

3580 3581
  if (srcA->canType.isEmpty())
  {
3582
    srcA->canType = extractCanonicalArgType(srcScope,srcFileScope,srcA);
3583 3584 3585
  }
  if (dstA->canType.isEmpty())
  {
3586
    dstA->canType = extractCanonicalArgType(dstScope,dstFileScope,dstA);
3587
  }
3588

3589
  if (srcA->canType==dstA->canType)
3590 3591
  {
    MATCH
3592
    return TRUE;
3593 3594 3595
  }
  else
  {
3596 3597
    //printf("   Canonical types do not match [%s]<->[%s]\n",
    //    srcA->canType.data(),dstA->canType.data());
3598
    NOMATCH
3599
    return FALSE;
3600 3601 3602 3603 3604 3605
  }
}


// new algorithm for argument matching
bool matchArguments2(Definition *srcScope,FileDef *srcFileScope,ArgumentList *srcAl,
3606 3607 3608
    Definition *dstScope,FileDef *dstFileScope,ArgumentList *dstAl,
    bool checkCV
    )
3609
{
3610
  //printf("*** matchArguments2\n");
3611 3612 3613 3614 3615 3616 3617 3618
  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
3619
      return TRUE;
3620 3621 3622 3623
    }
    else
    {
      NOMATCH
3624
      return FALSE;
3625 3626
    }
  }
3627

3628 3629
  // handle special case with void argument
  if ( srcAl->count()==0 && dstAl->count()==1 && 
3630
      dstAl->getFirst()->type=="void" )
3631 3632 3633 3634 3635
  { // special case for finding match between func() and func(void)
    Argument *a=new Argument;
    a->type = "void";
    srcAl->append(a);
    MATCH
3636
    return TRUE;
3637 3638
  }
  if ( dstAl->count()==0 && srcAl->count()==1 &&
3639
      srcAl->getFirst()->type=="void" )
3640 3641 3642 3643 3644
  { // special case for finding match between func(void) and func()
    Argument *a=new Argument;
    a->type = "void";
    dstAl->append(a);
    MATCH
3645
    return TRUE;
3646
  }
3647

3648 3649 3650
  if (srcAl->count() != dstAl->count())
  {
    NOMATCH
3651
    return FALSE; // different number of arguments -> no match
3652 3653 3654 3655 3656 3657 3658
  }

  if (checkCV)
  {
    if (srcAl->constSpecifier != dstAl->constSpecifier) 
    {
      NOMATCH
3659
      return FALSE; // one member is const, the other not -> no match
3660 3661 3662 3663
    }
    if (srcAl->volatileSpecifier != dstAl->volatileSpecifier)
    {
      NOMATCH
3664
      return FALSE; // one member is volatile, the other not -> no match
3665 3666 3667 3668 3669 3670 3671 3672 3673 3674
    }
  }

  // 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,
3675
          dstScope,dstFileScope,dstA)
3676 3677 3678
       )
    {
      NOMATCH
3679
      return FALSE;
3680 3681 3682
    }
  }
  MATCH
3683
  return TRUE; // all arguments match 
3684 3685 3686 3687
}



Dimitri van Heesch's avatar
Dimitri van Heesch committed
3688 3689
// 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
3690
void mergeArguments(ArgumentList *srcAl,ArgumentList *dstAl,bool forceNameOverwrite)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3691 3692 3693
{
  //printf("mergeArguments `%s', `%s'\n",
  //    argListToString(srcAl).data(),argListToString(dstAl).data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3694

Dimitri van Heesch's avatar
Dimitri van Heesch committed
3695 3696 3697 3698 3699 3700 3701 3702 3703
  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
3704
    if (srcA->defval.isEmpty() && !dstA->defval.isEmpty())
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3705 3706 3707 3708
    {
      //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
3709
    else if (!srcA->defval.isEmpty() && dstA->defval.isEmpty())
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3710 3711 3712 3713
    {
      //printf("Defval changing `%s'->`%s'\n",dstA->defval.data(),srcA->defval.data());
      dstA->defval=srcA->defval.copy();
    }
3714

3715
    // fix wrongly detected const or volatile specifiers before merging.
3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727
    // 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
3728
    if (srcA->type==dstA->type)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3729
    {
3730
      //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
3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746
      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())
      {
3747
        //printf("srcA->name=%s dstA->name=%s\n",srcA->name.data(),dstA->name.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3748
        if (forceNameOverwrite)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3749
        {
3750
          srcA->name = dstA->name;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3751
        }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3752
        else
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3753
        {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3754 3755
          if (srcA->docs.isEmpty() && !dstA->docs.isEmpty())
          {
3756
            srcA->name = dstA->name;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3757 3758 3759
          }
          else if (!srcA->docs.isEmpty() && dstA->docs.isEmpty())
          {
3760
            dstA->name = srcA->name;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3761
          }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3762
        }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3763
      }
3764
    }
3765 3766
    else
    {
3767 3768 3769
      //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();
3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788
      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
3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806
    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();
    }
3807 3808 3809 3810 3811 3812 3813 3814
    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();
    }
3815
    //printf("Merge argument `%s|%s' `%s|%s'\n",
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3816 3817
    //  srcA->type.data(),srcA->name.data(),
    //  dstA->type.data(),dstA->name.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3818 3819 3820
  }
}

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

3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889
/*!
 * 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
3890
bool getDefs(const QCString &scName,
3891
             const QCString &mbName, 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902
             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
3903
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3904
  fd=0, md=0, cd=0, nd=0, gd=0;
3905
  if (mbName.isEmpty()) return FALSE; /* empty name => nothing to link */
3906

3907
  QCString scopeName=scName;
3908
  QCString memberName=mbName;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3909
  scopeName = substitute(scopeName,"\\","::"); // for PHP
3910
  memberName = substitute(memberName,"\\","::"); // for PHP
3911 3912
  //printf("Search for name=%s args=%s in scope=%s forceEmpty=%d\n",
  //          memberName.data(),args,scopeName.data(),forceEmptyScope);
3913

3914
  int is,im=0,pm=0;
3915 3916
  // strip common part of the scope from the scopeName
  while ((is=scopeName.findRev("::"))!=-1 && 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3917 3918 3919
         (im=memberName.find("::",pm))!=-1 &&
          (scopeName.right(scopeName.length()-is-2)==memberName.mid(pm,im-pm))
        )
3920 3921 3922 3923 3924 3925
  {
    scopeName=scopeName.left(is); 
    pm=im+2;
  }
  //printf("result after scope corrections scope=%s name=%s\n",
  //          scopeName.data(),memberName.data());
3926

3927 3928
  QCString mName=memberName;
  QCString mScope;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3929
  if (memberName.left(9)!="operator " && // treat operator conversion methods
3930
      // as a special case
3931 3932
      (im=memberName.findRev("::"))!=-1 && 
      im<(int)memberName.length()-2 // not A::
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3933
     )
3934 3935 3936 3937
  {
    mScope=memberName.left(im); 
    mName=memberName.right(memberName.length()-im-2);
  }
3938

3939 3940 3941 3942
  // 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());
3943

3944
  MemberName *mn = Doxygen::memberNameSDict->find(mName);
3945
  //printf("mName=%s mn=%p\n",mName.data(),mn);
3946 3947 3948

  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
3949
  {
3950
    //printf("  >member name '%s' found\n",mName.data());
3951 3952 3953 3954 3955
    int scopeOffset=scopeName.length();
    do
    {
      QCString className = scopeName.left(scopeOffset);
      if (!className.isEmpty() && !mScope.isEmpty())
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3956
      {
3957
        className+="::"+mScope;
3958 3959 3960
      }
      else if (!mScope.isEmpty())
      {
3961
        className=mScope;
3962 3963
      }

3964 3965 3966
      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);
3967
      // todo: fill in correct fileScope!
3968
      if (fcd &&  // is it a documented class
3969
          fcd->isLinkable() 
3970 3971 3972
         )
      {
        //printf("  Found fcd=%p\n",fcd);
3973 3974
        MemberListIterator mmli(*mn);
        MemberDef *mmd;
3975
        int mdist=maxInheritanceDepth; 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3976 3977 3978 3979 3980 3981
        ArgumentList *argList=0;
        if (args)
        {
          argList=new ArgumentList;
          stringToArgumentList(args,argList);
        }
3982
        for (mmli.toFirst();(mmd=mmli.current());++mmli)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3983
        {
3984
          if (!mmd->isStrongEnumValue())
3985
          {
3986 3987 3988 3989 3990 3991 3992 3993
            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)
3994
            {
3995 3996
              ClassDef *mcd=mmd->getClassDef();
              if (mcd)
3997
              {
3998 3999 4000 4001 4002 4003 4004
                int m=minClassDistance(fcd,mcd);
                if (m<mdist && mcd->isLinkable())
                {
                  mdist=m;
                  cd=mcd;
                  md=mmd;
                }
4005
              }
4006
            }
4007
          }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4008
        }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4009 4010 4011 4012
        if (argList)
        {
          delete argList; argList=0;
        }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4013
        if (mdist==maxInheritanceDepth && args && qstrcmp(args,"()")==0)
4014
          // no exact match found, but if args="()" an arbitrary member will do
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4015
        {
4016
          //printf("  >Searching for arbitrary member\n");
4017
          for (mmli.toFirst();(mmd=mmli.current());++mmli)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4018
          {
4019 4020
            //if (mmd->isLinkable())
            //{
4021 4022
            ClassDef *mcd=mmd->getClassDef();
            //printf("  >Class %s found\n",mcd->name().data());
4023
            if (mcd)
4024
            {
4025 4026 4027 4028 4029 4030 4031 4032
              int m=minClassDistance(fcd,mcd);
              if (m<mdist /* && mcd->isLinkable()*/ )
              {
                //printf("Class distance %d\n",m);
                mdist=m;
                cd=mcd;
                md=mmd;
              }
4033
            }
4034
            //}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4035 4036
          }
        }
4037
        //printf("  >Succes=%d\n",mdist<maxInheritanceDepth);
4038 4039
        if (mdist<maxInheritanceDepth) 
        {
4040
          if (!md->isLinkable() || md->isStrongEnumValue()) 
4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051
          {
            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 */
          }
4052
        }
4053
      } 
4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069
      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;
4070
                return TRUE;
4071 4072 4073 4074 4075
              }
              else
              {
                cd=0;
                md=0;
4076
                return FALSE;
4077 4078 4079 4080 4081
              }
            }
          }
        }
      }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4082
      /* go to the parent scope */
4083 4084 4085
      if (scopeOffset==0)
      {
        scopeOffset=-1;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4086
      }
4087 4088 4089 4090 4091
      else if ((scopeOffset=scopeName.findRev("::",scopeOffset-1))==-1)
      {
        scopeOffset=0;
      }
    } while (scopeOffset>=0);
4092

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4093
  }
4094 4095
  if (mn && scopeName.isEmpty() && mScope.isEmpty()) // Maybe a related function?
  {
4096
    //printf("Global symbol\n");
4097 4098 4099
    MemberListIterator mmli(*mn);
    MemberDef *mmd, *fuzzy_mmd = 0;
    ArgumentList *argList = 0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4100
    bool hasEmptyArgs = args && qstrcmp(args, "()") == 0;
4101 4102 4103 4104 4105 4106

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

    for (mmli.toFirst(); (mmd = mmli.current()); ++mmli)
    {
4107 4108
      if (!mmd->isLinkable() || (!mmd->isRelated() && !mmd->isForeign()) ||
           !mmd->getClassDef())
4109 4110 4111 4112 4113 4114
        continue;

      if (!args) break;

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

4115 4116
      ArgumentList *mmdAl = mmd->argumentList();
      if (matchArguments2(mmd->getOuterScope(),mmd->getFileDef(),mmdAl,
4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129
            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;

4130
    if (mmd && !mmd->isStrongEnumValue())
4131 4132 4133 4134 4135 4136 4137
    {
      md = mmd;
      cd = mmd->getClassDef();
      return TRUE;
    }
  }

4138 4139

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

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

4356
  // no nothing found
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4357 4358 4359
  return FALSE;
}

4360 4361
/*!
 * Searches for a scope definition given its name as a string via parameter
4362
 * `scope`. 
4363
 *
4364 4365
 * The parameter `docScope` is a string representing the name of the scope in 
 * which the `scope` string was found.
4366 4367 4368
 *
 * The function returns TRUE if the scope is known and documented or
 * FALSE if it is not.
4369
 * If TRUE is returned exactly one of the parameter `cd`, `nd` 
4370
 * will be non-zero:
4371 4372
 *   - 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.
4373
 */
4374
static bool getScopeDefs(const char *docScope,const char *scope,
4375
    ClassDef *&cd, NamespaceDef *&nd)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4376
{
4377 4378 4379 4380
  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
4381
  if (scopeName.isEmpty()) return FALSE;
4382

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4383 4384 4385 4386 4387 4388
  bool explicitGlobalScope=FALSE;
  if (scopeName.at(0)==':' && scopeName.at(1)==':')
  {
    scopeName=scopeName.right(scopeName.length()-2);  
    explicitGlobalScope=TRUE;
  }
4389

4390
  QCString docScopeName=docScope;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4391
  int scopeOffset=explicitGlobalScope ? 0 : docScopeName.length();
4392 4393

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

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4398
    if (((cd=getClass(fullName)) ||         // normal class
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4399 4400
         (cd=getClass(fullName+"-p")) //||    // ObjC protocol
         //(cd=getClass(fullName+"-g"))       // C# generic
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4401
        ) && cd->isLinkable())
4402 4403 4404
    {
      return TRUE; // class link written => quit 
    }
4405
    else if ((nd=Doxygen::namespaceSDict->find(fullName)) && nd->isLinkable())
4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417
    {
      return TRUE; // namespace link written => quit 
    }
    if (scopeOffset==0)
    {
      scopeOffset=-1;
    }
    else if ((scopeOffset=docScopeName.findRev("::",scopeOffset-1))==-1)
    {
      scopeOffset=0;
    }
  } while (scopeOffset>=0);
4418

4419
  return FALSE;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4420 4421
}

4422 4423
static bool isLowerCase(QCString &s)
{
4424
  uchar *p=(uchar*)s.data();
4425 4426 4427 4428 4429
  if (p==0) return TRUE;
  int c;
  while ((c=*p++)) if (!islower(c)) return FALSE;
  return TRUE; 
}
4430 4431 4432 4433 4434

/*! 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,
4435 4436 4437
    /* in */  const char *name,
    /* in */  bool inSeeBlock,
    /* out */ Definition **resContext,
4438
    /* out */ MemberDef  **resMember,
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4439
    bool lookForSpecialization,
4440 4441
    FileDef *currentFile,
    bool checkScope
4442
    )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4443
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4444
  //printf("resolveRef(scope=%s,name=%s,inSeeBlock=%d)\n",scName,name,inSeeBlock);
4445
  QCString tsName = name;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4446
  //bool memberScopeFirst = tsName.find('#')!=-1;
4447
  QCString fullName = substitute(tsName,"#","::");
4448
  if (fullName.find("anonymous_namespace{")==-1)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4449 4450 4451 4452 4453 4454 4455
  {
    fullName = removeRedundantWhiteSpace(substitute(fullName,".","::"));
  }
  else
  {
    fullName = removeRedundantWhiteSpace(fullName);
  }
4456

4457
  int bracePos=findParameterList(fullName);
4458 4459
  int endNamePos=bracePos!=-1 ? bracePos : fullName.length();
  int scopePos=fullName.findRev("::",endNamePos);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4460 4461 4462 4463 4464
  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
                       );
4465 4466 4467 4468 4469

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

4470
  if (bracePos==-1) // simple name
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4471
  {
4472 4473
    ClassDef *cd=0;
    NamespaceDef *nd=0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4474

4475 4476 4477 4478 4479 4480
    // 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
4481

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

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

4509
  // extract userscope+name
4510
  QCString nameStr=fullName.left(endNamePos);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4511
  if (explicitScope) nameStr=nameStr.mid(2);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4512 4513

  // extract arguments
4514
  QCString argsStr;
4515
  if (bracePos!=-1) argsStr=fullName.right(fullName.length()-bracePos);
4516

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4517 4518 4519
  // strip template specifier
  // TODO: match against the correct partial template instantiation 
  int templPos=nameStr.find('<');
4520
  bool tryUnspecializedVersion = FALSE;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4521 4522 4523
  if (templPos!=-1 && nameStr.find("operator")==-1)
  {
    int endTemplPos=nameStr.findRev('>');
4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534
    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
4535
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4536

4537 4538
  QCString scopeStr=scName;

4539 4540 4541
  MemberDef    *md = 0;
  ClassDef     *cd = 0;
  FileDef      *fd = 0;
4542
  NamespaceDef *nd = 0;
4543
  GroupDef     *gd = 0;
4544 4545

  // check if nameStr is a member or global.
4546 4547
  //printf("getDefs(scope=%s,name=%s,args=%s checkScope=%d)\n",
  //    scopeStr.data(),nameStr.data(),argsStr.data(),checkScope);
4548
  if (getDefs(scopeStr,nameStr,argsStr,
4549
        md,cd,fd,nd,gd,
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4550 4551
        //scopePos==0 && !memberScopeFirst, // forceEmptyScope
        explicitScope, // replaces prev line due to bug 600829
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4552
        currentFile,
4553
        TRUE                              // checkCV
4554
        )
4555
     )
4556
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4557 4558
    //printf("after getDefs checkScope=%d nameStr=%s cd=%p nd=%p\n",checkScope,nameStr.data(),cd,nd);
    if (checkScope && md && md->getOuterScope()==Doxygen::globalScope && 
4559
        !md->isStrongEnumValue() &&
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4560
        (!scopeStr.isEmpty() || nameStr.find("::")>0))
4561 4562 4563 4564
    {
      // 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
4565
      //printf("not global member!\n");
4566 4567 4568 4569
      *resContext=0;
      *resMember=0;
      return FALSE;
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4570
    //printf("after getDefs md=%p cd=%p fd=%p nd=%p gd=%p\n",md,cd,fd,nd,gd);
4571 4572
    if      (md) { *resMember=md; *resContext=md; }
    else if (cd) *resContext=cd;
4573 4574 4575 4576
    else if (nd) *resContext=nd;
    else if (fd) *resContext=fd;
    else if (gd) *resContext=gd;
    else         { *resContext=0; *resMember=0; return FALSE; }
4577 4578
    //printf("member=%s (md=%p) anchor=%s linkable()=%d context=%s\n",
    //    md->name().data(),md,md->anchor().data(),md->isLinkable(),(*resContext)->name().data());
4579 4580
    return TRUE;
  }
4581
  else if (inSeeBlock && !nameStr.isEmpty() && (gd=Doxygen::groupSDict->find(nameStr)))
4582 4583 4584 4585
  { // group link
    *resContext=gd;
    return TRUE;
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4586 4587 4588 4589 4590 4591 4592 4593 4594 4595
  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;
    }
  }
4596

4597 4598
  if (tryUnspecializedVersion)
  {
4599
    return resolveRef(scName,name,inSeeBlock,resContext,resMember,FALSE,0,checkScope);
4600
  }
4601 4602 4603 4604 4605 4606 4607 4608
  if (bracePos!=-1) // Try without parameters as well, could be a contructor invocation
  {
    *resContext=getClass(fullName.left(bracePos));
    if (*resContext)
    {
      return TRUE;
    }
  }
4609
  //printf("resolveRef: %s not found!\n",name);
4610

4611 4612 4613
  return FALSE;
}

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

4638
#if 0
4639
/*
4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650
 * 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
4651
 *    4) "\#memberName     member variable, global variable or define
4652 4653 4654
 *    5) ("ScopeName::")+"memberName()" 
 *    6) ("ScopeName::")+"memberName(...)" 
 *    7) ("ScopeName::")+"memberName" 
4655
 * instead of :: the \# symbol may also be used.
4656 4657 4658
 */

bool generateRef(OutputDocInterface &od,const char *scName,
4659
    const char *name,bool inSeeBlock,const char *rt)
4660
{
4661
  //printf("generateRef(scName=%s,name=%s,inSee=%d,rt=%s)\n",scName,name,inSeeBlock,rt);
4662

4663 4664
  Definition *compound;
  MemberDef *md;
4665

4666
  // create default link text
4667
  QCString linkText = linkToText(rt,FALSE);
4668 4669 4670

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

4708
bool resolveLink(/* in */ const char *scName,
4709
    /* in */ const char *lr,
4710
    /* in */ bool /*inSeeBlock*/,
4711 4712 4713
    /* out */ Definition **resContext,
    /* out */ QCString &resAnchor
    )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4714
{
4715
  *resContext=0;
4716

4717
  QCString linkRef=lr;
4718
  //printf("ResolveLink linkRef=%s inSee=%d\n",lr,inSeeBlock);
4719
  FileDef  *fd;
4720
  GroupDef *gd;
4721
  PageDef  *pd;
4722
  ClassDef *cd;
4723
  DirDef   *dir;
4724
  NamespaceDef *nd;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4725
  SectionInfo *si=0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4726
  bool ambig;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4727
  if (linkRef.isEmpty()) // no reference name!
4728 4729 4730
  {
    return FALSE;
  }
4731
  else if ((pd=Doxygen::pageSDict->find(linkRef))) // link to a page
4732
  {
4733
    GroupDef *gd = pd->getGroupDef();
4734 4735
    if (gd)
    {
4736
      if (!pd->name().isEmpty()) si=Doxygen::sectionDict->find(pd->name());
4737 4738
      *resContext=gd;
      if (si) resAnchor = si->label;
4739 4740 4741
    }
    else
    {
4742
      *resContext=pd;
4743
    }
4744 4745
    return TRUE;
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4746 4747 4748 4749 4750 4751
  else if ((si=Doxygen::sectionDict->find(linkRef)))
  {
    *resContext=si->definition;
    resAnchor = si->label;
    return TRUE;
  }
4752
  else if ((pd=Doxygen::exampleSDict->find(linkRef))) // link to an example
4753
  {
4754
    *resContext=pd;
4755 4756
    return TRUE;
  }
4757
  else if ((gd=Doxygen::groupSDict->find(linkRef))) // link to a group
4758
  {
4759 4760 4761 4762 4763 4764 4765
    *resContext=gd;
    return TRUE;
  }
  else if ((fd=findFileDef(Doxygen::inputNameDict,linkRef,ambig)) // file link
      && fd->isLinkable())
  {
    *resContext=fd;
4766
    return TRUE;
4767
  }
4768 4769 4770
  else if ((cd=getClass(linkRef))) // class link
  {
    *resContext=cd;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4771
    resAnchor=cd->anchor();
4772 4773 4774
    return TRUE;
  }
  else if ((cd=getClass(linkRef+"-p"))) // Obj-C protocol link
4775 4776
  {
    *resContext=cd;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4777
    resAnchor=cd->anchor();
4778 4779
    return TRUE;
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4780 4781 4782 4783 4784 4785
//  else if ((cd=getClass(linkRef+"-g"))) // C# generic link
//  {
//    *resContext=cd;
//    resAnchor=cd->anchor();
//    return TRUE;
//  }
4786
  else if ((nd=Doxygen::namespaceSDict->find(linkRef)))
4787 4788 4789 4790
  {
    *resContext=nd;
    return TRUE;
  }
4791
  else if ((dir=Doxygen::directories->find(QFileInfo(linkRef).absFilePath().utf8()+"/"))
4792 4793 4794 4795 4796
      && dir->isLinkable()) // TODO: make this location independent like filedefs
  {
    *resContext=dir;
    return TRUE;
  }
4797
  else // probably a member reference
4798
  {
4799
    MemberDef *md;
4800
    bool res = resolveRef(scName,lr,TRUE,resContext,&md);
4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814
    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,
4815
    const char *lr,bool inSeeBlock,const char *lt)
4816
{
4817
  //printf("generateLink(clName=%s,lr=%s,lr=%s)\n",clName,lr,lt);
4818
  Definition *compound;
4819
  //PageDef *pageDef=0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4820
  QCString anchor,linkText=linkToText(SrcLangExt_Unknown,lt,FALSE);
4821
  //printf("generateLink linkText=%s\n",linkText.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4822
  if (resolveLink(clName,lr,inSeeBlock,&compound,anchor))
4823
  {
4824
    if (compound) // link to compound
4825
    {
4826 4827 4828
      if (lt==0 && anchor.isEmpty() &&                      /* compound link */
          compound->definitionType()==Definition::TypeGroup /* is group */ 
         )
4829
      {
4830
        linkText=((GroupDef *)compound)->groupTitle(); // use group's title as link
4831
      }
4832 4833
      else if (compound->definitionType()==Definition::TypeFile)
      {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4834
        linkText=linkToText(compound->getLanguage(),lt,TRUE); 
4835
      }
4836
      od.writeObjectLink(compound->getReference(),
4837
          compound->getOutputFileBase(),anchor,linkText);
4838 4839 4840 4841
      if (!compound->isReference())
      {
        writePageRef(od,compound->getOutputFileBase(),anchor);
      }
4842
    }
4843 4844
    else
    {
4845
      err("%s:%d: Internal error: resolveLink successful but no compound found!",__FILE__,__LINE__);
4846
    }
4847 4848
    return TRUE;
  }
4849
  else // link could not be found
4850
  {
4851 4852
    od.docify(linkText);
    return FALSE;
4853
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4854 4855
}

4856
void generateFileRef(OutputDocInterface &od,const char *name,const char *text)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4857
{
4858
  //printf("generateFileRef(%s,%s)\n",name,text);
4859
  QCString linkText = text ? text : name;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4860 4861 4862
  //FileInfo *fi;
  FileDef *fd;
  bool ambig;
4863
  if ((fd=findFileDef(Doxygen::inputNameDict,name,ambig)) && 
4864
      fd->isLinkable()) 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4865
    // link to documented input file
4866
    od.writeObjectLink(fd->getReference(),fd->getOutputFileBase(),0,linkText);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4867
  else
4868
    od.docify(linkText); 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4869 4870 4871 4872
}

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

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4873
#if 0
4874
QCString substituteClassNames(const QCString &s)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4875 4876
{
  int i=0,l,p;
4877
  QCString result;
4878
  if (s.isEmpty()) return result;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4879 4880 4881
  QRegExp r("[a-z_A-Z][a-z_A-Z0-9]*");
  while ((p=r.match(s,i,&l))!=-1)
  {
4882
    QCString *subst;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896
    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
4897
#endif
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4898 4899 4900

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

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4901
/** Cache element for the file name to FileDef mapping cache. */
4902 4903 4904 4905 4906 4907 4908 4909 4910
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
4911 4912 4913
FileDef *findFileDef(const FileNameDict *fnDict,const char *n,bool &ambig)
{
  ambig=FALSE;
4914 4915 4916 4917 4918 4919 4920 4921
  if (n==0) return 0;

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

  g_findFileDefCache.setAutoDelete(TRUE);
  FindFileCacheElem *cachedResult = g_findFileDefCache.find(key);
4922
  //printf("key=%s cachedResult=%p\n",key.data(),cachedResult);
4923 4924 4925
  if (cachedResult)
  {
    ambig = cachedResult->isAmbig;
4926
    //printf("cached: fileDef=%p\n",cachedResult->fileDef);
4927 4928 4929 4930 4931 4932
    return cachedResult->fileDef;
  }
  else
  {
    cachedResult = new FindFileCacheElem(0,FALSE);
  }
4933

4934
  QCString name=QDir::cleanDirPath(n).utf8();
4935
  QCString path;
4936 4937 4938 4939
  int slashPos;
  FileName *fn;
  if (name.isEmpty()) goto exit;
  slashPos=QMAX(name.findRev('/'),name.findRev('\\'));
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4940 4941 4942 4943
  if (slashPos!=-1)
  {
    path=name.left(slashPos+1);
    name=name.right(name.length()-slashPos-1); 
4944
    //printf("path=%s name=%s\n",path.data(),name.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4945
  }
4946
  if (name.isEmpty()) goto exit;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4947 4948
  if ((fn=(*fnDict)[name]))
  {
4949
    //printf("fn->count()=%d\n",fn->count());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4950 4951
    if (fn->count()==1)
    {
4952
      FileDef *fd = fn->getFirst();
4953 4954 4955 4956 4957 4958
#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)
4959
      {
4960 4961
        cachedResult->fileDef = fd;
        g_findFileDefCache.insert(key,cachedResult);
4962
        //printf("=1 ===> add to cache %p\n",fd);
4963 4964
        return fd;
      }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4965
    }
4966
    else // file name alone is ambiguous
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4967 4968
    {
      int count=0;
4969 4970
      FileNameIterator fni(*fn);
      FileDef *fd;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4971
      FileDef *lastMatch=0;
4972
      QCString pathStripped = stripFromIncludePath(path);
4973
      for (fni.toFirst();(fd=fni.current());++fni)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4974
      {
4975
        QCString fdStripPath = stripFromIncludePath(fd->getPath());
4976
        if (path.isEmpty() || fdStripPath.right(pathStripped.length())==pathStripped) 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4977 4978 4979 4980 4981
        { 
          count++; 
          lastMatch=fd; 
        }
      }
4982
      //printf(">1 ===> add to cache %p\n",fd);
4983

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4984
      ambig=(count>1);
4985 4986 4987
      cachedResult->isAmbig = ambig;
      cachedResult->fileDef = lastMatch;
      g_findFileDefCache.insert(key,cachedResult);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4988 4989 4990
      return lastMatch;
    }
  }
4991 4992 4993 4994
  else
  {
    //printf("not found!\n");
  }
4995
exit:
4996
  //printf("0  ===> add to cache %p: %s\n",cachedResult,n);
4997
  g_findFileDefCache.insert(key,cachedResult);
4998
  //delete cachedResult;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4999 5000 5001 5002 5003
  return 0;
}

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

5004
QCString showFileDefMatches(const FileNameDict *fnDict,const char *n)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5005
{
5006
  QCString result;
5007 5008
  QCString name=n;
  QCString path;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5009 5010 5011 5012 5013 5014 5015 5016 5017
  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]))
  {
5018 5019 5020
    FileNameIterator fni(*fn);
    FileDef *fd;
    for (fni.toFirst();(fd=fni.current());++fni)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5021
    {
5022
      if (path.isEmpty() || fd->getPath().right(path.length())==path)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5023
      {
5024
        result+="   "+fd->absFilePath()+"\n";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5025 5026 5027
      }
    }
  }
5028
  return result;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5029 5030
}

5031 5032
//----------------------------------------------------------------------

Dimitri van Heesch's avatar
Dimitri van Heesch committed
5033 5034
QCString substituteKeywords(const QCString &s,const char *title,
         const char *projName,const char *projNum,const char *projBrief)
5035
{
5036
  QCString result = s;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5037 5038 5039
  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
5040
  result = substitute(result,"$year",yearToString());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5041
  result = substitute(result,"$doxygenversion",versionString);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5042 5043 5044
  result = substitute(result,"$projectname",projName);
  result = substitute(result,"$projectnumber",projNum);
  result = substitute(result,"$projectbrief",projBrief);
5045
  result = substitute(result,"$projectlogo",stripPath(Config_getString("PROJECT_LOGO")));
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5046
  return result;
5047
}
5048

Dimitri van Heesch's avatar
Dimitri van Heesch committed
5049 5050
//----------------------------------------------------------------------

5051
/*! Returns the character index within \a name of the first prefix
5052
 *  in Config_getList("IGNORE_PREFIX") that matches \a name at the left hand side,
5053 5054 5055 5056
 *  or zero if no match was found
 */ 
int getPrefixIndex(const QCString &name)
{
5057
  if (name.isEmpty()) return 0;
5058
  static QStrList &sl = Config_getList("IGNORE_PREFIX");
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5059
  char *s = sl.first();
5060 5061 5062
  while (s)
  {
    const char *ps=s;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5063
    const char *pd=name.data();
5064 5065 5066 5067
    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
5068
      return i;
5069
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5070
    s = sl.next();
5071
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5072
  return 0;
5073
}
5074 5075 5076 5077 5078

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

static void initBaseClassHierarchy(BaseClassList *bcl)
{
5079
  if (bcl==0) return;
5080 5081 5082 5083
  BaseClassListIterator bcli(*bcl);
  for ( ; bcli.current(); ++bcli)
  {
    ClassDef *cd=bcli.current()->classDef;
5084
    if (cd->baseClasses()==0) // no base classes => new root
5085 5086 5087 5088 5089 5090
    {
      initBaseClassHierarchy(cd->baseClasses());
    }
    cd->visited=FALSE;
  }
}
5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118
//----------------------------------------------------------------------------

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;
}

5119 5120 5121

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

Dimitri van Heesch's avatar
Dimitri van Heesch committed
5122
void initClassHierarchy(ClassSDict *cl)
5123
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5124
  ClassSDict::Iterator cli(*cl);
5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136
  ClassDef *cd;
  for ( ; (cd=cli.current()); ++cli)
  {
    cd->visited=FALSE;
    initBaseClassHierarchy(cd->baseClasses());
  }
}

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

bool hasVisibleRoot(BaseClassList *bcl)
{
5137
  if (bcl)
5138
  {
5139 5140 5141 5142 5143 5144 5145
    BaseClassListIterator bcli(*bcl);
    for ( ; bcli.current(); ++bcli)
    {
      ClassDef *cd=bcli.current()->classDef;
      if (cd->isVisibleInHierarchy()) return TRUE;
      hasVisibleRoot(cd->baseClasses());
    }
5146 5147 5148 5149
  }
  return FALSE;
}

5150 5151
//----------------------------------------------------------------------

5152
// note that this function is not reentrant due to the use of static growBuf!
5153
QCString escapeCharsInString(const char *name,bool allowDots,bool allowUnderscore)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5154
{
5155
  static bool caseSenseNames = Config_getBool("CASE_SENSE_NAMES");
5156
  static bool allowUnicodeNames = Config_getBool("ALLOW_UNICODE_NAMES");
5157 5158
  static GrowBuf growBuf;
  growBuf.clear();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5159 5160 5161 5162 5163 5164
  char c;
  const char *p=name;
  while ((c=*p++)!=0)
  {
    switch(c)
    {
5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187
      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;
5188
      case '\\': growBuf.addStr("_0C"); break;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5189
      default: 
5190 5191 5192
                if (c<0)
                {
                  char ids[5];
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 5234 5235 5236 5237 5238 5239 5240 5241 5242
                  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);
                  }
5243 5244
                }
                else if (caseSenseNames || !isupper(c))
5245
                {
5246
                  growBuf.addChar(c);
5247 5248 5249
                }
                else
                {
5250 5251
                  growBuf.addChar('_');
                  growBuf.addChar(tolower(c)); 
5252 5253
                }
                break;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5254 5255
    }
  }
5256 5257
  growBuf.addChar(0);
  return growBuf.get();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5258 5259
}

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

5275
    int *value=usedNames.find(name);
5276 5277 5278
    int num;
    if (value==0)
    {
5279
      usedNames.insert(name,new int(count));
5280 5281 5282 5283
      num = count++;
    }
    else
    {
5284
      num = *value;
5285 5286 5287 5288 5289
    }
    result.sprintf("a%05d",num); 
  }
  else // long names
  {
5290
    result=escapeCharsInString(name,allowDots,allowUnderscore);
5291 5292 5293 5294 5295 5296 5297 5298 5299 5300
    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; 
    }
5301
  }
5302
  if (createSubdirs)
5303
  {
5304 5305 5306 5307 5308
    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.
5309 5310 5311 5312 5313 5314 5315 5316 5317 5318
    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)); 
5319 5320
      l1Dir = (curDirNum)&0xf;    // bits 0-3
      l2Dir = (curDirNum>>4)&0xff; // bits 4-11
5321 5322 5323 5324
      curDirNum++;
    }
    else // existing name
    {
5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340
      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));
5341
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5342
  //printf("*** convertNameToFile(%s)->%s\n",name,result.data());
5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371
  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"))
  {
5372
    // create 4096 subdirectories
5373
    int l1,l2;
5374
    for (l1=0;l1<16;l1++)
5375
    {
5376
      d.mkdir(QCString().sprintf("d%x",l1));
5377
      for (l2=0;l2<256;l2++)
5378
      {
5379
        d.mkdir(QCString().sprintf("d%x/d%02x",l1,l2));
5380 5381
      }
    }
5382 5383
  }
}
5384

Dimitri van Heesch's avatar
Dimitri van Heesch committed
5385 5386 5387 5388
/*! 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,
5389 5390
    QCString &className,QCString &namespaceName,
    bool allowEmptyClass)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5391
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5392 5393
  int i,p;
  QCString clName=scopeName;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5394
  NamespaceDef *nd = 0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5395
  if (!clName.isEmpty() && (nd=getResolvedNamespace(clName)) && getClass(clName)==0)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5396
  { // the whole name is a namespace (and not a class)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5397
    namespaceName=nd->name().copy();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5398
    className.resize(0);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5399
    goto done;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5400
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5401
  p=clName.length()-2;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5402 5403 5404
  while (p>=0 && (i=clName.findRev("::",p))!=-1) 
    // see if the first part is a namespace (and not a class)
  {
5405
    //printf("Trying %s\n",clName.left(i).data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5406
    if (i>0 && (nd=getResolvedNamespace(clName.left(i))) && getClass(clName.left(i))==0)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5407
    {
5408
      //printf("found!\n");
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5409
      namespaceName=nd->name().copy();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5410
      className=clName.right(clName.length()-i-2);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5411
      goto done;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5412 5413 5414
    } 
    p=i-2; // try a smaller piece of the scope
  }
5415
  //printf("not found!\n");
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5416 5417

  // not found, so we just have to guess.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5418 5419
  className=scopeName.copy();
  namespaceName.resize(0);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5420 5421

done:
5422
  if (className.isEmpty() && !namespaceName.isEmpty() && !allowEmptyClass)
5423 5424 5425 5426 5427
  {
    // 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
5428 5429
  //printf("extractNamespace `%s' => `%s|%s'\n",scopeName.data(),
  //       className.data(),namespaceName.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5430
  if (/*className.right(2)=="-g" ||*/ className.right(2)=="-p")
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5431 5432 5433
  {
    className = className.left(className.length()-2);
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5434 5435 5436
  return;
}

5437 5438 5439 5440 5441 5442
QCString insertTemplateSpecifierInScope(const QCString &scope,const QCString &templ)
{
  QCString result=scope.copy();
  if (!templ.isEmpty() && scope.find('<')==-1)
  {
    int si,pi=0;
5443 5444
    ClassDef *cd=0;
    while (
5445 5446 5447
        (si=scope.find("::",pi))!=-1 && !getClass(scope.left(si)+templ) && 
        ((cd=getClass(scope.left(si)))==0 || cd->templateArguments()==0) 
        ) 
5448 5449 5450 5451
    { 
      //printf("Tried `%s'\n",(scope.left(si)+templ).data()); 
      pi=si+2; 
    }
5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464
    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;
}
5465

5466
#if 0 // original version
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5467 5468 5469
/*! Strips the scope from a name. Examples: A::B will return A
 *  and A<T>::B<N::C<D> > will return A<T>.
 */
5470 5471 5472
QCString stripScope(const char *name)
{
  QCString result = name;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5473 5474 5475 5476 5477 5478
  int l=result.length();
  int p=l-1;
  bool done;
  int count;

  while (p>=0)
5479
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498
    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: 
5499 5500
                      //printf("c=%c count=%d\n",c,count);
                      break;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5501 5502 5503 5504 5505 5506 5507
          }
        }
        //printf("pos > = %d\n",p+1);
        break;
      default:
        p--;
    }
5508
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5509 5510
  //printf("stripScope(%s)=%s\n",name,name);
  return name;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5511
}
5512
#endif
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5513 5514 5515 5516 5517 5518 5519

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

Dimitri van Heesch's avatar
Dimitri van Heesch committed
5524 5525 5526 5527 5528 5529 5530 5531 5532
  do
  {
    p=l-1; // start at the end of the string
    while (p>=0 && count>=0)
    {
      char c=result.at(p);
      switch (c)
      {
        case ':': 
5533
          // only exit in the case of ::
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5534
          //printf("stripScope(%s)=%s\n",name,result.right(l-p-1).data());
5535 5536 5537
          if (p>0 && result.at(p-1)==':') return result.right(l-p-1);
          p--;
          break;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552
        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--;
5553 5554
            bool foundMatch=false;
            while (p>=0 && !foundMatch)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571
            {
              c=result.at(p--);
              switch (c)
              {
                case '>': 
                  count++; 
                  break;
                case '<': 
                  if (p>0)
                  {
                    if (result.at(p-1) == '<') // skip << operator
                    {
                      p--;
                      break;
                    }
                  }
                  count--; 
5572
                  foundMatch = count==0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591
                  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;
5592
}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5593

5594

Dimitri van Heesch's avatar
Dimitri van Heesch committed
5595
/*! Converts a string to an XML-encoded string */
5596 5597
QCString convertToXML(const char *s)
{
5598 5599
  static GrowBuf growBuf;
  growBuf.clear();
5600
  if (s==0) return "";
5601 5602 5603 5604 5605 5606
  const char *p=s;
  char c;
  while ((c=*p++))
  {
    switch (c)
    {
5607 5608 5609 5610 5611
      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;
5612 5613 5614 5615 5616
      case  1: case  2: case  3: case  4: case  5: case  6: case  7: case  8:
      case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18:
      case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26:
      case 27: case 28: case 29: case 30: case 31:
        break; // skip invalid XML characters (see http://www.w3.org/TR/2000/REC-xml-20001006#NT-Char)
5617
      default:   growBuf.addChar(c);       break;
5618 5619
    }
  }
5620 5621
  growBuf.addChar(0);
  return growBuf.get();
5622
}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5623 5624

/*! Converts a string to a HTML-encoded string */
5625
QCString convertToHtml(const char *s,bool keepEntities)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5626
{
5627 5628
  static GrowBuf growBuf;
  growBuf.clear();
5629
  if (s==0) return "";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5630 5631 5632 5633 5634 5635
  const char *p=s;
  char c;
  while ((c=*p++))
  {
    switch (c)
    {
5636 5637
      case '<':  growBuf.addStr("&lt;");   break;
      case '>':  growBuf.addStr("&gt;");   break;
5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648
      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
5649 5650
                     growBuf.addChar(c);
                     while (p<e) growBuf.addChar(*p++);
5651 5652 5653
                   }
                   else
                   {
5654
                     growBuf.addStr("&amp;");
5655 5656 5657 5658
                   }
                 }
                 else
                 {
5659
                   growBuf.addStr("&amp;");  
5660 5661
                 }
                 break;
5662 5663 5664
      case '\'': growBuf.addStr("&#39;");  break; 
      case '"':  growBuf.addStr("&quot;"); break;
      default:   growBuf.addChar(c);       break;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5665 5666
    }
  }
5667 5668
  growBuf.addChar(0);
  return growBuf.get();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5669 5670
}

5671 5672
QCString convertToJSString(const char *s)
{
5673 5674
  static GrowBuf growBuf;
  growBuf.clear();
5675 5676 5677 5678 5679 5680 5681
  if (s==0) return "";
  const char *p=s;
  char c;
  while ((c=*p++))
  {
    switch (c)
    {
5682 5683 5684
      case '"':  growBuf.addStr("\\\""); break;
      case '\\': growBuf.addStr("\\\\"); break;
      default:   growBuf.addChar(c);   break;
5685 5686
    }
  }
5687
  growBuf.addChar(0);
5688
  return convertCharEntitiesToUTF8(growBuf.get());
5689 5690 5691
}


5692 5693 5694
QCString convertCharEntitiesToUTF8(const QCString &s)
{
  QCString result;
5695
  static QRegExp entityPat("&[a-zA-Z]+[0-9]*;");
5696

5697 5698 5699
  if (s.length()==0) return result;
  static GrowBuf growBuf;
  growBuf.clear();
5700 5701 5702
  int p,i=0,l;
  while ((p=entityPat.match(s,i,&l))!=-1)
  {
5703
    if (p>i)
5704 5705 5706
    {
      growBuf.addStr(s.mid(i,p-i));
    }
5707 5708 5709 5710
    QCString entity = s.mid(p,l);
    DocSymbol::SymType symType = HtmlEntityMapper::instance()->name2sym(entity);
    const char *code=0;
    if (symType!=DocSymbol::Sym_Unknown && (code=HtmlEntityMapper::instance()->utf8(symType)))
5711
    {
5712
      growBuf.addStr(code);
5713 5714 5715
    }
    else
    {
5716
      growBuf.addStr(s.mid(p,l));
5717 5718 5719
    }
    i=p+l;
  }
5720 5721
  growBuf.addStr(s.mid(i,s.length()-i));
  growBuf.addChar(0);
5722
  //printf("convertCharEntitiesToUTF8(%s)->%s\n",s.data(),growBuf.get());
5723
  return growBuf.get();
5724 5725
}

5726 5727 5728
/*! Returns the standard string that is generated when the \\overload
 * command is used.
 */
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5729
QCString getOverloadDocs()
5730
{
5731 5732 5733 5734
  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.";
5735
}
5736

Dimitri van Heesch's avatar
Dimitri van Heesch committed
5737
void addMembersToMemberGroup(MemberList *ml,
5738 5739
    MemberGroupSDict **ppMemberGroupSDict,
    Definition *context)
5740
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5741
  ASSERT(context!=0);
5742
  //printf("addMemberToMemberGroup()\n");
5743
  if (ml==0) return;
5744 5745 5746 5747 5748
  MemberListIterator mli(*ml);
  MemberDef *md;
  uint index;
  for (index=0;(md=mli.current());)
  {
5749 5750
    if (md->isEnumerate()) // insert enum value of this enum into groups
    {
5751
      MemberList *fmdl=md->enumFieldList();
5752
      if (fmdl!=0)
5753
      {
5754 5755 5756
        MemberListIterator fmli(*fmdl);
        MemberDef *fmd;
        for (fmli.toFirst();(fmd=fmli.current());++fmli)
5757 5758 5759 5760
        {
          int groupId=fmd->getMemberGroupId();
          if (groupId!=-1)
          {
5761 5762 5763 5764
            MemberGroupInfo *info = Doxygen::memGrpInfoDict[groupId];
            //QCString *pGrpHeader = Doxygen::memberHeaderDict[groupId];
            //QCString *pDocs      = Doxygen::memberDocDict[groupId];
            if (info)
5765
            {
5766 5767 5768 5769 5770 5771
              if (*ppMemberGroupSDict==0)
              {
                *ppMemberGroupSDict = new MemberGroupSDict;
                (*ppMemberGroupSDict)->setAutoDelete(TRUE);
              }
              MemberGroup *mg = (*ppMemberGroupSDict)->find(groupId);
5772 5773
              if (mg==0)
              {
5774
                mg = new MemberGroup(
5775 5776 5777 5778 5779 5780
                    context,
                    groupId,
                    info->header,
                    info->doc,
                    info->docFile
                    );
5781
                (*ppMemberGroupSDict)->append(groupId,mg);
5782
              }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5783
              mg->insertMember(fmd); // insert in member group
5784 5785 5786 5787 5788 5789
              fmd->setMemberGroup(mg);
            }
          }
        }
      }
    }
5790 5791 5792
    int groupId=md->getMemberGroupId();
    if (groupId!=-1)
    {
5793 5794 5795 5796
      MemberGroupInfo *info = Doxygen::memGrpInfoDict[groupId];
      //QCString *pGrpHeader = Doxygen::memberHeaderDict[groupId];
      //QCString *pDocs      = Doxygen::memberDocDict[groupId];
      if (info)
5797
      {
5798 5799 5800 5801 5802 5803
        if (*ppMemberGroupSDict==0)
        {
          *ppMemberGroupSDict = new MemberGroupSDict;
          (*ppMemberGroupSDict)->setAutoDelete(TRUE);
        }
        MemberGroup *mg = (*ppMemberGroupSDict)->find(groupId);
5804 5805
        if (mg==0)
        {
5806
          mg = new MemberGroup(
5807 5808 5809 5810 5811 5812
              context,
              groupId,
              info->header,
              info->doc,
              info->docFile
              );
5813
          (*ppMemberGroupSDict)->append(groupId,mg);
5814
        }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5815
        md = ml->take(index); // remove from member list
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5816
        mg->insertMember(md); // insert in member group
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5817
        mg->setRefItems(info->m_sli);
5818
        md->setMemberGroup(mg);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5819
        continue;
5820 5821
      }
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5822
    ++mli;++index;
5823 5824
  }
}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5825 5826

/*! Extracts a (sub-)string from \a type starting at \a pos that
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5827 5828 5829
 *  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
5830
 */
5831
int extractClassNameFromType(const QCString &type,int &pos,QCString &name,QCString &templSpec,SrcLangExt lang)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5832
{
5833 5834 5835 5836
  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;

5837 5838 5839 5840 5841
  name.resize(0);
  templSpec.resize(0);
  int i,l;
  int typeLen=type.length();
  if (typeLen>0)
5842
  {
5843
    if (lang == SrcLangExt_Fortran)
5844
    {
5845 5846 5847 5848 5849 5850 5851 5852 5853
      if (type.at(pos)==',') return -1;
      if (type.left(4).lower()=="type")
      {
        re = re_norm;
      }
      else
      {
        re = re_ftn;
      }
5854 5855 5856
    }
    else
    {
5857
      re = re_norm;
5858 5859
    }

Dimitri van Heesch's avatar
Dimitri van Heesch committed
5860 5861 5862 5863
    if ((i=re.match(type,pos,&l))!=-1) // for each class name in the type
    {
      int ts=i+l;
      int te=ts;
5864 5865
      int tl=0;
      while (type.at(ts)==' ' && ts<typeLen) ts++,tl++; // skip any whitespace
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884
      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
5885 5886 5887 5888 5889 5890 5891 5892 5893
      if (te>ts) 
      {
        templSpec = type.mid(ts,te-ts),tl+=te-ts;
        pos=i+l+tl;
      }
      else // no template part
      {
        pos=i+l;
      }
5894 5895
      //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
5896
      return i;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5897 5898
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5899
  pos = typeLen;
5900 5901
  //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
5902
  return -1;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5903 5904
}

5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960
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);
}


5961 5962 5963
/*! 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
5964
 *  is returned as a string. The argument \a name is used to
5965
 *  prevent recursive substitution.
5966 5967
 */
QCString substituteTemplateArgumentsInString(
5968 5969 5970
    const QCString &name,
    ArgumentList *formalArgs,
    ArgumentList *actualArgs)
5971
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
5972 5973
  //printf("substituteTemplateArgumentsInString(name=%s formal=%s actualArg=%s)\n",
  //    name.data(),argListToString(formalArgs).data(),argListToString(actualArgs).data());
5974 5975
  if (formalArgs==0) return name;
  QCString result;
5976
  static QRegExp re("[a-z_A-Z\\x80-\\xFF][a-z_A-Z0-9\\x80-\\xFF]*");
5977 5978 5979 5980 5981 5982 5983
  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);
5984
    ArgumentListIterator actAli(*actualArgs);
5985
    Argument *formArg;
5986
    Argument *actArg;
5987 5988 5989 5990 5991

    // if n is a template argument, then we substitute it
    // for its template instance argument.
    bool found=FALSE;
    for (formAli.toFirst();
5992 5993
        (formArg=formAli.current()) && !found && (actArg=actAli.current());
        ++formAli,++actAli
5994 5995
        )
    {
5996 5997 5998 5999 6000 6001 6002 6003 6004 6005
      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
6006
      if (formArg->type=="class" || formArg->type=="typename" || formArg->type.left(8)=="template")
6007
      {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6008
        //printf("n=%s formArg->type='%s' formArg->name='%s' formArg->defval='%s'\n",
6009
        //  n.data(),formArg->type.data(),formArg->name.data(),formArg->defval.data());
6010 6011 6012
        //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
6013 6014 6015
        if (formArg->name==n && actArg && !actArg->type.isEmpty()) // base class is a template argument
        {
          // replace formal argument with the actual argument of the instance
6016 6017 6018 6019 6020 6021
          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
6022
          {
6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034
            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;
            }
6035
          }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6036
        }
6037 6038 6039 6040
        else if (formArg->name==n && 
                 actArg==0 && 
                 !formArg->defval.isEmpty() &&
                 formArg->defval!=name /* to prevent recursion */
6041
            )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6042
        {
6043
          result += substituteTemplateArgumentsInString(formArg->defval,formalArgs,actualArgs)+" ";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6044 6045
          found=TRUE;
        }
6046
      }
6047 6048 6049 6050 6051
      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
6052 6053 6054 6055
      {
        result += substituteTemplateArgumentsInString(formArg->defval,formalArgs,actualArgs)+" ";
        found=TRUE;
      }
6056
    }
6057 6058 6059 6060
    if (!found) 
    {
      result += n;
    }
6061 6062 6063 6064 6065
    p=i+l;
  }
  result+=name.right(name.length()-p);
  //printf("      Inheritance relation %s -> %s\n",
  //    name.data(),result.data());
6066
  return result.stripWhiteSpace();
6067 6068
}

6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080
/*! 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)
  {
6081
    dstLists->append(sl->deepCopy());
6082 6083 6084 6085 6086 6087 6088 6089
  }
  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 
6090
 *  try to strip \<T\> and not \<S\>, while \a parentOnly is \c FALSE will 
6091 6092 6093
 *  strip both unless A<T> or B<S> are specialized template classes. 
 */
QCString stripTemplateSpecifiersFromScope(const QCString &fullName,
6094 6095
    bool parentOnly,
    QCString *pLastScopeStripped)
6096 6097 6098 6099 6100
{
  QCString result;
  int p=0;
  int l=fullName.length();
  int i=fullName.find('<');
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6101
  while (i!=-1)
6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119
  {
    //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
6120 6121 6122
    int si= fullName.find("::",e);

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

    result+=fullName.mid(p,i-p);
6126
    //printf("  trying %s\n",(result+fullName.mid(i,e-i)).data());
6127
    if (getClass(result+fullName.mid(i,e-i))!=0)
6128 6129
    {
      result+=fullName.mid(i,e-i);
6130
      //printf("  2:result+=%s\n",fullName.mid(i,e-i-1).data());
6131
    }
6132 6133
    else if (pLastScopeStripped)
    {
6134
      //printf("  last stripped scope '%s'\n",fullName.mid(i,e-i).data());
6135 6136
      *pLastScopeStripped=fullName.mid(i,e-i);
    }
6137 6138 6139 6140 6141 6142 6143
    p=e;
    i=fullName.find('<',p);
  }
  result+=fullName.right(l-p);
  //printf("3:result+=%s\n",fullName.right(l-p).data());
  return result;
}
6144

Dimitri van Heesch's avatar
Dimitri van Heesch committed
6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233
/*! 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;
}

6234 6235
//----------------------------------------------------------------------------

6236
PageDef *addRelatedPage(const char *name,const QCString &ptitle,
6237 6238 6239 6240 6241
    const QCString &doc,
    QList<SectionInfo> * /*anchors*/,
    const char *fileName,int startLine,
    const QList<ListItemInfo> *sli,
    GroupDef *gd,
6242 6243
    TagInfo *tagInfo,
    SrcLangExt lang
6244
    )
6245
{
6246
  PageDef *pd=0;
6247
  //printf("addRelatedPage(name=%s gd=%p)\n",name,gd);
6248
  if ((pd=Doxygen::pageSDict->find(name)) && !tagInfo)
6249 6250
  {
    // append documentation block to the page.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6251
    pd->setDocumentation(doc,fileName,startLine);
6252
    //printf("Adding page docs `%s' pi=%p name=%s\n",doc.data(),pi,name);
6253 6254 6255 6256 6257 6258
  }
  else // new page
  {
    QCString baseName=name;
    if (baseName.right(4)==".tex") 
      baseName=baseName.left(baseName.length()-4);
6259 6260
    else if (baseName.right(Doxygen::htmlFileExtension.length())==Doxygen::htmlFileExtension)
      baseName=baseName.left(baseName.length()-Doxygen::htmlFileExtension.length());
6261

6262
    QCString title=ptitle.stripWhiteSpace();
6263
    pd=new PageDef(fileName,startLine,baseName,doc,title);
6264

6265
    pd->setRefItems(sli);
6266
    pd->setLanguage(lang);
6267

6268 6269
    if (tagInfo)
    {
6270
      pd->setReference(tagInfo->tagName);
6271
      pd->setFileName(tagInfo->fileName,TRUE);
6272 6273 6274
    }
    else
    {
6275
      pd->setFileName(convertNameToFile(pd->name(),FALSE,TRUE),FALSE);
6276 6277
    }

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

6281
    if (gd) gd->addPage(pd);
6282

6283
    if (!pd->title().isEmpty())
6284 6285 6286 6287
    {
      //outputList->writeTitle(pi->name,pi->title);

      // a page name is a label as well!
6288
      QCString file;
6289 6290
      if (gd)
      {
6291
        file=gd->getOutputFileBase();
6292
      }
6293
      else 
6294
      {
6295
        file=pd->getOutputFileBase();
6296
      }
6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319
      SectionInfo *si = Doxygen::sectionDict->find(pd->name());
      if (si)
      {
        if (si->lineNr != -1)
        {
          warn(file,-1,"multiple use of section label '%s', (first occurrence: %s, line %d)",pd->name().data(),si->fileName.data(),si->lineNr);
        }
        else
        {
          warn(file,-1,"multiple use of section label '%s', (first occurrence: %s)",pd->name().data(),si->fileName.data());
        }
      }
      else
      {
        si=new SectionInfo(
            file,-1,pd->name(),pd->title(),SectionInfo::Page,0,pd->getReference());
        //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());
        //printf("Adding section key=%s si->fileName=%s\n",pageName.data(),si->fileName.data());
        Doxygen::sectionDict->append(pd->name(),si);
      }
6320 6321
    }
  }
6322
  return pd;
6323 6324 6325 6326
}

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

6327
void addRefItem(const QList<ListItemInfo> *sli,
6328
    const char *key, 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6329
    const char *prefix, const char *name,const char *title,const char *args)
6330
{
6331
  //printf("addRefItem(sli=%p,key=%s,prefix=%s,name=%s,title=%s,args=%s)\n",sli,key,prefix,name,title,args);
6332
  if (sli && key && key[0]!='@') // check for @ to skip anonymous stuff (see bug427012)
6333 6334 6335 6336 6337
  {
    QListIterator<ListItemInfo> slii(*sli);
    ListItemInfo *lii;
    for (slii.toFirst();(lii=slii.current());++slii)
    {
6338
      RefList *refList = Doxygen::xrefLists->find(lii->type);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6339 6340
      if (refList
          &&
6341 6342
          (
           // either not a built-in list or the list is enabled
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6343 6344 6345
           (lii->type!="todo"       || Config_getBool("GENERATE_TODOLIST")) &&
           (lii->type!="test"       || Config_getBool("GENERATE_TESTLIST")) &&
           (lii->type!="bug"        || Config_getBool("GENERATE_BUGLIST"))  &&
6346
           (lii->type!="deprecated" || Config_getBool("GENERATE_DEPRECATEDLIST"))
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6347
          )
6348
         )
6349 6350 6351
      {
        RefItem *item = refList->getRefItem(lii->itemId);
        ASSERT(item!=0);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6352 6353 6354 6355 6356 6357

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

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

6360 6361
      }
    }
6362 6363 6364
  }
}

6365
bool recursivelyAddGroupListToTitle(OutputList &ol,Definition *d,bool root)
6366
{
6367 6368
  GroupList *groups = d->partOfGroups();
  if (groups) // write list of group to which this definition belongs
6369
  {
6370 6371
    if (root)
    {
Jeff Verkoeyen's avatar
Jeff Verkoeyen committed
6372 6373 6374 6375
      ol.pushGeneratorState();
      ol.disableAllBut(OutputGenerator::Html);
      ol.writeString("<div class=\"ingroups\">");
    }
6376
    GroupListIterator gli(*groups);
6377
    GroupDef *gd;
Jeff Verkoeyen's avatar
Jeff Verkoeyen committed
6378
    bool first=true;
6379 6380
    for (gli.toFirst();(gd=gli.current());++gli)
    {
6381 6382 6383
      if (recursivelyAddGroupListToTitle(ol, gd, FALSE))
      {
        ol.writeString(" &raquo; ");
Jeff Verkoeyen's avatar
Jeff Verkoeyen committed
6384 6385
      }
      if (!first) { ol.writeString(" &#124; "); } else first=FALSE;
6386
      ol.writeObjectLink(gd->getReference(),gd->getOutputFileBase(),0,gd->groupTitle());
6387
    }
6388 6389
    if (root)
    {
Jeff Verkoeyen's avatar
Jeff Verkoeyen committed
6390 6391 6392 6393
      ol.writeString("</div>");
      ol.popGeneratorState();
    }
    return true;
6394
  }
Jeff Verkoeyen's avatar
Jeff Verkoeyen committed
6395 6396 6397 6398 6399
  return false;
}

void addGroupListToTitle(OutputList &ol,Definition *d)
{
6400
  recursivelyAddGroupListToTitle(ol,d,TRUE);
6401
}
6402

6403
void filterLatexString(FTextStream &t,const char *str,
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6404
    bool insideTabbing,bool insidePre,bool insideItem)
6405
{
6406
  if (str==0) return;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6407 6408
  //printf("filterLatexString(%s)\n",str);
  //if (strlen(str)<2) stackTrace();
6409 6410 6411 6412
  const unsigned char *p=(const unsigned char *)str;
  unsigned char c;
  unsigned char pc='\0';
  while (*p)
6413
  {
6414
    c=*p++;
6415

6416 6417 6418
    if (insidePre)
    {
      switch(c)
6419
      {
6420 6421 6422 6423 6424 6425
        case '\\': t << "\\(\\backslash\\)"; break;
        case '{':  t << "\\{"; break;
        case '}':  t << "\\}"; break;
        case '_':  t << "\\_"; break;
        default: 
                   t << (char)c;
6426
      }
6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437
    }
    else
    {
      switch(c)
      {
        case '#':  t << "\\#";           break;
        case '$':  t << "\\$";           break;
        case '%':  t << "\\%";           break;
        case '^':  t << "$^\\wedge$";    break;
        case '&':  t << "\\&";           break;
        case '*':  t << "$\\ast$";       break;
6438
        case '_':  if (!insideTabbing) t << "\\+";  
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6439
                   t << "\\_"; 
6440
                   if (!insideTabbing) t << "\\+";  
6441 6442 6443 6444 6445
                   break;
        case '{':  t << "\\{";           break;
        case '}':  t << "\\}";           break;
        case '<':  t << "$<$";           break;
        case '>':  t << "$>$";           break;
6446
        case '|':  t << "$\\vert$";      break;
6447 6448 6449 6450 6451 6452 6453 6454 6455
        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{]}";
6456
                     else
6457 6458 6459 6460
                       t << "]";             
                   break;
        case '-':  t << "-\\/";
                   break;
6461
        case '\\': t << "\\textbackslash{}";
6462
                   break;           
6463
        case '"':  t << "\\char`\\\"{}";
6464 6465 6466
                   break;

        default:   
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6467 6468
                   //if (!insideTabbing && forceBreaks && c!=' ' && *p!=' ')
                   if (!insideTabbing && 
6469
                       ((c>='A' && c<='Z' && pc!=' ' && pc!='\0') || (c==':' && pc!=':') || (pc=='.' && isId(c)))
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6470
                      )
6471
                   {
6472
                     t << "\\+";
6473
                   }
6474
                   t << (char)c;
6475 6476
      }
    }
6477
    pc = c;
6478 6479
  }
}
6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496


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 )
  {
6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516
    // 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;
      }
    }
6517
  }
6518

6519 6520 6521
  return *tag;
}

6522 6523 6524 6525 6526 6527 6528 6529 6530 6531
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;
}

6532

6533 6534 6535 6536
void replaceNamespaceAliases(QCString &scope,int i)
{
  while (i>0)
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6537 6538
    QCString ns = scope.left(i);
    QCString *s = Doxygen::namespaceAliasDict[ns];
6539 6540 6541 6542 6543
    if (s)
    {
      scope=*s+scope.right(scope.length()-i);
      i=s->length();
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6544
    if (i>0 && ns==scope.left(i)) break;
6545 6546
  }
}
6547

6548 6549 6550 6551 6552 6553 6554 6555
QCString stripPath(const char *s)
{
  QCString result=s;
  int i=result.findRev('/');
  if (i!=-1)
  {
    result=result.mid(i+1);
  }
6556 6557 6558 6559 6560
  i=result.findRev('\\');
  if (i!=-1)
  {
    result=result.mid(i+1);
  }
6561 6562
  return result;
}
6563 6564 6565 6566

/** returns \c TRUE iff string \a s contains word \a w */
bool containsWord(const QCString &s,const QCString &word)
{
6567
  static QRegExp wordExp("[a-z_A-Z\\x80-\\xFF]+");
6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578
  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)
{
6579
  static QRegExp wordExp("[a-z_A-Z\\x80-\\xFF]+");
6580 6581 6582 6583 6584
  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
6585
      if (i>0 && isspace((uchar)s.at(i-1))) 
6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596
        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;
}

6597
/** Special version of QCString::stripWhiteSpace() that only strips
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6598 6599 6600 6601 6602 6603
 *  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.
6604
 */
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6605
QCString stripLeadingAndTrailingEmptyLines(const QCString &s,int &docLine)
6606 6607 6608 6609 6610 6611 6612 6613 6614 6615
{
  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
6616
    else if (c=='\n') i++,li=i,docLine++;
6617 6618 6619 6620 6621 6622 6623 6624
    else break;
  }

  // search for trailing empty lines
  int b=l-1,bi=-1;
  p=s.data()+b;
  while (b>=0)
  {
6625
    c=*p; p--;
6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640
    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);
}

6641
#if 0
6642
void stringToSearchIndex(const QCString &docBaseUrl,const QCString &title,
6643
    const QCString &str,bool priority,const QCString &anchor)
6644 6645 6646 6647 6648
{
  static bool searchEngine = Config_getBool("SEARCHENGINE");
  if (searchEngine)
  {
    Doxygen::searchIndex->setCurrentDoc(title,docBaseUrl,anchor);
6649
    static QRegExp wordPattern("[a-z_A-Z\\x80-\\xFF][a-z_A-Z0-9\\x80-\\xFF]*");
6650 6651 6652 6653 6654 6655 6656 6657
    int i,p=0,l;
    while ((i=wordPattern.match(str,p,&l))!=-1)
    {
      Doxygen::searchIndex->addWord(str.mid(i,l),priority);
      p=i+l;
    }
  }
}
6658
#endif
6659

6660 6661 6662 6663 6664 6665 6666
//--------------------------------------------------------------------------

static QDict<int> g_extLookup;

static struct Lang2ExtMap
{
  const char *langName;
6667
  const char *parserName;
6668 6669 6670 6671
  SrcLangExt parserId;
} 
g_lang2extMap[] =
{
6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690
//  language       parser           parser option
  { "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  },
  { "fortranfree", "fortranfree",   SrcLangExt_Fortran  },
  { "fortranfixed", "fortranfixed", SrcLangExt_Fortran  },
  { "vhdl",        "vhdl",          SrcLangExt_VHDL     },
  { "dbusxml",     "dbusxml",       SrcLangExt_XML      },
  { "tcl",         "tcl",           SrcLangExt_Tcl      },
  { "md",          "md",            SrcLangExt_Markdown },
  { 0,             0,              (SrcLangExt)0        }
6691 6692
};

6693
bool updateLanguageMapping(const QCString &extension,const QCString &language)
6694 6695
{
  const Lang2ExtMap *p = g_lang2extMap;
6696
  QCString langName = language.lower();
6697 6698 6699 6700 6701 6702 6703
  while (p->langName)
  {
    if (langName==p->langName) break;
    p++;
  }
  if (!p->langName) return FALSE;

6704
  // found the language
6705
  SrcLangExt parserId = p->parserId;
6706
  QCString extName = extension.lower();
6707 6708
  if (extName.isEmpty()) return FALSE;
  if (extName.at(0)!='.') extName.prepend(".");
6709
  if (g_extLookup.find(extension)!=0) // language was already register for this ext
6710 6711 6712
  {
    g_extLookup.remove(extension);
  }
6713 6714
  //printf("registering extension %s\n",extName.data());
  g_extLookup.insert(extName,new int(parserId));
6715 6716 6717 6718 6719 6720 6721 6722 6723 6724
  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());
  }
6725 6726 6727
  return TRUE;
}

6728 6729 6730
void initDefaultExtensionMapping()
{
  g_extLookup.setAutoDelete(TRUE);
6731
  //                  extension      parser id
6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756
  updateLanguageMapping(".dox",      "c");
  updateLanguageMapping(".txt",      "c");
  updateLanguageMapping(".doc",      "c");
  updateLanguageMapping(".c",        "c");
  updateLanguageMapping(".C",        "c");
  updateLanguageMapping(".cc",       "c");
  updateLanguageMapping(".CC",       "c");
  updateLanguageMapping(".cxx",      "c");
  updateLanguageMapping(".cpp",      "c");
  updateLanguageMapping(".c++",      "c");
  updateLanguageMapping(".ii",       "c");
  updateLanguageMapping(".ixx",      "c");
  updateLanguageMapping(".ipp",      "c");
  updateLanguageMapping(".i++",      "c");
  updateLanguageMapping(".inl",      "c");
  updateLanguageMapping(".h",        "c");
  updateLanguageMapping(".H",        "c");
  updateLanguageMapping(".hh",       "c");
  updateLanguageMapping(".HH",       "c");
  updateLanguageMapping(".hxx",      "c");
  updateLanguageMapping(".hpp",      "c");
  updateLanguageMapping(".h++",      "c");
  updateLanguageMapping(".idl",      "idl");
  updateLanguageMapping(".ddl",      "idl");
  updateLanguageMapping(".odl",      "idl");
6757
  updateLanguageMapping(".java",     "java");
6758
  updateLanguageMapping(".as",       "javascript");
6759 6760 6761
  updateLanguageMapping(".js",       "javascript");
  updateLanguageMapping(".cs",       "csharp");
  updateLanguageMapping(".d",        "d");
6762
  updateLanguageMapping(".php",      "php");
6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780
  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");
6781

Dimitri van Heesch's avatar
Dimitri van Heesch committed
6782
  //updateLanguageMapping(".xml",   "dbusxml");
6783 6784
}

6785 6786 6787 6788 6789
SrcLangExt getLanguageFromFileName(const QCString fileName)
{
  int i = fileName.findRev('.');
  if (i!=-1) // name has an extension
  {
6790
    QCString extStr=fileName.right(fileName.length()-i).lower();
6791 6792
    if (!extStr.isEmpty()) // non-empty extension
    {
6793
      int *pVal=g_extLookup.find(extStr);
6794 6795
      if (pVal) // listed extension
      {
6796
        //printf("getLanguageFromFileName(%s)=%x\n",extStr.data(),*pVal);
6797
        return (SrcLangExt)*pVal; 
6798 6799 6800
      }
    }
  }
6801
  //printf("getLanguageFromFileName(%s) not found!\n",fileName.data());
6802 6803 6804
  return SrcLangExt_Cpp; // not listed => assume C-ish language.
}

6805 6806
//--------------------------------------------------------------------------

6807 6808
MemberDef *getMemberFromSymbol(Definition *scope,FileDef *fileScope, 
                                const char *n)
6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820
{
  if (scope==0 ||
      (scope->definitionType()!=Definition::TypeClass &&
       scope->definitionType()!=Definition::TypeNamespace
      )
     )
  {
    scope=Doxygen::globalScope;
  }

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

6823 6824
  DefinitionIntf *di = Doxygen::symbolMap->find(name);
  if (di==0)
6825
    return 0; // could not find any matching symbols
6826 6827 6828 6829 6830 6831 6832 6833 6834 6835

  // 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);
  }
6836
  //printf("explicitScopePart=%s\n",explicitScopePart.data());
6837

6838 6839
  int minDistance = 10000;
  MemberDef *bestMatch = 0;
6840 6841

  if (di->definitionType()==DefinitionIntf::TypeSymbolList)
6842
  {
6843
    //printf("multiple matches!\n");
6844 6845 6846 6847
    // find the closest closest matching definition
    DefinitionListIterator dli(*(DefinitionList*)di);
    Definition *d;
    for (dli.toFirst();(d=dli.current());++dli)
6848
    {
6849
      if (d->definitionType()==Definition::TypeMember)
6850
      {
6851 6852 6853 6854 6855 6856
        g_visitedNamespaces.clear();
        int distance = isAccessibleFromWithExpScope(scope,fileScope,d,explicitScopePart);
        if (distance!=-1 && distance<minDistance)
        {
          minDistance = distance;
          bestMatch = (MemberDef *)d;
6857
          //printf("new best match %s distance=%d\n",bestMatch->qualifiedName().data(),distance);
6858
        }
6859 6860 6861
      }
    }
  }
6862 6863
  else if (di->definitionType()==Definition::TypeMember)
  {
6864
    //printf("unique match!\n");
6865 6866 6867 6868 6869 6870 6871
    Definition *d = (Definition *)di;
    g_visitedNamespaces.clear();
    int distance = isAccessibleFromWithExpScope(scope,fileScope,d,explicitScopePart);
    if (distance!=-1 && distance<minDistance)
    {
      minDistance = distance;
      bestMatch = (MemberDef *)d;
6872
      //printf("new best match %s distance=%d\n",bestMatch->qualifiedName().data(),distance);
6873 6874
    }
  }
6875 6876 6877 6878 6879 6880 6881
  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);
6882 6883 6884 6885 6886 6887

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

6889 6890 6891 6892 6893 6894
const char *writeUtf8Char(FTextStream &t,const char *s)
{
  char c=*s++;
  t << c;
  if (c<0) // multibyte character
  {
6895 6896 6897 6898 6899
    if (((uchar)c&0xE0)==0xC0)
    {
      t << *s++; // 11xx.xxxx: >=2 byte character
    }
    if (((uchar)c&0xF0)==0xE0)
6900 6901 6902
    {
      t << *s++; // 111x.xxxx: >=3 byte character
    }
6903 6904 6905 6906 6907 6908 6909 6910 6911
    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)
6912
    {
6913
      t << *s++; // 1111.1xxx: 6 byte character
6914 6915 6916 6917
    }
  }
  return s;
}
6918

Dimitri van Heesch's avatar
Dimitri van Heesch committed
6919 6920 6921 6922 6923 6924 6925
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
  {
6926 6927 6928 6929 6930
    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
6931 6932 6933
    {
      bytes++; // 111x.xxxx: >=3 byte character
    }
6934 6935 6936 6937 6938 6939 6940 6941 6942
    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
6943
    {
6944
      bytes++; // 1111.1xxx: 6 byte character
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6945 6946
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962
  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
6963 6964 6965
  return startPos+bytes;
}

6966
QCString parseCommentAsText(const Definition *scope,const MemberDef *md,
6967
    const QCString &doc,const QCString &fileName,int lineNr)
6968
{
6969 6970 6971
  QGString s;
  if (doc.isEmpty()) return s.data();
  FTextStream t(&s);
6972 6973
  DocNode *root = validatingParseDoc(fileName,lineNr,
      (Definition*)scope,(MemberDef*)md,doc,FALSE,FALSE);
6974 6975 6976 6977
  TextDocVisitor *visitor = new TextDocVisitor(t);
  root->accept(visitor);
  delete visitor;
  delete root;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6978
  QCString result = convertCharEntitiesToUTF8(s.data());
6979
  int i=0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6980 6981 6982 6983
  int charCnt=0;
  int l=result.length();
  bool addEllipsis=FALSE;
  while ((i=nextUtf8CharPosition(result,l,i))<l)
6984
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6985 6986 6987 6988 6989 6990
    charCnt++;
    if (charCnt>=80) break;
  }
  if (charCnt>=80) // try to truncate the string
  {
    while ((i=nextUtf8CharPosition(result,l,i))<l && charCnt<100)
6991
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6992
      charCnt++;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6993
      if (result.at(i)>=0 && isspace(result.at(i)))
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6994 6995 6996 6997 6998 6999
      {
        addEllipsis=TRUE;
      }
      else if (result.at(i)==',' || 
               result.at(i)=='.' || 
               result.at(i)=='?')
7000 7001 7002 7003 7004
      {
        break;
      }
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7005
  if (addEllipsis || charCnt==100) result=result.left(i)+"...";
7006 7007 7008
  return result.data();
}

7009 7010 7011 7012
//--------------------------------------------------------------------------------------

static QDict<void> aliasesProcessed;

7013
static QCString expandAliasRec(const QCString s,bool allowRecursion=FALSE);
7014 7015 7016 7017 7018 7019 7020 7021

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
};
7022

7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050
/** 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;
}

7051 7052 7053 7054
/** 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.
 */
7055 7056
static QCString replaceAliasArguments(const QCString &aliasValue,const QCString &argList)
{
7057 7058 7059
  //printf("----- replaceAliasArguments(val=[%s],args=[%s])\n",aliasValue.data(),argList.data());

  // first make a list of arguments from the comma separated argument list
7060
  QList<QCString> args;
7061 7062 7063
  args.setAutoDelete(TRUE);
  int i,l=(int)argList.length();
  int s=0;
7064 7065
  for (i=0;i<l;i++)
  {
7066 7067
    char c = argList.at(i);
    if (c==',' && (i==0 || argList.at(i-1)!='\\')) 
7068 7069 7070 7071
    {
      args.append(new QCString(argList.mid(s,i-s)));
      s=i+1; // start of next argument
    }
7072 7073 7074 7075 7076
    else if (c=='@' || c=='\\')
    {
      // check if this is the start of another aliased command (see bug704172)
      i+=findEndOfCommand(argList.data()+i+1);
    }
7077
  }
7078 7079 7080 7081 7082 7083 7084 7085 7086 7087
  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++)
7088
  {
7089 7090 7091 7092 7093 7094 7095 7096 7097 7098
    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
7099
    {
7100 7101 7102 7103 7104 7105 7106 7107 7108 7109
      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;
7110 7111
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123
  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)));
  }
7124 7125 7126 7127 7128

  // 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++)
7129
  {
7130 7131 7132 7133 7134
    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
    {
7135
      result+=expandAliasRec(*args.at(m->number-1),TRUE);
7136 7137 7138 7139
      //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
7140
  }
7141 7142
  result+=aliasValue.right(l-p); // append remainder
  //printf("string after replacement of markers: '%s'\n",result.data());
7143

7144 7145 7146 7147 7148
  // expand the result again
  result = substitute(result,"\\{","{");
  result = substitute(result,"\\}","}");
  result = expandAliasRec(substitute(result,"\\,",","));

7149 7150 7151
  return result;
}

7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173
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();
}

7174
static QCString expandAliasRec(const QCString s,bool allowRecursion)
7175 7176 7177 7178 7179 7180 7181 7182 7183 7184
{
  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
7185 7186 7187 7188
    int argsLen = args.length();
    QCString cmd = value.mid(i+1,l-1);
    QCString cmdNoArgs = cmd;
    int numArgs=0;
7189 7190
    if (hasArgs)
    {
7191 7192
      numArgs = countAliasArguments(args);
      cmd += QCString().sprintf("{%d}",numArgs);  // alias name + {n}
7193 7194
    }
    QCString *aliasText=Doxygen::aliasDict.find(cmd);
7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206
    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>");
7207
    if ((allowRecursion || aliasesProcessed.find(cmd)==0) && aliasText) // expand the alias
7208 7209
    {
      //printf("is an alias!\n");
7210
      if (!allowRecursion) aliasesProcessed.insert(cmd,(void *)0x8);
7211 7212 7213 7214 7215 7216 7217 7218
      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);
7219
      if (!allowRecursion) aliasesProcessed.remove(cmd);
7220
      p=i+l;
7221
      if (hasArgs) p+=argsLen+2;
7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235
    }
    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;
}

7236

7237 7238 7239 7240 7241 7242 7243
int countAliasArguments(const QCString argList)
{
  int count=1;
  int l = argList.length();
  int i;
  for (i=0;i<l;i++) 
  {
7244 7245 7246 7247 7248 7249 7250
    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);
    }
7251
  }
7252
  //printf("countAliasArguments=%d\n",count);
7253 7254 7255 7256 7257 7258 7259
  return count;
}

QCString extractAliasArgs(const QCString &args,int pos)
{
  int i;
  int bc=0;
7260
  char prevChar=0;
7261 7262 7263 7264
  if (args.at(pos)=='{') // alias has argument
  {
    for (i=pos;i<(int)args.length();i++)
    {
7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275
      if (prevChar!='\\')
      {
        if (args.at(i)=='{') bc++;
        if (args.at(i)=='}') bc--;
        prevChar=args.at(i);
      }
      else
      {
        prevChar=0;
      }

7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308
      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;
}

7309 7310 7311
void writeTypeConstraints(OutputList &ol,Definition *d,ArgumentList *al)
{
  if (al==0) return;
7312
  ol.startConstraintList(theTranslator->trTypeConstraints()); 
7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323
  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();
7324
    ol.generateDoc(d->docFile(),d->docLine(),d,0,a->docs,TRUE,FALSE);
7325 7326 7327 7328
    ol.endConstraintDocs();
  }
  ol.endConstraintList();
}
7329

7330
//----------------------------------------------------------------------------
7331

7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358
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
}

7359
static int transcodeCharacterBuffer(const char *fileName,BufStr &srcBuf,int size,
7360 7361 7362 7363 7364 7365 7366
           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)) 
  {
7367
    err("unsupported character conversion: '%s'->'%s': %s\n"
7368 7369 7370 7371 7372 7373 7374 7375
        "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;
7376
  char *srcPtr = srcBuf.data();
7377 7378 7379 7380
  char *dstPtr = tmpBuf.data();
  uint newSize=0;
  if (!portable_iconv(cd, &srcPtr, &iLeft, &dstPtr, &oLeft))
  {
7381
    newSize = tmpBufSize-(int)oLeft;
7382 7383 7384 7385 7386 7387
    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
  {
7388
    err("%s: failed to translate characters from %s to %s: check INPUT_ENCODING\n",
7389
        fileName,inputEncoding,outputEncoding);
7390 7391 7392 7393 7394 7395 7396
    exit(1);
  }
  portable_iconv_close(cd);
  return newSize;
}

//! read a file name \a fileName and optionally filter and transcode it
7397
bool readInputFile(const char *fileName,BufStr &inBuf,bool filter,bool isSourceCode)
7398 7399 7400 7401 7402 7403 7404 7405
{
  // try to open file
  int size=0;
  //uint oldPos = dest.curPos();
  //printf(".......oldPos=%d\n",oldPos);

  QFileInfo fi(fileName);
  if (!fi.exists()) return FALSE;
7406 7407
  QCString filterName = getFileFilter(fileName,isSourceCode);
  if (filterName.isEmpty() || !filter)
7408 7409 7410 7411
  {
    QFile f(fileName);
    if (!f.open(IO_ReadOnly))
    {
7412
      err("could not open file %s\n",fileName);
7413 7414 7415 7416 7417 7418 7419
      return FALSE;
    }
    size=fi.size();
    // read the file
    inBuf.skip(size);
    if (f.readBlock(inBuf.data()/*+oldPos*/,size)!=size)
    {
7420
      err("problems while reading file %s\n",fileName);
7421 7422 7423 7424 7425 7426 7427 7428 7429 7430
      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)
    {
7431
      err("could not execute filter %s\n",filterName.data());
7432 7433 7434 7435 7436
      return FALSE;
    }
    const int bufSize=1024;
    char buf[bufSize];
    int numRead;
7437
    while ((numRead=(int)fread(buf,1,bufSize,f))>0)
7438 7439 7440 7441 7442
    {
      //printf(">>>>>>>>Reading %d bytes\n",numRead);
      inBuf.addArray(buf,numRead),size+=numRead;
    }
    portable_pclose(f);
7443 7444 7445
    inBuf.at(inBuf.curPos()) ='\0';
    Debug::print(Debug::FilterOutput, 0, "Filter output\n");
    Debug::print(Debug::FilterOutput,0,"-------------\n%s\n-------------\n",inBuf.data());
7446 7447
  }

7448
  int start=0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7449
  if (size>=2 &&
7450 7451 7452 7453 7454
      ((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
  {
7455
    transcodeCharacterBuffer(fileName,inBuf,inBuf.curPos(),
7456 7457
        "UCS-2","UTF-8");
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7458
  else if (size>=3 &&
7459 7460 7461
           (uchar)inBuf.at(0)==0xEF &&
           (uchar)inBuf.at(1)==0xBB &&
           (uchar)inBuf.at(2)==0xBF
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7462
     ) // UTF-8 encoded file
7463 7464 7465
  {
    inBuf.dropFromStart(3); // remove UTF-8 BOM: no translation needed
  }
7466 7467 7468
  else // transcode according to the INPUT_ENCODING setting
  {
    // do character transcoding if needed.
7469
    transcodeCharacterBuffer(fileName,inBuf,inBuf.curPos(),
7470 7471 7472
        Config_getString("INPUT_ENCODING"),"UTF-8");
  }

7473
  //inBuf.addChar('\n'); /* to prevent problems under Windows ? */
7474 7475

  // and translate CR's
7476 7477
  size=inBuf.curPos()-start;
  int newSize=filterCRLF(inBuf.data()+start,size);
7478 7479 7480 7481 7482 7483
  //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());
  }
7484
  inBuf.addChar(0);
7485 7486 7487
  return TRUE;
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502
// 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;
}
7503

7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514
//----------------------------------------------------------------------------
// 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;
7515 7516 7517 7518 7519

    QCString fn = fi.fileName().data();
    QCString fp = fi.filePath().data();
    QCString afp= fi.absFilePath().data();

7520 7521
    for (it.toFirst();(pattern=it.current());++it)
    {
7522
      if (!pattern.isEmpty())
7523 7524 7525 7526 7527 7528 7529 7530 7531
      {
        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
7532 7533 7534
        found = re.match(fn)!=-1 ||
                re.match(fp)!=-1 ||
                re.match(afp)!=-1;
7535
        if (found) break;
7536 7537 7538 7539 7540 7541 7542 7543
        //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
7544
#if 0 // move to HtmlGenerator::writeSummaryLink
7545
void writeSummaryLink(OutputList &ol,const char *label,const char *title,
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7546
                      bool &first,const char *file)
7547 7548 7549 7550 7551 7552 7553 7554 7555 7556
{
  if (first)
  {
    ol.writeString("  <div class=\"summary\">\n");
    first=FALSE;
  }
  else
  {
    ol.writeString(" &#124;\n");
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567
  if (file)
  {
    ol.writeString("<a href=\"");
    ol.writeString(file);
    ol.writeString(Doxygen::htmlFileExtension);
  }
  else
  {
    ol.writeString("<a href=\"#");
    ol.writeString(label);
  }
7568 7569 7570 7571
  ol.writeString("\">");
  ol.writeString(title);
  ol.writeString("</a>");
}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7572
#endif
7573

7574 7575 7576 7577 7578
QCString externalLinkTarget()
{
  static bool extLinksInWindow = Config_getBool("EXT_LINKS_IN_WINDOW");
  if (extLinksInWindow) return "target=\"_blank\" "; else return "";
}
7579

7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594
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
7595
      if (l>0 && result.at(l-1)!='/') result+='/';
7596 7597 7598 7599 7600 7601 7602 7603 7604
      if (!href) result.append("\" ");
    }
  }
  else
  {
    result = relPath;
  }
  return result;
}
7605

Dimitri van Heesch's avatar
Dimitri van Heesch committed
7606 7607 7608
/** Writes the intensity only bitmap representated by \a data as an image to 
 *  directory \a dir using the colors defined by HTML_COLORSTYLE_*.
 */
7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628
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);
    }
7629
    Doxygen::indexList->addImageFile(data->name);
7630 7631 7632 7633
    data++;
  }
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
7634 7635 7636 7637 7638
/** 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.
 */
7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682
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
7683 7684 7685
/** Copies the contents of file with name \a src to the newly created 
 *  file with name \a dest. Returns TRUE if successful.
 */
7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702
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
    {
7703
      err("could not write to file %s\n",dest.data());
7704 7705 7706 7707 7708
      return FALSE;
    }
  }
  else
  {
7709
    err("could not open user specified file %s\n",src.data());
7710 7711 7712 7713 7714
    return FALSE;
  }
  return TRUE;
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737
/** 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;
7738
  int lp=i;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7739 7740 7741 7742 7743 7744 7745 7746 7747 7748
  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;
7749
      lp=i;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7750 7751
    }
  }
7752 7753 7754 7755
  if (l2==-1) // marker at last line without newline (see bug706874)
  {
    l2=lp;
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7756
  //printf("text=[%s]\n",text.mid(l1,l2-l1).data());
7757
  return l2>l1 ? text.mid(l1,l2-l1) : QCString();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7758 7759 7760 7761 7762 7763 7764
}

/** Returns a string representation of \a lang. */
QCString langToString(SrcLangExt lang)
{
  switch(lang)
  {
7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779
    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
7780 7781 7782 7783 7784
  }
  return "Unknown";
}

/** Returns the scope separator to use given the programming language \a lang */
7785
QCString getLanguageSpecificSeparator(SrcLangExt lang,bool classScope)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7786
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7787
  if (lang==SrcLangExt_Java || lang==SrcLangExt_CSharp || lang==SrcLangExt_VHDL || lang==SrcLangExt_Python)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7788 7789 7790
  {
    return ".";
  }
7791
  else if (lang==SrcLangExt_PHP && !classScope)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7792 7793 7794 7795 7796 7797 7798 7799 7800
  {
    return "\\";
  }
  else
  {
    return "::";
  }
}

7801 7802 7803 7804 7805 7806 7807 7808
/** 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:" && 
7809
      url.left(4)!="ftp:"  && url.left(5)!="file:")
7810 7811 7812 7813 7814 7815
  {
    result.prepend(relPath);
  }
  return result;
}

7816
//---------------------------------------------------------------------------
7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827

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
7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908
//---------------------------------------------------------------------------

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
         );
}

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
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);
    }
  }
}

7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 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 8019 8020
//--------------------------------------------------------------------------------------

/*! @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;
}

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

8021 8022 8023 8024 8025 8026 8027 8028
bool namespaceHasVisibleChild(NamespaceDef *nd,bool includeClasses)
{
  if (nd->getNamespaceSDict())
  {
    NamespaceSDict::Iterator cnli(*nd->getNamespaceSDict());
    NamespaceDef *cnd;
    for (cnli.toFirst();(cnd=cnli.current());++cnli)
    {
8029
      if (cnd->isLinkableInProject() && cnd->localName().find('@')==-1)
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
      {
        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();
}

8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084
//----------------------------------------------------------------------------

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();
}

8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 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 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 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
//-----------------------------------------------------------

/** 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);
}
8275

8276 8277 8278 8279 8280 8281 8282 8283
bool mainPageHasTitle()
{
  if (Doxygen::mainPage==0) return FALSE;
  if (Doxygen::mainPage->title().isEmpty()) return FALSE;
  if (Doxygen::mainPage->title().lower()=="notitle") return FALSE;
  return TRUE;
}