⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cpp.c

📁 cg编译器
💻 C
📖 第 1 页 / 共 2 页
字号:
/****************************************************************************\
Copyright (c) 2002, NVIDIA Corporation.

NVIDIA Corporation("NVIDIA") supplies this software to you in
consideration of your agreement to the following terms, and your use,
installation, modification or redistribution of this NVIDIA software
constitutes acceptance of these terms.  If you do not agree with these
terms, please do not use, install, modify or redistribute this NVIDIA
software.

In consideration of your agreement to abide by the following terms, and
subject to these terms, NVIDIA grants you a personal, non-exclusive
license, under NVIDIA's copyrights in this original NVIDIA software (the
"NVIDIA Software"), to use, reproduce, modify and redistribute the
NVIDIA Software, with or without modifications, in source and/or binary
forms; provided that if you redistribute the NVIDIA Software, you must
retain the copyright notice of NVIDIA, this notice and the following
text and disclaimers in all such redistributions of the NVIDIA Software.
Neither the name, trademarks, service marks nor logos of NVIDIA
Corporation may be used to endorse or promote products derived from the
NVIDIA Software without specific prior written permission from NVIDIA.
Except as expressly stated in this notice, no other rights or licenses
express or implied, are granted by NVIDIA herein, including but not
limited to any patent rights that may be infringed by your derivative
works or by other works in which the NVIDIA Software may be
incorporated. No hardware is licensed hereunder. 

THE NVIDIA SOFTWARE IS BEING PROVIDED ON AN "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, WARRANTIES OR CONDITIONS OF TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
ITS USE AND OPERATION EITHER ALONE OR IN COMBINATION WITH OTHER
PRODUCTS.

IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT,
INCIDENTAL, EXEMPLARY, CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, LOST PROFITS; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) OR ARISING IN ANY WAY
OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE
NVIDIA SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT,
TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\****************************************************************************/

//
// cpp.c
//

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include "slglobals.h"

/* Don't use memory.c's replacements, as we clean up properly here */
#undef malloc
#undef free

static int bindAtom = 0;
static int constAtom = 0;
static int defaultAtom = 0;
static int defineAtom = 0;
static int definedAtom = 0;
static int elseAtom = 0;
static int elifAtom = 0;
static int endifAtom = 0;
static int ifAtom = 0;
static int ifdefAtom = 0;
static int ifndefAtom = 0;
static int includeAtom = 0;
static int lineAtom = 0;
static int pragmaAtom = 0;
static int texunitAtom = 0;
static int undefAtom = 0;
static int __LINE__Atom = 0;
static int __FILE__Atom = 0;


static Scope *macros = 0;
#define MAX_MACRO_ARGS  64

static int ifdepth = 0; /* depth of #if nesting -- used to detect invalid
                         * #else/#endif */
static SourceLoc ifloc; /* outermost #if */

int InitCPP(void)
{
    char        buffer[64], *t;
    const char  *f;
    // Add various atoms needed by the CPP line scanner:
    bindAtom = LookUpAddString(atable, "bind");
    constAtom = LookUpAddString(atable, "const");
    defaultAtom = LookUpAddString(atable, "default");
    defineAtom = LookUpAddString(atable, "define");
    definedAtom = LookUpAddString(atable, "defined");
    elifAtom = LookUpAddString(atable, "elif");
    elseAtom = LookUpAddString(atable, "else");
    endifAtom = LookUpAddString(atable, "endif");
    ifAtom = LookUpAddString(atable, "if");
    ifdefAtom = LookUpAddString(atable, "ifdef");
    ifndefAtom = LookUpAddString(atable, "ifndef");
    includeAtom = LookUpAddString(atable, "include");
    lineAtom = LookUpAddString(atable, "line");
    pragmaAtom = LookUpAddString(atable, "pragma");
    texunitAtom = LookUpAddString(atable, "texunit");
    undefAtom = LookUpAddString(atable, "undef");
    __LINE__Atom = LookUpAddString(atable, "__LINE__");
    __FILE__Atom = LookUpAddString(atable, "__FILE__");
    macros = NewScopeInPool(mem_CreatePool(0, 0));
    strcpy(buffer, "PROFILE_");
    t = buffer + strlen(buffer);
    f = Cg->options.profileString;
    while ((isalnum(*f) || *f == '_') && t < buffer + sizeof(buffer) - 1)
        *t++ = toupper(*f++);
    *t = 0;
    PredefineMacro(buffer);
    return 1;
} // InitCPP

int FinalCPP(void)
{
    if (ifdepth)
        SemanticWarning(&ifloc, WARNING___CPP_IF_MISMATCH, "if");
    return 1;
}

static int CPPdefine()
{
    int token, name, args[MAX_MACRO_ARGS], argc;
    MacroSymbol mac;
    Symbol *symb;
    SourceLoc dummyLoc;

    memset(&mac, 0, sizeof(mac));
    token = Cg->currentInput->scan(Cg->currentInput);
    if (token != IDENT_SY) {
        SemanticError(Cg->tokenLoc, ERROR___CPP_SYNTAX, "define");
        return token;
    }
    name = yylval.sc_ident;
    token = Cg->currentInput->scan(Cg->currentInput);
    if (token == '(' && !yylval.sc_int) {
        // gather arguments
        argc = 0;
        do {
            token = Cg->currentInput->scan(Cg->currentInput);
            if (argc == 0 && token == ')') break;
            if (token != IDENT_SY) {
                SemanticError(Cg->tokenLoc, ERROR___CPP_SYNTAX, "define");
                return token;
            }
            if (argc < MAX_MACRO_ARGS)
                args[argc++] = yylval.sc_ident;
            token = Cg->currentInput->scan(Cg->currentInput);
        } while (token == ',');
        if (token != ')') {
            SemanticError(Cg->tokenLoc, ERROR___CPP_SYNTAX, "define");
            return token;
        }
        mac.argc = argc;
        mac.args = mem_Alloc(macros->pool, argc * sizeof(int));
        memcpy(mac.args, args, argc * sizeof(int));
        token = Cg->currentInput->scan(Cg->currentInput);
    }
    mac.body = NewTokenStream(GetAtomString(atable, name));
    while (token != '\n') {
        while (token == '\\') {
            token = Cg->currentInput->scan(Cg->currentInput);
            if (token == '\n')
                token = Cg->currentInput->scan(Cg->currentInput);
            else
                RecordToken(mac.body, '\\');
        }
        RecordToken(mac.body, token);
        token = Cg->currentInput->scan(Cg->currentInput);
    };

    symb = LookUpSymbol(macros, name);
    if (symb) {
        if (!symb->details.mac.undef) {
            // already defined -- need to make sure they are identical
            if (symb->details.mac.argc != mac.argc) goto error;
            for (argc=0; argc < mac.argc; argc++)
                if (symb->details.mac.args[argc] != mac.args[argc])
                    goto error;
            RewindTokenStream(symb->details.mac.body);
            RewindTokenStream(mac.body);
            do {
                int old_lval, old_token;
                old_token = ReadToken(symb->details.mac.body);
                old_lval = yylval.sc_int;
                token = ReadToken(mac.body);
                if (token != old_token || yylval.sc_int != old_lval) {
                error:
                    SemanticWarning(Cg->tokenLoc, WARNING___CPP_MACRO_REDEFINED,
                                    GetAtomString(atable, name));
                    break; }
            } while (token > 0);
        }
        FreeMacro(&symb->details.mac);
    } else {
        dummyLoc.file = 0;
        dummyLoc.line = 0;
        symb = AddSymbol(&dummyLoc, macros, name, 0, MACRO_S);
    }
    symb->details.mac = mac;
    return '\n';
} // CPPdefine

static int CPPundef()
{
    int token = Cg->currentInput->scan(Cg->currentInput);
    Symbol *symb;

    if (token != IDENT_SY) goto error;
    symb = LookUpSymbol(macros, yylval.sc_ident);
    if (symb) {
        symb->details.mac.undef = 1;
    }
    token = Cg->currentInput->scan(Cg->currentInput);
    if (token != '\n') {
    error:
        SemanticError(Cg->tokenLoc, ERROR___CPP_SYNTAX, "undef");
    }
    return token;
} // CPPundef

static int CPPif();

/* CPPelse -- skip forward to appropriate spot.  This is actually used
** to skip to and #endif after seeing an #else, AND to skip to a #else,
** #elif, or #endif after a #if/#ifdef/#ifndef/#elif test was false
*/

static int CPPelse(int matchelse)
{
    int atom, depth = 0;
    int token = Cg->currentInput->scan(Cg->currentInput);
    while (token > 0) {
        while (token != '\n')
            token = Cg->currentInput->scan(Cg->currentInput);
        if ((token = Cg->currentInput->scan(Cg->currentInput)) != '#')
            continue;
        if ((token = Cg->currentInput->scan(Cg->currentInput)) != IDENT_SY)
            continue;
        atom = yylval.sc_ident;
        if (atom == ifAtom || atom == ifdefAtom || atom == ifndefAtom)
            depth++;
        else if (atom == endifAtom) {
            if (--depth < 0) {
                if (ifdepth) ifdepth--;
                break;
            }
        }
        else if (matchelse && depth == 0) {
            if (atom == elseAtom)
                break;
            else if (atom == elifAtom) {
                /* we decrement ifdepth here, because CPPif will increment
                 * it and we really want to leave it alone */
                if (ifdepth) ifdepth--;
                return CPPif();
            }
        }
    };
    return token;
}

enum eval_prec {
    MIN_PREC,
    COND, LOGOR, LOGAND, OR, XOR, AND, EQUAL, RELATION, SHIFT, ADD, MUL, UNARY,
    MAX_PREC
};

static int op_logor(int a, int b) { return a || b; }
static int op_logand(int a, int b) { return a && b; }
static int op_or(int a, int b) { return a | b; }
static int op_xor(int a, int b) { return a ^ b; }
static int op_and(int a, int b) { return a & b; }
static int op_eq(int a, int b) { return a == b; }
static int op_ne(int a, int b) { return a != b; }
static int op_ge(int a, int b) { return a >= b; }
static int op_le(int a, int b) { return a <= b; }
static int op_gt(int a, int b) { return a > b; }
static int op_lt(int a, int b) { return a < b; }
static int op_shl(int a, int b) { return a << b; }
static int op_shr(int a, int b) { return a >> b; }
static int op_add(int a, int b) { return a + b; }
static int op_sub(int a, int b) { return a - b; }
static int op_mul(int a, int b) { return a * b; }
static int op_div(int a, int b) { return a / b; }
static int op_mod(int a, int b) { return a % b; }
static int op_pos(int a) { return a; }
static int op_neg(int a) { return -a; }
static int op_cmpl(int a) { return ~a; }
static int op_not(int a) { return !a; }

struct {
    int token, prec, (*op)(int, int);
} binop[] = {
    { OR_SY, LOGOR, op_logor },
    { AND_SY, LOGAND, op_logand },
    { '|', OR, op_or },
    { '^', XOR, op_xor },
    { '&', AND, op_and },
    { EQ_SY, EQUAL, op_eq },
    { NE_SY, EQUAL, op_ne },
    { '>', RELATION, op_gt },
    { GE_SY, RELATION, op_ge },
    { '<', RELATION, op_lt },
    { LE_SY, RELATION, op_le },
    { LL_SY, SHIFT, op_shl },
    { GG_SY, SHIFT, op_shr },
    { '+', ADD, op_add },
    { '-', ADD, op_sub },
    { '*', MUL, op_mul },
    { '/', MUL, op_div },
    { '%', MUL, op_mod },
};

struct {
    int token, (*op)(int);
} unop[] = {
    { '+', op_pos },
    { '-', op_neg },
    { '~', op_cmpl },
    { '!', op_not },
};

#define ALEN(A) (sizeof(A)/sizeof(A[0]))

int eval(int token, int prec, int *res, int *err)
{
    int         i, val;
    Symbol      *s;

    if (token == IDENT_SY) {
        if (yylval.sc_ident == definedAtom) {
            int needclose = 0;

            token = Cg->currentInput->scan(Cg->currentInput);
            if (token == '(') {
                needclose = 1;
                token = Cg->currentInput->scan(Cg->currentInput);
            }
            if (token != IDENT_SY)
                goto error;
            *res = (s = LookUpSymbol(macros, yylval.sc_ident))
                        ? !s->details.mac.undef : 0;
            token = Cg->currentInput->scan(Cg->currentInput);
            if (needclose) {
                if (token != ')')
                    goto error;
                token = Cg->currentInput->scan(Cg->currentInput);
            }
        } else if (MacroExpand(yylval.sc_ident)) {
            token = Cg->currentInput->scan(Cg->currentInput);
            return eval(token, prec, res, err);
        } else {
            goto error;
        }
    } else if (token == INTCONST_SY) {
        *res = yylval.sc_int;
        token = Cg->currentInput->scan(Cg->currentInput);
    } else if (token == '(') {
        token = Cg->currentInput->scan(Cg->currentInput);
        token = eval(token, MIN_PREC, res, err);
        if (!*err) {
            if (token != ')')
                goto error;
            token = Cg->currentInput->scan(Cg->currentInput);
        }
    } else {
        for (i = ALEN(unop) - 1; i >= 0; i--) {
            if (unop[i].token == token)
                break;
        }
        if (i >= 0) {
            token = Cg->currentInput->scan(Cg->currentInput);
            token = eval(token, UNARY, res, err);
            *res = unop[i].op(*res);
        } else {
            goto error;
        }
    }
    while (!*err) {
        if (token == ')' || token == '\n') break;
        for (i = ALEN(binop) - 1; i >= 0; i--) {
            if (binop[i].token == token)
                break;
        }
        if (i < 0 || binop[i].prec <= prec)
            break;
        val = *res;
        token = Cg->currentInput->scan(Cg->currentInput);
        token = eval(token, binop[i].prec, res, err);
        *res = binop[i].op(val, *res);
    }
    return token;
error:
    SemanticError(Cg->tokenLoc, ERROR___CPP_SYNTAX, "if");
    *err = 1;
    *res = 0;
    return token;
} // eval

static int CPPif() {
    int token = Cg->currentInput->scan(Cg->currentInput);
    int res = 0, err = 0;

    if (!ifdepth++)
        ifloc = *Cg->tokenLoc;
    token = eval(token, MIN_PREC, &res, &err);
    if (token != '\n') {
        SemanticError(Cg->tokenLoc, ERROR___CPP_SYNTAX, "if");
    } else if (!res && !err) {
        token = CPPelse(1);
    }
    return token;
} // CPPif

static int CPPifdef(int defined)
{
    int token = Cg->currentInput->scan(Cg->currentInput);
    int name = yylval.sc_ident;
    ifdepth++;
    if (token != IDENT_SY) {
        SemanticError(Cg->tokenLoc, ERROR___CPP_SYNTAX,
                      defined ? "ifdef" : "ifndef");
    } else {
        Symbol *s = LookUpSymbol(macros, name);
        if (((s && !s->details.mac.undef) ? 1 : 0) != defined)
            token = CPPelse(1);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -