home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / dmake40.zip / expand.c < prev    next >
C/C++ Source or Header  |  1994-10-23  |  30KB  |  1,050 lines

  1. /* RCS      -- $Header: /u5/dvadura/src/public/dmake/src/RCS/expand.c,v 1.1 1994/10/06 17:41:25 dvadura Exp $
  2. -- SYNOPSIS -- macro expansion code.
  3. -- 
  4. -- DESCRIPTION
  5. --
  6. --    This routine handles all the necessary junk that deals with macro
  7. --    expansion.  It understands the following syntax.  If a macro is
  8. --    not defined it expands to NULL, and {} are synonyms for ().
  9. --
  10. --        $$      - expands to $
  11. --        {{      - expands to {
  12. --            }}      - expands to }
  13. --        $A      - expands to whatever the macro A is defined as
  14. --        $(AA)   - expands to whatever the macro AA is defined as
  15. --        $($(A)) - represents macro indirection
  16. --        <+...+> - get mapped to $(mktmp ...)
  17. --    
  18. --        following macro is recognized
  19. --        
  20. --                string1{ token_list }string2
  21. --                
  22. --        and expands to string1 prepended to each element of token_list and
  23. --        string2 appended to each of the resulting tokens from the first
  24. --        operation.  If string2 is of the form above then the result is
  25. --        the cross product of the specified (possibly modified) token_lists.
  26. --        
  27. --        The folowing macro modifiers are defined and expanded:
  28. --        
  29. --               $(macro:modifier_list:modifier_list:...)
  30. --               
  31. --        where modifier_list a combination of:
  32. --        
  33. --               D or d      - Directory portion of token including separator
  34. --               F or f      - File portion of token including suffix
  35. --               B or b      - basename portion of token not including suffix
  36. --         T or t      - for tokenization
  37. --         E or e      - Suffix portion of name
  38. --         L or l         - translate to lower case
  39. --             U or u      - translate to upper case
  40. --         I or i         - return inferred names
  41. --
  42. --      or a single
  43. --               S or s      - pattern substitution (simple)
  44. --               
  45. --        NOTE:  Modifiers are applied once the macro value has been found.
  46. --               Thus the construct $($(test):s/joe/mary/) is defined and
  47. --               modifies the value of $($(test))
  48. --
  49. --           Also the construct $(m:d:f) is not the same as $(m:df)
  50. --           the first applies d to the value of $(m) and then
  51. --           applies f to the value of that whereas the second form
  52. --           applies df to the value of $(m).
  53. --
  54. -- AUTHOR
  55. --      Dennis Vadura, dvadura@watdragon.uwaterloo.ca
  56. --      CS DEPT, University of Waterloo, Waterloo, Ont., Canada
  57. --
  58. -- COPYRIGHT
  59. --      Copyright (c) 1992,1994 by Dennis Vadura.  All rights reserved.
  60. -- 
  61. --      This program is free software; you can redistribute it and/or
  62. --      modify it under the terms of the GNU General Public License
  63. --      (version 1), as published by the Free Software Foundation, and
  64. --      found in the file 'LICENSE' included with this distribution.
  65. -- 
  66. --      This program is distributed in the hope that it will be useful,
  67. --      but WITHOUT ANY WARRANTY; without even the implied warrant of
  68. --      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  69. --      GNU General Public License for more details.
  70. -- 
  71. --      You should have received a copy of the GNU General Public License
  72. --      along with this program;  if not, write to the Free Software
  73. --      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  74. --
  75. -- LOG
  76. --     $Log: expand.c,v $
  77.  * Revision 1.1  1994/10/06  17:41:25  dvadura
  78.  * dmake Release Version 4.0, Initial revision
  79.  *
  80. */
  81.  
  82. #include "extern.h"
  83.  
  84. /* Microsoft BRAINDAMAGE ALERT!!!!
  85.  * This #ifdef is here only to satisfy stupid bugs in MSC5.0 and MSC5.1
  86.  * it isn't needed for anything else.  It turns loop optimization off. */
  87. #if defined(_MSC_VER)
  88. #include "optoff.h"
  89. #endif
  90.  
  91. static    char*    _scan_macro ANSI((char*, char**, int));
  92. static    char*    _scan_brace ANSI((char*, char**, int*));
  93. static    char*    _cross_prod ANSI((char*, char*));
  94. static  char*   _scan_ballanced_parens ANSI((char*, char));
  95.  
  96.  
  97. PUBLIC char *
  98. Expand( src )/*
  99. ===============
  100.       This is the driver routine for the expansion, it identifies non-white
  101.       space tokens and gets the ScanToken routine to figure out if they should
  102.       be treated in a special way. */
  103.  
  104. char *src;                    /* pointer to source string  */
  105. {
  106.    char  *tmp;              /* pointer to temporary str  */
  107.    char  *res;                /* pointer to result string  */
  108.    char  *start;              /* pointer to start of token */
  109.    
  110.    DB_ENTER( "Expand" );
  111.    DB_PRINT( "exp", ("Expanding [%s]", src) );
  112.  
  113.    res = DmStrDup( "" );
  114.    if( src == NIL(char) ) DB_RETURN( res );
  115.  
  116.    while( *src ) {
  117.       char *ks, *ke;
  118.  
  119.       /* Here we find the next non white space token in the string
  120.        * and find it's end, with respect to non-significant white space. */
  121.       
  122.       start = DmStrSpn( src, " \t\n" );
  123.       res   = DmStrJoin( res, src, start-src, TRUE );
  124.       if( !(*start) ) break;
  125.  
  126.       /* START <+...+> KLUDGE */
  127.       if(   (ks=DmStrStr(start,"<+")) != NIL(char)
  128.          && (ke=DmStrStr(ks,"+>")) != NIL(char) ){
  129.      char *t1, *t2;
  130.  
  131.      res = DmStrJoin( res, t2=Expand(t1=DmSubStr(start,ks)), -1, TRUE);
  132.      FREE(t1); FREE(t2);
  133.  
  134.      t1 = DmSubStr(ks+2, ke+1); t1[ke-ks-2] = ')';
  135.      t2 = DmStrJoin( "$(mktmp ", t1, -1,FALSE);
  136.      FREE(t1);
  137.      res = DmStrJoin( res, t2=Expand(t2), -1, TRUE);
  138.      FREE(t2);
  139.      src = ke+2;
  140.       }
  141.       /* END <+...+> KLUDGE */
  142.       else {
  143.      res   = DmStrJoin( res, tmp = ScanToken(start,&src,TRUE), -1, TRUE );
  144.      FREE( tmp );
  145.       }
  146.    }
  147.    
  148.    DB_PRINT( "exp", ("Returning [%s]", res) );
  149.    DB_RETURN( res );
  150. }
  151.  
  152.  
  153. PUBLIC char *
  154. Apply_edit( src, pat, subst, fr, anchor )/*
  155. ===========================================
  156.    Take the src string and apply the pattern substitution.  ie. look for
  157.    occurrences of pat in src and replace each occurrence with subst.  This is
  158.    NOT a regular expressions pattern substitution, it's just not worth it.
  159.    
  160.    if anchor == TRUE then the src pattern match must be at the end of a token.
  161.    ie. this is for SYSV compatibility and is only used for substitutions of
  162.    the caused by $(macro:pat=sub).  So if src = "fre.o.k june.o" then
  163.    $(src:.o=.a) results in "fre.o.k june.a", and $(src:s/.o/.a) results in
  164.    "fre.a.k june.a" */
  165.  
  166. char *src;            /* the source string */
  167. char *pat;            /* pattern to find   */
  168. char *subst;            /* substitute string */
  169. int   fr;            /* if TRUE free src  */
  170. int   anchor;            /* if TRUE anchor    */
  171. {
  172.    char *res;
  173.    char *p;
  174.    char *s;
  175.    int   l;
  176.  
  177.    DB_ENTER( "Apply_edit" );
  178.    
  179.    if( !*pat ) DB_RETURN( src );        /* do nothing if pat is NULL */
  180.  
  181.    DB_PRINT( "mod", ("Source str:  [%s]", src) );
  182.    DB_PRINT( "mod", ("Replacing [%s], with [%s]", pat, subst) );
  183.  
  184.    s   = src;
  185.    l   = strlen( pat );
  186.    if( (p = DmStrStr( s, pat )) != NIL(char) ) {
  187.       res = DmStrDup( "" );
  188.       do {
  189.      if( anchor )
  190.         if( !*(p+l) || (strchr(" \t", *(p+l)) != NIL(char)) )
  191.            res = DmStrJoin( DmStrJoin(res,s,p-s,TRUE), subst, -1, TRUE );
  192.         else
  193.            res = DmStrJoin( res, s, p+l-s, TRUE );
  194.      else
  195.         res = DmStrJoin( DmStrJoin(res,s,p-s,TRUE), subst, -1, TRUE );
  196.  
  197.      s   = p + l;
  198.       }
  199.       while( (p = DmStrStr( s, pat )) != NIL(char) );
  200.  
  201.       res = DmStrJoin( res, s, -1, TRUE );
  202.       if( fr ) FREE( src );
  203.    }
  204.    else
  205.       res = src;
  206.  
  207.  
  208.    DB_PRINT( "mod", ("Result [%s]", res) );
  209.    DB_RETURN( res );
  210. }
  211.  
  212.  
  213. PUBLIC void
  214. Map_esc( tok )/*
  215. ================
  216.    Map an escape sequence and replace it by it's corresponding character
  217.    value.  It is assumed that tok points at the initial \, the esc
  218.    sequence in the original string is replaced and the value of tok
  219.    is not modified. */
  220. char *tok;
  221. {
  222.    if( strchr( "\"\\vantbrf01234567", tok[1] ) ) {
  223.       switch( tok[1] ) {
  224.      case 'a' : *tok = 0x07; break;
  225.      case 'b' : *tok = '\b'; break;
  226.      case 'f' : *tok = '\f'; break;
  227.      case 'n' : *tok = '\n'; break;
  228.      case 'r' : *tok = '\r'; break;
  229.      case 't' : *tok = '\t'; break;
  230.      case 'v' : *tok = 0x0b; break;
  231.      case '\\': *tok = '\\'; break;
  232.      case '\"': *tok = '\"'; break;
  233.  
  234.      default: {
  235.         register int i = 0;
  236.         register int j = 0;
  237.         for( ; i<2 && isdigit(tok[2]); i++ ) {
  238.            j = (j << 3) + (tok[1] - '0');
  239.            strcpy( tok+1, tok+2 );
  240.         }
  241.         j = (j << 3) + (tok[1] - '0');
  242.         *tok = j;
  243.      }
  244.       }
  245.       strcpy( tok+1, tok+2 );
  246.    }
  247. }
  248.  
  249.  
  250. PUBLIC char*
  251. Apply_modifiers( mod, src )/*
  252. =============================
  253.    This routine applies the appropriate modifiers to the string src
  254.    and returns the proper result string */
  255.  
  256. int  mod;
  257. char *src;
  258. {
  259.    char       *s;
  260.    char    *e;
  261.    TKSTR   str;
  262.  
  263.    DB_ENTER( "Apply_modifiers" );
  264.  
  265.    if ( mod & INFNAME_FLAG ) {
  266.       SET_TOKEN( &str, src );
  267.       e = NIL(char);
  268.  
  269.       while( *(s = Get_token( &str, "", FALSE )) != '\0' ) {
  270.      HASHPTR hp;
  271.  
  272.      if ( (hp = Get_name(s, Defs, FALSE)) != NIL(HASH) 
  273.        && hp->CP_OWNR
  274.        && hp->CP_OWNR->ce_fname
  275.      ) {
  276.         e = DmStrApp(e,hp->CP_OWNR->ce_fname);
  277.      }
  278.      else
  279.         e = DmStrApp(e,s);
  280.       }
  281.  
  282.       FREE(src);
  283.       src = e;
  284.       mod &= ~INFNAME_FLAG;
  285.    }
  286.  
  287.    if(mod & (TOLOWER_FLAG|TOUPPER_FLAG) ) {
  288.       int lower;
  289.       lower = mod & TOLOWER_FLAG;
  290.  
  291.       for (s=src; *s; s++) 
  292.      if ( isalpha(*s) )
  293.         *s = ((lower) ? tolower(*s) : toupper(*s));
  294.  
  295.       mod &= ~(TOLOWER_FLAG|TOUPPER_FLAG);
  296.    }
  297.  
  298.    if( !mod || mod == (SUFFIX_FLAG | DIRECTORY_FLAG | FILE_FLAG) )
  299.       DB_RETURN( src );
  300.  
  301.    SET_TOKEN( &str, src );
  302.    DB_PRINT( "mod", ("Source string [%s]", src) );
  303.  
  304.    while( *(s = Get_token( &str, "", FALSE )) != '\0' ) {
  305.       /* search for the directory portion of the filename.  If the
  306.        * DIRECTORY_FLAG is set, then we want to keep the directory portion
  307.        * othewise throw it away and blank out to the end of the token */
  308.  
  309.       if( (e = Basename(s)) != s)
  310.      if( !(mod & DIRECTORY_FLAG) ) {
  311.         strcpy(s, e);
  312.         e = s+(str.tk_str-e);
  313.         for(; e != str.tk_str; e++)
  314.                *e = ' ';
  315.      }
  316.      else
  317.         s = e;
  318.  
  319.       /* search for the suffix, if there is none, treat it as a NULL suffix.
  320.        * if no file name treat it as a NULL file name.  same copy op as
  321.        * for directory case above */
  322.  
  323.       e = strrchr( s, '.' );            /* NULL suffix if e=0 */
  324.       if( e == NIL(char) ) e = s+strlen(s);
  325.  
  326.       if( !(mod & FILE_FLAG) ) {
  327.      strcpy( s, e );
  328.      e = s+(str.tk_str-e);
  329.      for( ; e != str.tk_str; e++ ) *e = ' ';
  330.       }
  331.       else
  332.      s = e;
  333.  
  334.       /* The last and final part.  This is the suffix case, if we don't want
  335.        * it then just erase to the end of the token. */
  336.  
  337.       if( s != NIL(char) )
  338.      if( !(mod & SUFFIX_FLAG) )
  339.         for( ; s != str.tk_str; s++ ) *s = ' ';
  340.    }
  341.  
  342.    /* delete the extra white space, it looks ugly */
  343.    for( s = src, e = NIL(char); *s; s++ )
  344.       if( *s == ' ' || *s == '\t' || *s == '\n' ) {
  345.      if( e == NIL(char) )
  346.         e = s;
  347.       }
  348.       else {
  349.      if( e != NIL(char) ) {
  350.         if( e+1 < s ) {
  351.            strcpy( e+1, s );
  352.            s = e+1;
  353.            *e = ' ';
  354.         }
  355.         e = NIL(char);
  356.      }
  357.       }
  358.  
  359.    if( e != NIL(char) )
  360.       if( e < s )
  361.      strcpy( e, s );
  362.  
  363.    DB_PRINT( "mod", ("Result string [%s]", src) );
  364.    DB_RETURN( src );
  365. }
  366.  
  367.  
  368. PUBLIC char*
  369. Tokenize( src, separator, op, mapesc )/*
  370. ========================================
  371.     Tokenize the input of src and join each token found together with
  372.     the next token separated by the separator string.
  373.  
  374.     When doing the tokenization, <sp>, <tab>, <nl>, and \<nl> all
  375.     constitute white space. */
  376.  
  377. char *src;
  378. char *separator;
  379. char op;
  380. int  mapesc;
  381. {
  382.    TKSTR    tokens;
  383.    char        *tok;
  384.    char        *res;
  385.    int        first = (op == 't' || op == 'T');
  386.  
  387.    DB_ENTER( "Tokenize" );
  388.  
  389.    /* map the escape codes in the separator string first */
  390.    if ( mapesc )
  391.       for(tok=separator; (tok = strchr(tok,ESCAPE_CHAR)) != NIL(char); tok++)
  392.      Map_esc( tok );
  393.  
  394.    DB_PRINT( "exp", ("Separator [%s]", separator) );
  395.  
  396.    /* By default we return an empty string */
  397.    res = DmStrDup( "" );
  398.  
  399.    /* Build the token list */
  400.    SET_TOKEN( &tokens, src );
  401.    while( *(tok = Get_token( &tokens, "", FALSE )) != '\0' ) {
  402.       char *x;
  403.  
  404.       if( first ) {
  405.      FREE( res );
  406.      res   = DmStrDup( tok );
  407.      first = FALSE;
  408.       }
  409.       else if (op == '^') {
  410.      res = DmStrAdd(res, DmStrJoin(separator, tok, -1, FALSE), TRUE);
  411.       }
  412.       else if (op == '+') {
  413.      res = DmStrAdd(res, DmStrJoin(tok, separator, -1, FALSE), TRUE);
  414.       }
  415.       else {
  416.      res = DmStrJoin(res, x =DmStrJoin(separator, tok, -1, FALSE),
  417.             -1, TRUE);
  418.      FREE( x );
  419.       }
  420.  
  421.       DB_PRINT( "exp", ("Tokenizing [%s] --> [%s]", tok, res) );
  422.    }
  423.  
  424.    FREE( src );
  425.    DB_RETURN( res );
  426. }
  427.  
  428.  
  429. static char*
  430. _scan_ballanced_parens(p, delim)
  431. char *p;
  432. char delim;
  433. {
  434.    int pcount = 0;
  435.    int bcount = 0;
  436.  
  437.    if ( p ) {
  438.       do {
  439.      if (delim)
  440.         if( !(bcount || pcount) && *p == delim) {
  441.            return(p);
  442.         }
  443.  
  444.      if ( *p == '(' ) pcount++;
  445.      else if ( *p == '{' ) bcount++;
  446.      else if ( *p == ')' && pcount ) pcount--;
  447.      else if ( *p == '}' && bcount ) bcount--;
  448.  
  449.      p++;
  450.       }
  451.       while (*p && (pcount || bcount || delim));
  452.    }
  453.  
  454.    return(p);
  455. }
  456.  
  457.  
  458. PUBLIC char*
  459. ScanToken( s, ps, doexpand )/*
  460. ==============================
  461.       This routine scans the token characters one at a time and identifies
  462.       macros starting with $( and ${ and calls _scan_macro to expand their
  463.       value.   the string1{ token_list }string2 expansion is also handled.
  464.       In this case a temporary result is maintained so that we can take it's
  465.       cross product with any other token_lists that may possibly appear. */
  466.       
  467. char *s;        /* pointer to start of src string */
  468. char **ps;        /* pointer to start pointer      */
  469. int  doexpand;
  470. {
  471.    char *res;                 /* pointer to result          */
  472.    char *start;               /* pointer to start of prefix */
  473.    int  crossproduct = 0;     /* if 1 then computing X-prod */
  474.  
  475.    start = s;
  476.    res   = DmStrDup( "" );
  477.    while( 1 ) {
  478.       switch( *s ) {
  479.          /* Termination, We halt at seeing a space or a tab or end of string.
  480.           * We return the value of the result with any new macro's we scanned
  481.           * or if we were computing cross_products then we return the new
  482.           * cross_product.
  483.           * NOTE:  Once we start computing cross products it is impossible to
  484.           *        stop.  ie. the semantics are such that once a {} pair is
  485.           *        seen we compute cross products until termination. */
  486.  
  487.          case ' ':
  488.          case '\t':
  489.      case '\n':
  490.          case '\0': 
  491.      {
  492.         char *tmp;
  493.  
  494.         *ps = s;
  495.         if( !crossproduct )
  496.            tmp = DmStrJoin( res, start, (s-start), TRUE );
  497.         else
  498.         {
  499.            tmp = DmSubStr( start, s );
  500.            tmp = _cross_prod( res, tmp );
  501.         }
  502.         return( tmp );
  503.      }
  504.          
  505.          case '$':
  506.          case '{':
  507.      {
  508.         /* Handle if it's a macro or if it's a {} construct.
  509.          * The results of a macro expansion are handled differently based
  510.          * on whether we have seen a {} beforehand. */
  511.         
  512.         char *tmp;
  513.         tmp = DmSubStr( start, s );          /* save the prefix */
  514.  
  515.         if( *s == '$' ) {
  516.            start = _scan_macro( s+1, &s, doexpand );
  517.  
  518.            if( crossproduct ) {
  519.           res = _cross_prod( res, DmStrJoin( tmp, start, -1, TRUE ) );
  520.            }
  521.            else {
  522.           res = DmStrJoin(res,tmp=DmStrJoin(tmp,start,-1,TRUE),-1,TRUE);
  523.           FREE( tmp );
  524.            }
  525.            FREE( start );
  526.         }
  527.         else if( strchr("{ \t",s[1]) == NIL(char) ){
  528.            int ok;
  529.            start = _scan_brace( s+1, &s, &ok );
  530.           
  531.            if( ok ) {
  532.           if ( crossproduct ) {
  533.              res = _cross_prod(res,_cross_prod(tmp,start));
  534.           }
  535.           else {
  536.              char *freeres;
  537.              res = Tokenize(start,
  538.                     freeres=DmStrJoin(res,tmp,-1,TRUE),
  539.                     '^', FALSE);
  540.              FREE(freeres);
  541.              FREE(tmp);
  542.           }
  543.           crossproduct = TRUE;
  544.            }
  545.            else {
  546.           res =DmStrJoin(res,tmp=DmStrJoin(tmp,start,-1,TRUE),-1,TRUE);
  547.           FREE( start );
  548.           FREE( tmp   );
  549.            }
  550.         }
  551.         else {    /* handle the {{ case */
  552.            res = DmStrJoin( res, start, (s-start+1), TRUE );
  553.            s  += (s[1]=='{')?2:1;
  554.            FREE( tmp );
  555.         }
  556.  
  557.         start = s;
  558.      }
  559.      break;
  560.  
  561.      case '}':
  562.         if( s[1] != '}' ) {
  563.            /* error malformed macro expansion */
  564.            s++;
  565.         }
  566.         else {    /* handle the }} case */
  567.            res = DmStrJoin( res, start, (s-start+1), TRUE );
  568.            s += 2;
  569.            start = s;
  570.         }
  571.         break;
  572.          
  573.          default: s++;
  574.       }
  575.    }
  576. }
  577.  
  578.  
  579. static char*
  580. _scan_macro( s, ps, doexpand )/*
  581. ================================
  582.     This routine scans a macro use and expands it to the value.  It
  583.     returns the macro's expanded value and modifies the pointer into the
  584.     src string to point at the first character after the macro use.
  585.     The types of uses recognized are:
  586.  
  587.         $$ and $<sp>    - expands to $
  588.         $(name)        - expands to value of name
  589.         ${name}        - same as above
  590.         $($(name))    - recurses on macro names (any level)
  591.     and
  592.         $(func[,args ...] [data])
  593.     and 
  594.             $(name:modifier_list:modifier_list:...)
  595.         
  596.     see comment for Expand for description of valid modifiers.
  597.  
  598.     NOTE that once a macro name bounded by ( or { is found only
  599.     the appropriate terminator (ie. ( or } is searched for. */
  600.  
  601. char *s;        /* pointer to start of src string   */
  602. char **ps;        /* pointer to start pointer        */
  603. int  doexpand;          /* If TRUE enables macro expansion  */
  604. {
  605.    char sdelim;         /* start of macro delimiter         */
  606.    char edelim;         /* corresponding end macro delim    */
  607.    char *start;         /* start of prefix                  */
  608.    char *macro_name;    /* temporary macro name             */
  609.    char *recurse_name;  /* recursive macro name             */
  610.    char *result;    /* result for macro expansion        */
  611.    int  bflag = 0;      /* brace flag, ==0 => $A type macro */
  612.    int  done  = 0;      /* != 0 => done macro search        */
  613.    int  lev   = 0;      /* brace level                      */
  614.    int  mflag = 0;      /* != 0 => modifiers present in mac */
  615.    int  fflag = 0;    /* != 0 => GNU style function         */
  616.    HASHPTR hp;        /* hash table pointer for macros    */
  617.    
  618.    DB_ENTER( "_scan_macro" );
  619.  
  620.    /* Check for $ at end of line, or $ followed by white space */
  621.    if( !*s || strchr(" \t", *s) != NIL(char)) {
  622.       *ps = s;
  623.       DB_RETURN( DmStrDup("") );
  624.    }
  625.  
  626.    if( *s == '$' ) {    /* Take care of the simple $$ case. */
  627.       *ps = s+1;
  628.       DB_RETURN( DmStrDup("$") );
  629.    }
  630.  
  631.    sdelim = *s;         /* set and remember start/end delim */
  632.    if( sdelim == '(' )
  633.       edelim = ')';
  634.    else
  635.       edelim = '}';
  636.  
  637.    start = s;           /* build up macro name, find its end*/
  638.    while( !done ) {
  639.       switch( *s ) {
  640.          case '(':                /* open macro brace */
  641.          case '{':
  642.         if( *s == sdelim ) {
  643.            lev++;
  644.            bflag++;
  645.         }
  646.         break;
  647.          
  648.          case ':':                              /* halt at modifier */
  649.             if( lev == 1 && !fflag && doexpand ) {
  650.                done = TRUE;
  651.                mflag = 1;
  652.             }
  653.             break;
  654.  
  655.      case ' ':
  656.      case '\t':
  657.      case '\n':
  658.         if ( lev == 1 ) fflag = 1;
  659.         break;
  660.             
  661.      case '\0':                /* check for null */
  662.         *ps = s;
  663.         done = TRUE;
  664.         if( lev ) {
  665.            bflag = 0;
  666.            s     = start;
  667.         }
  668.         break;
  669.          
  670.          case ')':                /* close macro brace */
  671.          case '}':
  672.         if( *s == edelim && lev ) --lev;
  673.         /*FALLTHRU*/
  674.  
  675.          default:
  676.         done = !lev;
  677.       }
  678.       s++;
  679.    }
  680.  
  681.    /* Check if this is a $A type macro.  If so then we have to
  682.     * handle it a little differently. */
  683.    if( bflag )
  684.       macro_name = DmSubStr( start+1, s-1 );
  685.    else
  686.       macro_name = DmSubStr( start, s );
  687.  
  688.    if (!doexpand) {
  689.       *ps = s;
  690.       DB_RETURN(macro_name);
  691.    }
  692.  
  693.    /* Check to see if the macro name contains spaces, if so then treat it
  694.     * as a GNU style function invocation and call the function mapper to
  695.     * deal with it.  We do not call the function expander if the function
  696.     * invocation begins with a '$' */
  697.    if( fflag && *macro_name != '$' ) {
  698.       result = Exec_function(macro_name);
  699.    }
  700.    else {
  701.       /* Check if the macro is a recursive macro name, if so then
  702.        * EXPAND the name before expanding the value */
  703.       if( strchr( macro_name, '$' ) != NIL(char) ) {
  704.      recurse_name = Expand( macro_name );
  705.      FREE( macro_name );
  706.      macro_name = recurse_name;
  707.       }
  708.  
  709.       /* Code to do value expansion goes here, NOTE:  macros whose assign bit
  710.      is one have been evaluated and assigned, they contain no further
  711.      expansions and thus do not need their values expanded again. */
  712.  
  713.       if( (hp = GET_MACRO( macro_name )) != NIL(HASH) ) {
  714.      if( hp->ht_flag & M_MARK )
  715.         Fatal( "Detected circular macro [%s]", hp->ht_name );
  716.  
  717.      if( !(hp->ht_flag & M_EXPANDED) ) {
  718.         hp->ht_flag |= M_MARK;
  719.         result = Expand( hp->ht_value );
  720.         hp->ht_flag ^= M_MARK;
  721.      }
  722.      else if( hp->ht_value != NIL(char) )
  723.         result = DmStrDup( hp->ht_value );
  724.      else
  725.         result = DmStrDup( "" );
  726.  
  727.      /*
  728.       * Mark macros as used only if we are not expanding them for
  729.       * the purpose of a .IF test, so we can warn about redef after use*/
  730.  
  731.      if( !If_expand ) hp->ht_flag |= M_USED;
  732.       }
  733.       else
  734.      result = DmStrDup( "" );
  735.    }
  736.  
  737.    if( mflag ) {
  738.       char separator;
  739.       int  modifier_list = 0;
  740.       int  aug_mod       = FALSE;
  741.       char *pat1;
  742.       char *pat2;
  743.       char *p;
  744.  
  745.       /* Yet another brain damaged AUGMAKE kludge.  We should accept the 
  746.        * AUGMAKE bullshit of $(f:pat=sub) form of macro expansion.  In
  747.        * order to do this we will forgo the normal processing if the
  748.        * AUGMAKE solution pans out, otherwise we will try to process the
  749.        * modifiers ala dmake.
  750.        *
  751.        * So we look for = in modifier string.
  752.        * If found we process it and not do the normal stuff */
  753.  
  754.       for( p=s; *p && *p != '=' && *p != edelim; p++ );
  755.  
  756.       if( *p == '=' ) {
  757.      char *tmp;
  758.  
  759.      pat1 = Expand(tmp = DmSubStr(s,p)); FREE(tmp);
  760.      s = p+1;
  761.      p = _scan_ballanced_parens(s+1, edelim);
  762.  
  763.      if ( !*p ) {
  764.         Warning( "Incomplete macro expression [%s]", s );
  765.         p = s+1;
  766.      }
  767.      pat2 = Expand(tmp = DmSubStr(s,p)); FREE(tmp);
  768.  
  769.      result = Apply_edit( result, pat1, pat2, TRUE, TRUE );
  770.      FREE( pat1 );
  771.      FREE( pat2 );
  772.      s = p;
  773.      aug_mod = TRUE;
  774.       }
  775.  
  776.       if( !aug_mod )
  777.      while( *s && *s != edelim ) {        /* while not at end of macro */
  778.         char switch_char;
  779.  
  780.         switch( switch_char = *s++ ) {
  781.            case 'b':
  782.            case 'B': modifier_list |= FILE_FLAG;            break;
  783.  
  784.            case 'd':
  785.            case 'D': modifier_list |= DIRECTORY_FLAG;         break;
  786.  
  787.            case 'f':
  788.            case 'F': modifier_list |= FILE_FLAG | SUFFIX_FLAG; break;
  789.  
  790.            case 'e':
  791.            case 'E': modifier_list |= SUFFIX_FLAG; break;
  792.  
  793.            case 'l':
  794.            case 'L': modifier_list |= TOLOWER_FLAG; break;
  795.  
  796.            case 'i':
  797.            case 'I': modifier_list |= INFNAME_FLAG; break;
  798.  
  799.            case 'u':
  800.            case 'U': modifier_list |= TOUPPER_FLAG; break;
  801.  
  802.            case 'S':
  803.            case 's':
  804.           if( modifier_list ) {
  805.              Warning( "Edit modifier must appear alone, ignored");
  806.              modifier_list = 0;
  807.           }
  808.           else {
  809.              separator = *s++;
  810.              for( p=s; *p != separator && *p != edelim; p++ );
  811.  
  812.              if( *p == edelim )
  813.                 Warning("Syntax error in edit pattern, ignored");
  814.              else {
  815.             char *t1, *t2;
  816.             pat1 = DmSubStr( s, p );
  817.             for(s=p=p+1; (*p != separator) && (*p != edelim); p++ );
  818.             pat2 = DmSubStr( s, p );
  819.             t1 = Expand(pat1); FREE(pat1);
  820.             t2 = Expand(pat2); FREE(pat2);
  821.             result = Apply_edit( result, t1, t2, TRUE, FALSE );
  822.             FREE( t1 );
  823.             FREE( t2 );
  824.              }
  825.              s = p;
  826.           }
  827.           /* find the end of the macro spec, or the start of a new
  828.            * modifier list for further processing of the result */
  829.  
  830.           for( ; (*s != edelim) && (*s != ':'); s++ );
  831.           if( *s == ':' ) s++;
  832.           break;
  833.  
  834.            case 'T':
  835.            case 't':
  836.            case '^':
  837.            case '+':
  838.           if( modifier_list ) {
  839.              Warning( "Tokenize modifier must appear alone, ignored");
  840.              modifier_list = 0;
  841.           }
  842.           else {
  843.              separator = *s++;
  844.  
  845.              if( separator == '$' ) {
  846.             p = _scan_ballanced_parens(s,'\0');
  847.  
  848.             if ( *p ) {
  849.                char *tmp;
  850.                pat1 = Expand(tmp = DmSubStr(s-1,p));
  851.                FREE(tmp);
  852.                result = Tokenize(result, pat1, switch_char, TRUE);
  853.                FREE(pat1);
  854.             }
  855.             else {
  856.                Warning( "Incomplete macro expression [%s]", s );
  857.             }
  858.             s = p;
  859.              }
  860.              else if ( separator == '\"' ) {
  861.             /* we change the semantics to allow $(v:t")") */
  862.             for (p = s; *p && *p != separator; p++)
  863.                if (*p == '\\')
  864.                   if (p[1] == '\\' || p[1] == '"')
  865.                  p++;
  866.  
  867.             if( *p == 0 )
  868.                Fatal( "Unterminated separator string" );
  869.             else {
  870.                pat1 = DmSubStr( s, p );
  871.                result = Tokenize( result, pat1, switch_char, TRUE);
  872.                FREE( pat1 );
  873.             }
  874.             s = p;
  875.              }
  876.              else {
  877.                Warning(
  878.                "Separator must be a quoted string or macro expression");
  879.              }
  880.  
  881.              /* find the end of the macro spec, or the start of a new
  882.               * modifier list for further processing of the result */
  883.  
  884.              for( ; (*s != edelim) && (*s != ':'); s++ );
  885.              if( *s == ':' ) s++;
  886.           }
  887.           break;
  888.  
  889.            case ':':
  890.           if( modifier_list ) {
  891.              result = Apply_modifiers( modifier_list, result );
  892.              modifier_list = 0;
  893.           }
  894.           break;
  895.  
  896.            default:
  897.           Warning( "Illegal modifier in macro, ignored" );
  898.           break;
  899.         }
  900.      }
  901.  
  902.       if( modifier_list ) /* apply modifier */
  903.          result = Apply_modifiers( modifier_list, result );
  904.       
  905.       s++;
  906.    }
  907.  
  908.    *ps = s;
  909.    FREE( macro_name );
  910.    DB_RETURN( result );
  911. }
  912.  
  913.  
  914. static char*
  915. _scan_brace( s, ps, flag )/*
  916. ============================
  917.       This routine scans for { token_list } pairs.  It expands the value of
  918.       token_list by calling Expand on it.  Token_list may be anything at all.
  919.       Note that the routine count's ballanced parentheses.  This means you
  920.       cannot have something like { fred { joe }, if that is what you really
  921.       need the write it as { fred {{ joe }, flag is set to 1 if all ok
  922.       and to 0 if the braces were unballanced. */
  923.       
  924. char *s;
  925. char **ps;
  926. int  *flag;
  927. {
  928.    char *t;
  929.    char *start;
  930.    char *res;
  931.    int  lev  = 1;
  932.    int  done = 0;
  933.    
  934.    DB_ENTER( "_scan_brace" );
  935.  
  936.    start = s;
  937.    while( !done )
  938.       switch( *s++ ) {
  939.          case '{': 
  940.             if( *s == '{' ) break;              /* ignore {{ */
  941.             lev++;
  942.             break;
  943.             
  944.          case '}': 
  945.             if( *s == '}' ) break;              /* ignore }} */
  946.         if( lev )
  947.            if( --lev == 0 ) done = TRUE;
  948.         break;
  949.  
  950.      case '$':
  951.         if( *s == '{' || *s == '}' ) {
  952.           if( (t = strchr(s,'}')) != NIL(char) )
  953.              s = t;
  954.           s++;
  955.         }
  956.         break;
  957.          
  958.          case '\0':
  959.         if( lev ) {
  960.            done = TRUE;
  961.            s--;
  962.            /* error malformed macro expansion */
  963.         }
  964.         break;
  965.       }
  966.  
  967.    start = DmSubStr( start, (lev) ? s : s-1 );
  968.  
  969.    if( lev ) {
  970.       /* Braces were not ballanced so just return the string.
  971.        * Do not expand it. */
  972.        
  973.       res   = DmStrJoin( "{", start, -1, FALSE );
  974.       *flag = 0;
  975.    }
  976.    else {
  977.       *flag = 1;
  978.       res   = Expand( start );
  979.  
  980.       if( (t = DmStrSpn( res, " \t" )) != res ) strcpy( res, t );
  981.    }
  982.  
  983.    FREE( start );       /* this is ok! start is assigned a DmSubStr above */
  984.    *ps = s;
  985.  
  986.    DB_RETURN( res );
  987. }
  988.  
  989.  
  990. static char*
  991. _cross_prod( x, y )/*
  992. =====================
  993.       Given two strings x and y compute the cross-product of the tokens found
  994.       in each string.  ie. if x = "a b" and y = "c d" return "ac ad bc bd".
  995.  
  996.          NOTE:  buf will continue to grow until it is big enough to handle
  997.                 all cross product requests.  It is never freed!  (maybe I
  998.             will fix this someday) */
  999.       
  1000. char *x;
  1001. char *y;
  1002. {
  1003.    static char *buf;
  1004.    static int  buf_siz = 0;
  1005.    char *brkx;
  1006.    char *brky;
  1007.    char *cy;
  1008.    char *cx;
  1009.    char *res;
  1010.    int  i;
  1011.  
  1012.    if( *x && *y ) {
  1013.       res = DmStrDup( "" ); cx = x;
  1014.       while( *cx ) {
  1015.      cy = y;
  1016.          brkx = DmStrPbrk( cx, " \t\n" );
  1017.      if( (brkx-cx == 2) && *cx == '\"' && *(cx+1) == '\"' ) cx = brkx;
  1018.  
  1019.      while( *cy ) {
  1020.         brky = DmStrPbrk( cy, " \t\n" );
  1021.         if( (brky-cy == 2) && *cy == '\"' && *(cy+1) == '\"' ) cy = brky;
  1022.         i    = brkx-cx + brky-cy + 2;
  1023.  
  1024.         if( i > buf_siz ) {        /* grow buf to the correct size */
  1025.            if( buf != NIL(char) ) FREE( buf );
  1026.            if( (buf = MALLOC( i, char )) == NIL(char))  No_ram();
  1027.            buf_siz = i;
  1028.         }
  1029.  
  1030.         strncpy( buf, cx, (i = brkx-cx) );
  1031.         buf[i] = '\0';
  1032.         if (brky-cy > 0) strncat( buf, cy, brky-cy );
  1033.         buf[i+(brky-cy)] = '\0';
  1034.         strcat( buf, " " );
  1035.         res = DmStrJoin( res, buf, -1, TRUE );
  1036.         cy = DmStrSpn( brky, " \t\n" );
  1037.      }
  1038.      cx = DmStrSpn( brkx, " \t\n" );
  1039.       }
  1040.  
  1041.       FREE( x );
  1042.       res[ strlen(res)-1 ] = '\0';
  1043.    }
  1044.    else
  1045.       res = DmStrJoin( x, y, -1, TRUE );
  1046.  
  1047.    FREE( y );
  1048.    return( res );
  1049. }
  1050.