Create a base GLSL front-end from the 3Dlabs glslang front-end from 20-Sep-2005.

git-svn-id: https://cvs.khronos.org/svn/repos/ogl/trunk/ecosystem/public/sdk/tools/glslang@19944 e7fa87d3-cd2b-0410-9028-fcbf551c1848
This commit is contained in:
John Kessenich 2012-12-12 21:15:54 +00:00
commit a0af473a8b
80 changed files with 21238 additions and 0 deletions

View file

@ -0,0 +1,107 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
#include "Include/InfoSink.h"
#ifdef _WIN32
#include <windows.h>
#endif
void TInfoSinkBase::append(const char *s)
{
if (outputStream & EString) {
checkMem(strlen(s));
sink.append(s);
}
#ifdef _WIN32
if (outputStream & EDebugger)
OutputDebugString(s);
#endif
if (outputStream & EStdOut)
fprintf(stdout, "%s", s);
}
void TInfoSinkBase::append(int count, char c)
{
if (outputStream & EString) {
checkMem(count);
sink.append(count, c);
}
#ifdef _WIN32
if (outputStream & EDebugger) {
char str[2];
str[0] = c;
str[1] = '\0';
OutputDebugString(str);
}
#endif
if (outputStream & EStdOut)
fprintf(stdout, "%c", c);
}
void TInfoSinkBase::append(const TPersistString& t)
{
if (outputStream & EString) {
checkMem(t.size());
sink.append(t);
}
#ifdef _WIN32
if (outputStream & EDebugger)
OutputDebugString(t.c_str());
#endif
if (outputStream & EStdOut)
fprintf(stdout, "%s", t.c_str());
}
void TInfoSinkBase::append(const TString& t)
{
if (outputStream & EString) {
checkMem(t.size());
sink.append(t.c_str());
}
#ifdef _WIN32
if (outputStream & EDebugger)
OutputDebugString(t.c_str());
#endif
if (outputStream & EStdOut)
fprintf(stdout, "%s", t.c_str());
}

View file

@ -0,0 +1,962 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
//
// Create strings that declare built-in definitions, add built-ins that
// cannot be expressed in the files, and establish mappings between
// built-in functions and operators.
//
#include "../Include/intermediate.h"
#include "Initialize.h"
void TBuiltIns::initialize()
{
//
// Initialize all the built-in strings for parsing.
//
TString BuiltInFunctions;
TString BuiltInFunctionsVertex;
TString BuiltInFunctionsFragment;
TString StandardVertexVaryings;
TString StandardFragmentVaryings;
TString StandardVertexAttributes;
TString StandardUniforms;
{
//============================================================================
//
// Prototypes for built-in functions seen by both vertex and fragment shaders.
//
//============================================================================
TString& s = BuiltInFunctions;
//
// Angle and Trigonometric Functions.
//
s.append(TString("float radians(float degrees);"));
s.append(TString("vec2 radians(vec2 degrees);"));
s.append(TString("vec3 radians(vec3 degrees);"));
s.append(TString("vec4 radians(vec4 degrees);"));
s.append(TString("float degrees(float radians);"));
s.append(TString("vec2 degrees(vec2 radians);"));
s.append(TString("vec3 degrees(vec3 radians);"));
s.append(TString("vec4 degrees(vec4 radians);"));
s.append(TString("float sin(float angle);"));
s.append(TString("vec2 sin(vec2 angle);"));
s.append(TString("vec3 sin(vec3 angle);"));
s.append(TString("vec4 sin(vec4 angle);"));
s.append(TString("float cos(float angle);"));
s.append(TString("vec2 cos(vec2 angle);"));
s.append(TString("vec3 cos(vec3 angle);"));
s.append(TString("vec4 cos(vec4 angle);"));
s.append(TString("float tan(float angle);"));
s.append(TString("vec2 tan(vec2 angle);"));
s.append(TString("vec3 tan(vec3 angle);"));
s.append(TString("vec4 tan(vec4 angle);"));
s.append(TString("float asin(float x);"));
s.append(TString("vec2 asin(vec2 x);"));
s.append(TString("vec3 asin(vec3 x);"));
s.append(TString("vec4 asin(vec4 x);"));
s.append(TString("float acos(float x);"));
s.append(TString("vec2 acos(vec2 x);"));
s.append(TString("vec3 acos(vec3 x);"));
s.append(TString("vec4 acos(vec4 x);"));
s.append(TString("float atan(float y, float x);"));
s.append(TString("vec2 atan(vec2 y, vec2 x);"));
s.append(TString("vec3 atan(vec3 y, vec3 x);"));
s.append(TString("vec4 atan(vec4 y, vec4 x);"));
s.append(TString("float atan(float y_over_x);"));
s.append(TString("vec2 atan(vec2 y_over_x);"));
s.append(TString("vec3 atan(vec3 y_over_x);"));
s.append(TString("vec4 atan(vec4 y_over_x);"));
//
// Exponential Functions.
//
s.append(TString("float pow(float x, float y);"));
s.append(TString("vec2 pow(vec2 x, vec2 y);"));
s.append(TString("vec3 pow(vec3 x, vec3 y);"));
s.append(TString("vec4 pow(vec4 x, vec4 y);"));
s.append(TString("float exp(float x);"));
s.append(TString("vec2 exp(vec2 x);"));
s.append(TString("vec3 exp(vec3 x);"));
s.append(TString("vec4 exp(vec4 x);"));
s.append(TString("float log(float x);"));
s.append(TString("vec2 log(vec2 x);"));
s.append(TString("vec3 log(vec3 x);"));
s.append(TString("vec4 log(vec4 x);"));
s.append(TString("float exp2(float x);"));
s.append(TString("vec2 exp2(vec2 x);"));
s.append(TString("vec3 exp2(vec3 x);"));
s.append(TString("vec4 exp2(vec4 x);"));
s.append(TString("float log2(float x);"));
s.append(TString("vec2 log2(vec2 x);"));
s.append(TString("vec3 log2(vec3 x);"));
s.append(TString("vec4 log2(vec4 x);"));
s.append(TString("float sqrt(float x);"));
s.append(TString("vec2 sqrt(vec2 x);"));
s.append(TString("vec3 sqrt(vec3 x);"));
s.append(TString("vec4 sqrt(vec4 x);"));
s.append(TString("float inversesqrt(float x);"));
s.append(TString("vec2 inversesqrt(vec2 x);"));
s.append(TString("vec3 inversesqrt(vec3 x);"));
s.append(TString("vec4 inversesqrt(vec4 x);"));
//
// Common Functions.
//
s.append(TString("float abs(float x);"));
s.append(TString("vec2 abs(vec2 x);"));
s.append(TString("vec3 abs(vec3 x);"));
s.append(TString("vec4 abs(vec4 x);"));
s.append(TString("float sign(float x);"));
s.append(TString("vec2 sign(vec2 x);"));
s.append(TString("vec3 sign(vec3 x);"));
s.append(TString("vec4 sign(vec4 x);"));
s.append(TString("float floor(float x);"));
s.append(TString("vec2 floor(vec2 x);"));
s.append(TString("vec3 floor(vec3 x);"));
s.append(TString("vec4 floor(vec4 x);"));
s.append(TString("float ceil(float x);"));
s.append(TString("vec2 ceil(vec2 x);"));
s.append(TString("vec3 ceil(vec3 x);"));
s.append(TString("vec4 ceil(vec4 x);"));
s.append(TString("float fract(float x);"));
s.append(TString("vec2 fract(vec2 x);"));
s.append(TString("vec3 fract(vec3 x);"));
s.append(TString("vec4 fract(vec4 x);"));
s.append(TString("float mod(float x, float y);"));
s.append(TString("vec2 mod(vec2 x, float y);"));
s.append(TString("vec3 mod(vec3 x, float y);"));
s.append(TString("vec4 mod(vec4 x, float y);"));
s.append(TString("vec2 mod(vec2 x, vec2 y);"));
s.append(TString("vec3 mod(vec3 x, vec3 y);"));
s.append(TString("vec4 mod(vec4 x, vec4 y);"));
s.append(TString("float min(float x, float y);"));
s.append(TString("vec2 min(vec2 x, float y);"));
s.append(TString("vec3 min(vec3 x, float y);"));
s.append(TString("vec4 min(vec4 x, float y);"));
s.append(TString("vec2 min(vec2 x, vec2 y);"));
s.append(TString("vec3 min(vec3 x, vec3 y);"));
s.append(TString("vec4 min(vec4 x, vec4 y);"));
s.append(TString("float max(float x, float y);"));
s.append(TString("vec2 max(vec2 x, float y);"));
s.append(TString("vec3 max(vec3 x, float y);"));
s.append(TString("vec4 max(vec4 x, float y);"));
s.append(TString("vec2 max(vec2 x, vec2 y);"));
s.append(TString("vec3 max(vec3 x, vec3 y);"));
s.append(TString("vec4 max(vec4 x, vec4 y);"));
s.append(TString("float clamp(float x, float minVal, float maxVal);"));
s.append(TString("vec2 clamp(vec2 x, float minVal, float maxVal);"));
s.append(TString("vec3 clamp(vec3 x, float minVal, float maxVal);"));
s.append(TString("vec4 clamp(vec4 x, float minVal, float maxVal);"));
s.append(TString("vec2 clamp(vec2 x, vec2 minVal, vec2 maxVal);"));
s.append(TString("vec3 clamp(vec3 x, vec3 minVal, vec3 maxVal);"));
s.append(TString("vec4 clamp(vec4 x, vec4 minVal, vec4 maxVal);"));
s.append(TString("float mix(float x, float y, float a);"));
s.append(TString("vec2 mix(vec2 x, vec2 y, float a);"));
s.append(TString("vec3 mix(vec3 x, vec3 y, float a);"));
s.append(TString("vec4 mix(vec4 x, vec4 y, float a);"));
s.append(TString("vec2 mix(vec2 x, vec2 y, vec2 a);"));
s.append(TString("vec3 mix(vec3 x, vec3 y, vec3 a);"));
s.append(TString("vec4 mix(vec4 x, vec4 y, vec4 a);"));
s.append(TString("float step(float edge, float x);"));
s.append(TString("vec2 step(vec2 edge, vec2 x);"));
s.append(TString("vec3 step(vec3 edge, vec3 x);"));
s.append(TString("vec4 step(vec4 edge, vec4 x);"));
s.append(TString("vec2 step(float edge, vec2 x);"));
s.append(TString("vec3 step(float edge, vec3 x);"));
s.append(TString("vec4 step(float edge, vec4 x);"));
s.append(TString("float smoothstep(float edge0, float edge1, float x);"));
s.append(TString("vec2 smoothstep(vec2 edge0, vec2 edge1, vec2 x);"));
s.append(TString("vec3 smoothstep(vec3 edge0, vec3 edge1, vec3 x);"));
s.append(TString("vec4 smoothstep(vec4 edge0, vec4 edge1, vec4 x);"));
s.append(TString("vec2 smoothstep(float edge0, float edge1, vec2 x);"));
s.append(TString("vec3 smoothstep(float edge0, float edge1, vec3 x);"));
s.append(TString("vec4 smoothstep(float edge0, float edge1, vec4 x);"));
//
// Geometric Functions.
//
s.append(TString("float length(float x);"));
s.append(TString("float length(vec2 x);"));
s.append(TString("float length(vec3 x);"));
s.append(TString("float length(vec4 x);"));
s.append(TString("float distance(float p0, float p1);"));
s.append(TString("float distance(vec2 p0, vec2 p1);"));
s.append(TString("float distance(vec3 p0, vec3 p1);"));
s.append(TString("float distance(vec4 p0, vec4 p1);"));
s.append(TString("float dot(float x, float y);"));
s.append(TString("float dot(vec2 x, vec2 y);"));
s.append(TString("float dot(vec3 x, vec3 y);"));
s.append(TString("float dot(vec4 x, vec4 y);"));
s.append(TString("vec3 cross(vec3 x, vec3 y);"));
s.append(TString("float normalize(float x);"));
s.append(TString("vec2 normalize(vec2 x);"));
s.append(TString("vec3 normalize(vec3 x);"));
s.append(TString("vec4 normalize(vec4 x);"));
s.append(TString("float faceforward(float N, float I, float Nref);"));
s.append(TString("vec2 faceforward(vec2 N, vec2 I, vec2 Nref);"));
s.append(TString("vec3 faceforward(vec3 N, vec3 I, vec3 Nref);"));
s.append(TString("vec4 faceforward(vec4 N, vec4 I, vec4 Nref);"));
s.append(TString("float reflect(float I, float N);"));
s.append(TString("vec2 reflect(vec2 I, vec2 N);"));
s.append(TString("vec3 reflect(vec3 I, vec3 N);"));
s.append(TString("vec4 reflect(vec4 I, vec4 N);"));
s.append(TString("float refract(float I, float N, float eta);"));
s.append(TString("vec2 refract(vec2 I, vec2 N, float eta);"));
s.append(TString("vec3 refract(vec3 I, vec3 N, float eta);"));
s.append(TString("vec4 refract(vec4 I, vec4 N, float eta);"));
//
// Matrix Functions.
//
s.append(TString("mat2 matrixCompMult(mat2 x, mat2 y);"));
s.append(TString("mat3 matrixCompMult(mat3 x, mat3 y);"));
s.append(TString("mat4 matrixCompMult(mat4 x, mat4 y);"));
//
// Vector relational functions.
//
s.append(TString("bvec2 lessThan(vec2 x, vec2 y);"));
s.append(TString("bvec3 lessThan(vec3 x, vec3 y);"));
s.append(TString("bvec4 lessThan(vec4 x, vec4 y);"));
s.append(TString("bvec2 lessThan(ivec2 x, ivec2 y);"));
s.append(TString("bvec3 lessThan(ivec3 x, ivec3 y);"));
s.append(TString("bvec4 lessThan(ivec4 x, ivec4 y);"));
s.append(TString("bvec2 lessThanEqual(vec2 x, vec2 y);"));
s.append(TString("bvec3 lessThanEqual(vec3 x, vec3 y);"));
s.append(TString("bvec4 lessThanEqual(vec4 x, vec4 y);"));
s.append(TString("bvec2 lessThanEqual(ivec2 x, ivec2 y);"));
s.append(TString("bvec3 lessThanEqual(ivec3 x, ivec3 y);"));
s.append(TString("bvec4 lessThanEqual(ivec4 x, ivec4 y);"));
s.append(TString("bvec2 greaterThan(vec2 x, vec2 y);"));
s.append(TString("bvec3 greaterThan(vec3 x, vec3 y);"));
s.append(TString("bvec4 greaterThan(vec4 x, vec4 y);"));
s.append(TString("bvec2 greaterThan(ivec2 x, ivec2 y);"));
s.append(TString("bvec3 greaterThan(ivec3 x, ivec3 y);"));
s.append(TString("bvec4 greaterThan(ivec4 x, ivec4 y);"));
s.append(TString("bvec2 greaterThanEqual(vec2 x, vec2 y);"));
s.append(TString("bvec3 greaterThanEqual(vec3 x, vec3 y);"));
s.append(TString("bvec4 greaterThanEqual(vec4 x, vec4 y);"));
s.append(TString("bvec2 greaterThanEqual(ivec2 x, ivec2 y);"));
s.append(TString("bvec3 greaterThanEqual(ivec3 x, ivec3 y);"));
s.append(TString("bvec4 greaterThanEqual(ivec4 x, ivec4 y);"));
s.append(TString("bvec2 equal(vec2 x, vec2 y);"));
s.append(TString("bvec3 equal(vec3 x, vec3 y);"));
s.append(TString("bvec4 equal(vec4 x, vec4 y);"));
s.append(TString("bvec2 equal(ivec2 x, ivec2 y);"));
s.append(TString("bvec3 equal(ivec3 x, ivec3 y);"));
s.append(TString("bvec4 equal(ivec4 x, ivec4 y);"));
s.append(TString("bvec2 equal(bvec2 x, bvec2 y);"));
s.append(TString("bvec3 equal(bvec3 x, bvec3 y);"));
s.append(TString("bvec4 equal(bvec4 x, bvec4 y);"));
s.append(TString("bvec2 notEqual(vec2 x, vec2 y);"));
s.append(TString("bvec3 notEqual(vec3 x, vec3 y);"));
s.append(TString("bvec4 notEqual(vec4 x, vec4 y);"));
s.append(TString("bvec2 notEqual(ivec2 x, ivec2 y);"));
s.append(TString("bvec3 notEqual(ivec3 x, ivec3 y);"));
s.append(TString("bvec4 notEqual(ivec4 x, ivec4 y);"));
s.append(TString("bvec2 notEqual(bvec2 x, bvec2 y);"));
s.append(TString("bvec3 notEqual(bvec3 x, bvec3 y);"));
s.append(TString("bvec4 notEqual(bvec4 x, bvec4 y);"));
s.append(TString("bool any(bvec2 x);"));
s.append(TString("bool any(bvec3 x);"));
s.append(TString("bool any(bvec4 x);"));
s.append(TString("bool all(bvec2 x);"));
s.append(TString("bool all(bvec3 x);"));
s.append(TString("bool all(bvec4 x);"));
s.append(TString("bvec2 not(bvec2 x);"));
s.append(TString("bvec3 not(bvec3 x);"));
s.append(TString("bvec4 not(bvec4 x);"));
//
// Texture Functions.
//
s.append(TString("vec4 texture1D(sampler1D sampler, float coord);"));
s.append(TString("vec4 texture1DProj(sampler1D sampler, vec2 coord);"));
s.append(TString("vec4 texture1DProj(sampler1D sampler, vec4 coord);"));
s.append(TString("vec4 texture2D(sampler2D sampler, vec2 coord);"));
s.append(TString("vec4 texture2DProj(sampler2D sampler, vec3 coord);"));
s.append(TString("vec4 texture2DProj(sampler2D sampler, vec4 coord);"));
s.append(TString("vec4 texture3D(sampler3D sampler, vec3 coord);"));
s.append(TString("vec4 texture3DProj(sampler3D sampler, vec4 coord);"));
s.append(TString("vec4 textureCube(samplerCube sampler, vec3 coord);"));
s.append(TString("vec4 shadow1D(sampler1DShadow sampler, vec3 coord);"));
s.append(TString("vec4 shadow2D(sampler2DShadow sampler, vec3 coord);"));
s.append(TString("vec4 shadow1DProj(sampler1DShadow sampler, vec4 coord);"));
s.append(TString("vec4 shadow2DProj(sampler2DShadow sampler, vec4 coord);"));
// ARB_texture_rectangle
s.append(TString("vec4 texture2DRect(sampler2DRect sampler, vec2 coord);"));
s.append(TString("vec4 texture2DRectProj(sampler2DRect sampler, vec3 coord);"));
s.append(TString("vec4 texture2DRectProj(sampler2DRect sampler, vec4 coord);"));
s.append(TString("vec4 shadow2DRect(sampler2DRectShadow sampler, vec3 coord);"));
s.append(TString("vec4 shadow2DRectProj(sampler2DRectShadow sampler, vec4 coord);"));
//
// Noise functions.
//
s.append(TString("float noise1(float x);"));
s.append(TString("float noise1(vec2 x);"));
s.append(TString("float noise1(vec3 x);"));
s.append(TString("float noise1(vec4 x);"));
s.append(TString("vec2 noise2(float x);"));
s.append(TString("vec2 noise2(vec2 x);"));
s.append(TString("vec2 noise2(vec3 x);"));
s.append(TString("vec2 noise2(vec4 x);"));
s.append(TString("vec3 noise3(float x);"));
s.append(TString("vec3 noise3(vec2 x);"));
s.append(TString("vec3 noise3(vec3 x);"));
s.append(TString("vec3 noise3(vec4 x);"));
s.append(TString("vec4 noise4(float x);"));
s.append(TString("vec4 noise4(vec2 x);"));
s.append(TString("vec4 noise4(vec3 x);"));
s.append(TString("vec4 noise4(vec4 x);"));
s.append(TString("\n"));
}
{
//============================================================================
//
// Prototypes for built-in functions seen by vertex shaders only.
//
//============================================================================
TString& s = BuiltInFunctionsVertex;
//
// Geometric Functions.
//
s.append(TString("vec4 ftransform();"));
//
// Texture Functions.
//
s.append(TString("vec4 texture1DLod(sampler1D sampler, float coord, float lod);"));
s.append(TString("vec4 texture1DProjLod(sampler1D sampler, vec2 coord, float lod);"));
s.append(TString("vec4 texture1DProjLod(sampler1D sampler, vec4 coord, float lod);"));
s.append(TString("vec4 texture2DLod(sampler2D sampler, vec2 coord, float lod);"));
s.append(TString("vec4 texture2DProjLod(sampler2D sampler, vec3 coord, float lod);"));
s.append(TString("vec4 texture2DProjLod(sampler2D sampler, vec4 coord, float lod);"));
s.append(TString("vec4 texture3DLod(sampler3D sampler, vec3 coord, float lod);"));
s.append(TString("vec4 texture3DProjLod(sampler3D sampler, vec4 coord, float lod);"));
s.append(TString("vec4 textureCubeLod(samplerCube sampler, vec3 coord, float lod);"));
s.append(TString("vec4 shadow1DLod(sampler1DShadow sampler, vec3 coord, float lod);"));
s.append(TString("vec4 shadow2DLod(sampler2DShadow sampler, vec3 coord, float lod);"));
s.append(TString("vec4 shadow1DProjLod(sampler1DShadow sampler, vec4 coord, float lod);"));
s.append(TString("vec4 shadow2DProjLod(sampler2DShadow sampler, vec4 coord, float lod);"));
s.append(TString("\n"));
}
{
//============================================================================
//
// Prototypes for built-in functions seen by fragment shaders only.
//
//============================================================================
TString& s = BuiltInFunctionsFragment;
//
// Texture Functions.
//
s.append(TString("vec4 texture1D(sampler1D sampler, float coord, float bias);"));
s.append(TString("vec4 texture1DProj(sampler1D sampler, vec2 coord, float bias);"));
s.append(TString("vec4 texture1DProj(sampler1D sampler, vec4 coord, float bias);"));
s.append(TString("vec4 texture2D(sampler2D sampler, vec2 coord, float bias);"));
s.append(TString("vec4 texture2DProj(sampler2D sampler, vec3 coord, float bias);"));
s.append(TString("vec4 texture2DProj(sampler2D sampler, vec4 coord, float bias);"));
s.append(TString("vec4 texture3D(sampler3D sampler, vec3 coord, float bias);"));
s.append(TString("vec4 texture3DProj(sampler3D sampler, vec4 coord, float bias);"));
s.append(TString("vec4 textureCube(samplerCube sampler, vec3 coord, float bias);"));
s.append(TString("vec4 shadow1D(sampler1DShadow sampler, vec3 coord, float bias);"));
s.append(TString("vec4 shadow2D(sampler2DShadow sampler, vec3 coord, float bias);"));
s.append(TString("vec4 shadow1DProj(sampler1DShadow sampler, vec4 coord, float bias);"));
s.append(TString("vec4 shadow2DProj(sampler2DShadow sampler, vec4 coord, float bias);"));
s.append(TString("float dFdx(float p);"));
s.append(TString("vec2 dFdx(vec2 p);"));
s.append(TString("vec3 dFdx(vec3 p);"));
s.append(TString("vec4 dFdx(vec4 p);"));
s.append(TString("float dFdy(float p);"));
s.append(TString("vec2 dFdy(vec2 p);"));
s.append(TString("vec3 dFdy(vec3 p);"));
s.append(TString("vec4 dFdy(vec4 p);"));
s.append(TString("float fwidth(float p);"));
s.append(TString("vec2 fwidth(vec2 p);"));
s.append(TString("vec3 fwidth(vec3 p);"));
s.append(TString("vec4 fwidth(vec4 p);"));
s.append(TString("\n"));
}
{
//============================================================================
//
// Standard Uniforms
//
//============================================================================
TString& s = StandardUniforms;
//
// OpenGL'uniform' state. Page numbers are in reference to version
// 1.4 of the OpenGL specification.
//
//
// Matrix state. p. 31, 32, 37, 39, 40.
//
s.append(TString("uniform mat4 gl_ModelViewMatrix;"));
s.append(TString("uniform mat4 gl_ProjectionMatrix;"));
s.append(TString("uniform mat4 gl_ModelViewProjectionMatrix;"));
//
// Derived matrix state that provides inverse and transposed versions
// of the matrices above.
//
s.append(TString("uniform mat3 gl_NormalMatrix;"));
s.append(TString("uniform mat4 gl_ModelViewMatrixInverse;"));
s.append(TString("uniform mat4 gl_ProjectionMatrixInverse;"));
s.append(TString("uniform mat4 gl_ModelViewProjectionMatrixInverse;"));
s.append(TString("uniform mat4 gl_ModelViewMatrixTranspose;"));
s.append(TString("uniform mat4 gl_ProjectionMatrixTranspose;"));
s.append(TString("uniform mat4 gl_ModelViewProjectionMatrixTranspose;"));
s.append(TString("uniform mat4 gl_ModelViewMatrixInverseTranspose;"));
s.append(TString("uniform mat4 gl_ProjectionMatrixInverseTranspose;"));
s.append(TString("uniform mat4 gl_ModelViewProjectionMatrixInverseTranspose;"));
//
// Normal scaling p. 39.
//
s.append(TString("uniform float gl_NormalScale;"));
//
// Depth range in window coordinates, p. 33
//
s.append(TString("struct gl_DepthRangeParameters {"));
s.append(TString(" float near;")); // n
s.append(TString(" float far;")); // f
s.append(TString(" float diff;")); // f - n
s.append(TString("};"));
s.append(TString("uniform gl_DepthRangeParameters gl_DepthRange;"));
//
// Point Size, p. 66, 67.
//
s.append(TString("struct gl_PointParameters {"));
s.append(TString(" float size;"));
s.append(TString(" float sizeMin;"));
s.append(TString(" float sizeMax;"));
s.append(TString(" float fadeThresholdSize;"));
s.append(TString(" float distanceConstantAttenuation;"));
s.append(TString(" float distanceLinearAttenuation;"));
s.append(TString(" float distanceQuadraticAttenuation;"));
s.append(TString("};"));
s.append(TString("uniform gl_PointParameters gl_Point;"));
//
// Material State p. 50, 55.
//
s.append(TString("struct gl_MaterialParameters {"));
s.append(TString(" vec4 emission;")); // Ecm
s.append(TString(" vec4 ambient;")); // Acm
s.append(TString(" vec4 diffuse;")); // Dcm
s.append(TString(" vec4 specular;")); // Scm
s.append(TString(" float shininess;")); // Srm
s.append(TString("};"));
s.append(TString("uniform gl_MaterialParameters gl_FrontMaterial;"));
s.append(TString("uniform gl_MaterialParameters gl_BackMaterial;"));
//
// Light State p 50, 53, 55.
//
s.append(TString("struct gl_LightSourceParameters {"));
s.append(TString(" vec4 ambient;")); // Acli
s.append(TString(" vec4 diffuse;")); // Dcli
s.append(TString(" vec4 specular;")); // Scli
s.append(TString(" vec4 position;")); // Ppli
s.append(TString(" vec4 halfVector;")); // Derived: Hi
s.append(TString(" vec3 spotDirection;")); // Sdli
s.append(TString(" float spotExponent;")); // Srli
s.append(TString(" float spotCutoff;")); // Crli
// (range: [0.0,90.0], 180.0)
s.append(TString(" float spotCosCutoff;")); // Derived: cos(Crli)
// (range: [1.0,0.0],-1.0)
s.append(TString(" float constantAttenuation;")); // K0
s.append(TString(" float linearAttenuation;")); // K1
s.append(TString(" float quadraticAttenuation;"));// K2
s.append(TString("};"));
s.append(TString("struct gl_LightModelParameters {"));
s.append(TString(" vec4 ambient;")); // Acs
s.append(TString("};"));
s.append(TString("uniform gl_LightModelParameters gl_LightModel;"));
//
// Derived state from products of light and material.
//
s.append(TString("struct gl_LightModelProducts {"));
s.append(TString(" vec4 sceneColor;")); // Derived. Ecm + Acm * Acs
s.append(TString("};"));
s.append(TString("uniform gl_LightModelProducts gl_FrontLightModelProduct;"));
s.append(TString("uniform gl_LightModelProducts gl_BackLightModelProduct;"));
s.append(TString("struct gl_LightProducts {"));
s.append(TString(" vec4 ambient;")); // Acm * Acli
s.append(TString(" vec4 diffuse;")); // Dcm * Dcli
s.append(TString(" vec4 specular;")); // Scm * Scli
s.append(TString("};"));
//
// Fog p. 161
//
s.append(TString("struct gl_FogParameters {"));
s.append(TString(" vec4 color;"));
s.append(TString(" float density;"));
s.append(TString(" float start;"));
s.append(TString(" float end;"));
s.append(TString(" float scale;")); // 1 / (gl_FogEnd - gl_FogStart)
s.append(TString("};"));
s.append(TString("uniform gl_FogParameters gl_Fog;"));
s.append(TString("\n"));
}
{
//============================================================================
//
// Vertex attributes, p. 19.
//
//============================================================================
TString& s = StandardVertexAttributes;
s.append(TString("attribute vec4 gl_Color;"));
s.append(TString("attribute vec4 gl_SecondaryColor;"));
s.append(TString("attribute vec3 gl_Normal;"));
s.append(TString("attribute vec4 gl_Vertex;"));
s.append(TString("attribute vec4 gl_MultiTexCoord0;"));
s.append(TString("attribute vec4 gl_MultiTexCoord1;"));
s.append(TString("attribute vec4 gl_MultiTexCoord2;"));
s.append(TString("attribute vec4 gl_MultiTexCoord3;"));
s.append(TString("attribute vec4 gl_MultiTexCoord4;"));
s.append(TString("attribute vec4 gl_MultiTexCoord5;"));
s.append(TString("attribute vec4 gl_MultiTexCoord6;"));
s.append(TString("attribute vec4 gl_MultiTexCoord7;"));
s.append(TString("attribute float gl_FogCoord;"));
s.append(TString("\n"));
}
{
//============================================================================
//
// Define the output varying interface from the vertex shader.
//
//============================================================================
TString& s = StandardVertexVaryings;
s.append(TString("varying vec4 gl_FrontColor;"));
s.append(TString("varying vec4 gl_BackColor;"));
s.append(TString("varying vec4 gl_FrontSecondaryColor;"));
s.append(TString("varying vec4 gl_BackSecondaryColor;"));
s.append(TString("varying vec4 gl_TexCoord[];"));
s.append(TString("varying float gl_FogFragCoord;"));
s.append(TString("\n"));
}
{
//============================================================================
//
// Define the input varying interface to the fragment shader.
//
//============================================================================
TString& s = StandardFragmentVaryings;
s.append(TString("varying vec4 gl_Color;"));
s.append(TString("varying vec4 gl_SecondaryColor;"));
s.append(TString("varying vec4 gl_TexCoord[];"));
s.append(TString("varying float gl_FogFragCoord;"));
s.append(TString("\n"));
}
builtInStrings[EShLangFragment].push_back(BuiltInFunctions.c_str());
builtInStrings[EShLangFragment].push_back(BuiltInFunctionsFragment);
builtInStrings[EShLangFragment].push_back(StandardUniforms);
builtInStrings[EShLangFragment].push_back(StandardFragmentVaryings);
builtInStrings[EShLangVertex].push_back(BuiltInFunctions);
builtInStrings[EShLangVertex].push_back(BuiltInFunctionsVertex);
builtInStrings[EShLangVertex].push_back(StandardVertexVaryings);
builtInStrings[EShLangVertex].push_back(StandardVertexAttributes);
builtInStrings[EShLangVertex].push_back(StandardUniforms);
}
void TBuiltIns::initialize(const TBuiltInResource &resources)
{
//
// Initialize all the built-in strings for parsing.
//
TString StandardUniforms;
{
//============================================================================
//
// Standard Uniforms
//
//============================================================================
TString& s = StandardUniforms;
//
// Implementation dependent constants. The example values below
// are the minimum values allowed for these maximums.
//
char builtInConstant[80];
sprintf(builtInConstant, "const int gl_MaxLights = %d;", resources.maxLights); // GL 1.0
s.append(TString(builtInConstant));
sprintf(builtInConstant, "const int gl_MaxClipPlanes = %d;", resources.maxClipPlanes); // GL 1.0
s.append(TString(builtInConstant));
sprintf(builtInConstant, "const int gl_MaxTextureUnits = %d;", resources.maxTextureUnits); // GL 1.2
s.append(TString(builtInConstant));
sprintf(builtInConstant, "const int gl_MaxTextureCoords = %d;", resources.maxTextureCoords); // ARB_fragment_program
s.append(TString(builtInConstant));
sprintf(builtInConstant, "const int gl_MaxVertexAttribs = %d;", resources.maxVertexAttribs); // ARB_vertex_shader
s.append(TString(builtInConstant));
sprintf(builtInConstant, "const int gl_MaxVertexUniformComponents = %d;", resources.maxVertexUniformComponents); // ARB_vertex_shader
s.append(TString(builtInConstant));
sprintf(builtInConstant, "const int gl_MaxVaryingFloats = %d;", resources.maxVaryingFloats); // ARB_vertex_shader
s.append(TString(builtInConstant));
sprintf(builtInConstant, "const int gl_MaxVertexTextureImageUnits = %d;", resources.maxVertexTextureImageUnits); // ARB_vertex_shader
s.append(TString(builtInConstant));
sprintf(builtInConstant, "const int gl_MaxCombinedTextureImageUnits = %d;", resources.maxCombinedTextureImageUnits); // ARB_vertex_shader
s.append(TString(builtInConstant));
sprintf(builtInConstant, "const int gl_MaxTextureImageUnits = %d;", resources.maxTextureImageUnits); // ARB_fragment_shader
s.append(TString(builtInConstant));
sprintf(builtInConstant, "const int gl_MaxFragmentUniformComponents = %d;", resources.maxFragmentUniformComponents); // ARB_fragment_shader
s.append(TString(builtInConstant));
sprintf(builtInConstant, "const int gl_MaxDrawBuffers = %d;", resources.maxDrawBuffers); // proposed ARB_draw_buffers
s.append(TString(builtInConstant));
//
// OpenGL'uniform' state. Page numbers are in reference to version
// 1.4 of the OpenGL specification.
//
//
// Matrix state. p. 31, 32, 37, 39, 40.
//
s.append(TString("uniform mat4 gl_TextureMatrix[gl_MaxTextureCoords];"));
//
// Derived matrix state that provides inverse and transposed versions
// of the matrices above.
//
s.append(TString("uniform mat4 gl_TextureMatrixInverse[gl_MaxTextureCoords];"));
s.append(TString("uniform mat4 gl_TextureMatrixTranspose[gl_MaxTextureCoords];"));
s.append(TString("uniform mat4 gl_TextureMatrixInverseTranspose[gl_MaxTextureCoords];"));
//
// Clip planes p. 42.
//
s.append(TString("uniform vec4 gl_ClipPlane[gl_MaxClipPlanes];"));
//
// Light State p 50, 53, 55.
//
s.append(TString("uniform gl_LightSourceParameters gl_LightSource[gl_MaxLights];"));
//
// Derived state from products of light.
//
s.append(TString("uniform gl_LightProducts gl_FrontLightProduct[gl_MaxLights];"));
s.append(TString("uniform gl_LightProducts gl_BackLightProduct[gl_MaxLights];"));
//
// Textureg Environment and Generation, p. 152, p. 40-42.
//
s.append(TString("uniform vec4 gl_TextureEnvColor[gl_MaxTextureImageUnits];"));
s.append(TString("uniform vec4 gl_EyePlaneS[gl_MaxTextureCoords];"));
s.append(TString("uniform vec4 gl_EyePlaneT[gl_MaxTextureCoords];"));
s.append(TString("uniform vec4 gl_EyePlaneR[gl_MaxTextureCoords];"));
s.append(TString("uniform vec4 gl_EyePlaneQ[gl_MaxTextureCoords];"));
s.append(TString("uniform vec4 gl_ObjectPlaneS[gl_MaxTextureCoords];"));
s.append(TString("uniform vec4 gl_ObjectPlaneT[gl_MaxTextureCoords];"));
s.append(TString("uniform vec4 gl_ObjectPlaneR[gl_MaxTextureCoords];"));
s.append(TString("uniform vec4 gl_ObjectPlaneQ[gl_MaxTextureCoords];"));
s.append(TString("\n"));
}
builtInStrings[EShLangFragment].push_back(StandardUniforms);
builtInStrings[EShLangVertex].push_back(StandardUniforms);
}
void IdentifyBuiltIns(EShLanguage language, TSymbolTable& symbolTable)
{
//
// First, insert some special built-in variables that are not in
// the built-in header files.
//
switch(language) {
case EShLangFragment: {
symbolTable.insert(*new TVariable(NewPoolTString("gl_FrontFacing"), TType(EbtBool, EvqFace, 1)));
symbolTable.insert(*new TVariable(NewPoolTString("gl_FragCoord"), TType(EbtFloat, EvqFragCoord, 4)));
symbolTable.insert(*new TVariable(NewPoolTString("gl_FragColor"), TType(EbtFloat, EvqFragColor, 4)));
symbolTable.insert(*new TVariable(NewPoolTString("gl_FragDepth"), TType(EbtFloat, EvqFragDepth, 1)));
}
break;
case EShLangVertex:
symbolTable.insert(*new TVariable(NewPoolTString("gl_Position"), TType(EbtFloat, EvqPosition, 4)));
symbolTable.insert(*new TVariable(NewPoolTString("gl_PointSize"), TType(EbtFloat, EvqPointSize, 1)));
symbolTable.insert(*new TVariable(NewPoolTString("gl_ClipVertex"), TType(EbtFloat, EvqClipVertex, 4)));
break;
default: break;
}
//
// Next, identify which built-ins from the already loaded headers have
// a mapping to an operator. Those that are not identified as such are
// expected to be resolved through a library of functions, versus as
// operations.
//
symbolTable.relateToOperator("not", EOpVectorLogicalNot);
symbolTable.relateToOperator("matrixCompMult", EOpMul);
symbolTable.relateToOperator("mod", EOpMod);
symbolTable.relateToOperator("equal", EOpVectorEqual);
symbolTable.relateToOperator("notEqual", EOpVectorNotEqual);
symbolTable.relateToOperator("lessThan", EOpLessThan);
symbolTable.relateToOperator("greaterThan", EOpGreaterThan);
symbolTable.relateToOperator("lessThanEqual", EOpLessThanEqual);
symbolTable.relateToOperator("greaterThanEqual", EOpGreaterThanEqual);
symbolTable.relateToOperator("radians", EOpRadians);
symbolTable.relateToOperator("degrees", EOpDegrees);
symbolTable.relateToOperator("sin", EOpSin);
symbolTable.relateToOperator("cos", EOpCos);
symbolTable.relateToOperator("tan", EOpTan);
symbolTable.relateToOperator("asin", EOpAsin);
symbolTable.relateToOperator("acos", EOpAcos);
symbolTable.relateToOperator("atan", EOpAtan);
symbolTable.relateToOperator("pow", EOpPow);
symbolTable.relateToOperator("exp2", EOpExp2);
symbolTable.relateToOperator("log", EOpLog);
symbolTable.relateToOperator("exp", EOpExp);
symbolTable.relateToOperator("log2", EOpLog2);
symbolTable.relateToOperator("sqrt", EOpSqrt);
symbolTable.relateToOperator("inversesqrt", EOpInverseSqrt);
symbolTable.relateToOperator("abs", EOpAbs);
symbolTable.relateToOperator("sign", EOpSign);
symbolTable.relateToOperator("floor", EOpFloor);
symbolTable.relateToOperator("ceil", EOpCeil);
symbolTable.relateToOperator("fract", EOpFract);
symbolTable.relateToOperator("min", EOpMin);
symbolTable.relateToOperator("max", EOpMax);
symbolTable.relateToOperator("clamp", EOpClamp);
symbolTable.relateToOperator("mix", EOpMix);
symbolTable.relateToOperator("step", EOpStep);
symbolTable.relateToOperator("smoothstep", EOpSmoothStep);
symbolTable.relateToOperator("length", EOpLength);
symbolTable.relateToOperator("distance", EOpDistance);
symbolTable.relateToOperator("dot", EOpDot);
symbolTable.relateToOperator("cross", EOpCross);
symbolTable.relateToOperator("normalize", EOpNormalize);
symbolTable.relateToOperator("forward", EOpFaceForward);
symbolTable.relateToOperator("reflect", EOpReflect);
symbolTable.relateToOperator("refract", EOpRefract);
symbolTable.relateToOperator("any", EOpAny);
symbolTable.relateToOperator("all", EOpAll);
switch(language) {
case EShLangVertex:
break;
case EShLangFragment:
symbolTable.relateToOperator("dFdx", EOpDPdx);
symbolTable.relateToOperator("dFdy", EOpDPdy);
symbolTable.relateToOperator("fwidth", EOpFwidth);
break;
case EShLangPack:
case EShLangUnpack:
symbolTable.relateToOperator("itof", EOpItof);
symbolTable.relateToOperator("ftoi", EOpFtoi);
symbolTable.relateToOperator("skipPixels", EOpSkipPixels);
symbolTable.relateToOperator("readInput", EOpReadInput);
symbolTable.relateToOperator("writePixel", EOpWritePixel);
symbolTable.relateToOperator("bitmapLSB", EOpBitmapLsb);
symbolTable.relateToOperator("bitmapMSB", EOpBitmapMsb);
symbolTable.relateToOperator("writeOutput", EOpWriteOutput);
symbolTable.relateToOperator("readPixel", EOpReadPixel);
break;
default: assert(false && "Language not supported");
}
}
void IdentifyBuiltIns(EShLanguage language, TSymbolTable& symbolTable, const TBuiltInResource &resources)
{
//
// First, insert some special built-in variables that are not in
// the built-in header files.
//
switch(language) {
case EShLangFragment: {
// Set up gl_FragData. The array size.
TType fragData(EbtFloat, EvqFragColor, 4, false, true);
fragData.setArraySize(resources.maxDrawBuffers);
symbolTable.insert(*new TVariable(NewPoolTString("gl_FragData"), fragData));
}
break;
default: break;
}
}
char* GetPreprocessorBuiltinString()
{
static char *PreprocessorBuiltinString = "#define GL_ARB_texture_rectangle 1\n"
"#define GL_3DL_array_objects 1\n";
return PreprocessorBuiltinString;
}

View file

@ -0,0 +1,63 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
#ifndef _INITIALIZE_INCLUDED_
#define _INITIALIZE_INCLUDED_
#include "Include/ResourceLimits.h"
#include "../Include/Common.h"
#include "../Include/ShHandle.h"
#include "SymbolTable.h"
typedef TVector<TString> TBuiltInStrings;
class TBuiltIns {
public:
POOL_ALLOCATOR_NEW_DELETE(GlobalPoolAllocator)
void initialize();
void initialize(const TBuiltInResource& resources);
TBuiltInStrings* getBuiltInStrings() { return builtInStrings; }
protected:
TBuiltInStrings builtInStrings[EShLangCount];
};
void IdentifyBuiltIns(EShLanguage, TSymbolTable&);
void IdentifyBuiltIns(EShLanguage, TSymbolTable&, const TBuiltInResource &resources);
bool GenerateBuiltInSymbolTable(const TBuiltInResource* resources, TInfoSink&, TSymbolTable*, EShLanguage language = EShLangCount);
bool InitializeSymbolTable(TBuiltInStrings* BuiltInStrings, EShLanguage language, TInfoSink& infoSink, const TBuiltInResource *resources, TSymbolTable*);
char* GetPreprocessorBuiltinString();
extern "C" int InitPreprocessor(void);
extern "C" int FinalizePreprocessor(void);
#endif // _INITIALIZE_INCLUDED_

View file

@ -0,0 +1,243 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
#include "../Include/intermediate.h"
//
// Traverse the intermediate representation tree, and
// call a node type specific function for each node.
// Done recursively through the member function Traverse().
// Node types can be skipped if their function to call is 0,
// but their subtree will still be traversed.
// Nodes with children can have their whole subtree skipped
// if preVisit is turned on and the type specific function
// returns false.
//
// preVisit, postVisit, and rightToLeft control what order
// nodes are visited in.
//
//
// Traversal functions for terminals are straighforward....
//
void TIntermSymbol::traverse(TIntermTraverser* it)
{
if (it->visitSymbol)
it->visitSymbol(this, it);
}
void TIntermConstantUnion::traverse(TIntermTraverser* it)
{
if (it->visitConstantUnion)
it->visitConstantUnion(this, it);
}
//
// Traverse a binary node.
//
void TIntermBinary::traverse(TIntermTraverser* it)
{
bool visit = true;
//
// visit the node before children if pre-visiting.
//
if (it->preVisit && it->visitBinary)
visit = it->visitBinary(true, this, it);
//
// Visit the children, in the right order.
//
if (visit) {
++it->depth;
if (it->rightToLeft) {
if (right)
right->traverse(it);
if (left)
left->traverse(it);
} else {
if (left)
left->traverse(it);
if (right)
right->traverse(it);
}
--it->depth;
}
//
// Visit the node after the children, if requested and the traversal
// hasn't been cancelled yet.
//
if (visit && it->postVisit && it->visitBinary)
it->visitBinary(false, this, it);
}
//
// Traverse a unary node. Same comments in binary node apply here.
//
void TIntermUnary::traverse(TIntermTraverser* it)
{
bool visit = true;
if (it->preVisit && it->visitUnary)
visit = it->visitUnary(true, this, it);
if (visit) {
++it->depth;
operand->traverse(it);
--it->depth;
}
if (visit && it->postVisit && it->visitUnary)
it->visitUnary(false, this, it);
}
//
// Traverse an aggregate node. Same comments in binary node apply here.
//
void TIntermAggregate::traverse(TIntermTraverser* it)
{
bool visit = true;
if (it->preVisit && it->visitAggregate)
visit = it->visitAggregate(true, this, it);
if (visit) {
++it->depth;
TIntermSequence::iterator sit;
if (it->rightToLeft) {
sit = sequence.end();
while (sit != sequence.begin()) {
--sit;
(*sit)->traverse(it);
}
} else {
for (sit = sequence.begin(); sit != sequence.end(); ++sit)
(*sit)->traverse(it);
}
--it->depth;
}
if (visit && it->postVisit && it->visitAggregate)
it->visitAggregate(false, this, it);
}
//
// Traverse a selection node. Same comments in binary node apply here.
//
void TIntermSelection::traverse(TIntermTraverser* it)
{
bool visit = true;
if (it->preVisit && it->visitSelection)
visit = it->visitSelection(true, this, it);
if (visit) {
++it->depth;
if (it->rightToLeft) {
if (falseBlock)
falseBlock->traverse(it);
if (trueBlock)
trueBlock->traverse(it);
condition->traverse(it);
} else {
condition->traverse(it);
if (trueBlock)
trueBlock->traverse(it);
if (falseBlock)
falseBlock->traverse(it);
}
--it->depth;
}
if (visit && it->postVisit && it->visitSelection)
it->visitSelection(false, this, it);
}
//
// Traverse a loop node. Same comments in binary node apply here.
//
void TIntermLoop::traverse(TIntermTraverser* it)
{
bool visit = true;
if (it->preVisit && it->visitLoop)
visit = it->visitLoop(true, this, it);
if (visit) {
++it->depth;
if (it->rightToLeft) {
if (terminal)
terminal->traverse(it);
if (body)
body->traverse(it);
if (test)
test->traverse(it);
} else {
if (test)
test->traverse(it);
if (body)
body->traverse(it);
if (terminal)
terminal->traverse(it);
}
--it->depth;
}
if (visit && it->postVisit && it->visitLoop)
it->visitLoop(false, this, it);
}
//
// Traverse a branch node. Same comments in binary node apply here.
//
void TIntermBranch::traverse(TIntermTraverser* it)
{
bool visit = true;
if (it->preVisit && it->visitBranch)
visit = it->visitBranch(true, this, it);
if (visit && expression) {
++it->depth;
expression->traverse(it);
--it->depth;
}
if (visit && it->postVisit && it->visitBranch)
it->visitBranch(false, this, it);
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,84 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
#ifndef _MMAP_INCLUDED_
#define _MMAP_INCLUDED_
//
// Encapsulate memory mapped files
//
class TMMap {
public:
TMMap(const char* fileName) :
fSize(-1), // -1 is the error value returned by GetFileSize()
fp(NULL),
fBuff(0) // 0 is the error value returned by MapViewOfFile()
{
if ((fp = fopen(fileName, "r")) == NULL)
return;
char c = getc(fp);
fSize = 0;
while (c != EOF) {
fSize++;
c = getc(fp);
}
if (c == EOF)
fSize++;
rewind(fp);
fBuff = (char*)malloc(sizeof(char) * fSize);
int count = 0;
c = getc(fp);
while (c != EOF) {
fBuff[count++] = c;
c = getc(fp);
}
fBuff[count++] = c;
}
char* getData() { return fBuff; }
int getSize() { return fSize; }
~TMMap() {
if (fp != NULL)
fclose(fp);
}
private:
int fSize; // size of file to map in
FILE *fp;
char* fBuff; // the actual data;
};
#endif // _MMAP_INCLUDED_

View file

@ -0,0 +1,161 @@
INCLUDE = -I. -I.. -I../.. -I../Include -I../Public -I../OSDependent/Linux -I../../OGLCompilersDLL
CC=g++
INCPREPROCESSOR=./preprocessor
INCCODEGEN=./../GenericCodeGen
INCOSDEPENDENT=./../OSDependent/Linux/
INCINITIALISATION=./../../OGLCompilersDLL/
LIBPREPROCESSOR=./preprocessor/libPreprocessor.a
LIBOSDEPENDENT=./../OSDependent/Linux/libOssource.a
LIBINITIALISATION=./../../OGLCompilersDLL/libInitializeDll.a
LIBCODEGEN=./../GenericCodeGen/libCodeGen.a
OBJECTS= Initialize.o IntermTraverse.o \
Intermediate.o ParseHelper.o PoolAlloc.o QualifierAlive.o \
RemoveTree.o ShaderLang.o intermOut.o parseConst.o SymbolTable.o \
InfoSink.o
SRCS= Gen_glslang.cpp Gen_glslang_tab.cpp Initialize.cpp IntermTraverse.cpp \
Intermediate.cpp ParseHelper.cpp PoolAlloc.cp QualifierAlive.cpp \
RemoveTree.cpp ShaderLang.cpp SymbolTable.cpp intermOut.cpp \
parseConst.cpp InfoSink.cpp
CPPFLAGS=$(DEFINE) $(INCLUDE)
SHAREDOBJECT=./lib/libglslang.so
default: all
all: $(SHAREDOBJECT)
$(SHAREDOBJECT): Gen_glslang.o Gen_glslang_tab.o $(OBJECTS) \
$(LIBPREPROCESSOR) $(LIBCODEGEN) $(LIBOSDEPENDENT) $(LIBINITIALISATION)
$(CC) -fPIC -shared -lc -o $@ $(OBJECTS) $(LIBPREPROCESSOR) $(LIBCODEGEN) $(LIBOSDEPENDENT) $(LIBINITIALISATION) Gen_glslang.o Gen_glslang_tab.o
Gen_glslang.o : Gen_glslang.cpp glslang_tab.h
$(CC) -c $(INCLUDE) Gen_glslang.cpp -o $@
Gen_glslang_tab.o : Gen_glslang_tab.cpp
$(CC) -c $(INCLUDE) Gen_glslang_tab.cpp -o $@
Gen_glslang.cpp: glslang.l
@echo Generating Gen_glslang.cpp
@dos2unix glslang.l
flex glslang.l
Gen_glslang_tab.cpp glslang_tab.h: glslang.y
@echo Generating Gen_glslang_tab.cpp
@dos2unix glslang.y
bison -t -v -d glslang.y
mv glslang.tab.c Gen_glslang_tab.cpp
mv glslang.tab.h glslang_tab.h
%.o : %.cpp
$(CC) $(CPPFLAGS) -c $<
$(LIBPREPROCESSOR):
cd $(INCPREPROCESSOR); make
$(LIBCODEGEN):
cd $(INCCODEGEN); make
$(LIBINITIALISATION):
cd $(INCINITIALISATION); make
$(LIBOSDEPENDENT):
cd $(INCOSDEPENDENT); make
depend:
cd $(INCPREPROCESSOR); make depend
cd $(INCCODEGEN); make depend
cd $(INCINITIALISATION); make depend
cd $(INCOSDEPENDENT); make depend
makedepend -Y -- $(CPPFLAGS) -- $(SRCS)
#
# Cleanup
#
.PHONY : clean
clean :
$(RM) *.o *.a Gen_glslang_tab.cpp Gen_glslang.cpp glslang_tab.h glslang.output
$(RM) ./lib/*.so
cd $(INCPREPROCESSOR); make clean
cd $(INCCODEGEN); make clean
cd $(INCINITIALISATION); make clean
cd $(INCOSDEPENDENT); make clean
# DO NOT DELETE
Gen_glslang.o: ParseHelper.h ../Include/ShHandle.h
Gen_glslang.o: ../Public/ShaderLang.h ../Include/InfoSink.h
Gen_glslang.o: ../Include/Common.h ../Include/PoolAlloc.h SymbolTable.h
Gen_glslang.o: ../Include/Common.h ../Include/intermediate.h
Gen_glslang.o: ../Include/Types.h ../Include/BaseTypes.h
Gen_glslang.o: ../Include/ConstantUnion.h ../Include/InfoSink.h
Gen_glslang.o: localintermediate.h ../Include/intermediate.h
Gen_glslang.o: ../Public/ShaderLang.h glslang_tab.h ./unistd.h
Gen_glslang.o: ./preprocessor/preprocess.h ./preprocessor/slglobals.h
Gen_glslang.o: ./preprocessor/memory.h ./preprocessor/atom.h
Gen_glslang.o: ./preprocessor/scanner.h ./preprocessor/parser.h
Gen_glslang.o: ./preprocessor/cpp.h ./preprocessor/tokens.h
Gen_glslang.o: ./preprocessor/symbols.h ./preprocessor/compile.h
Gen_glslang_tab.o: SymbolTable.h ../Include/Common.h
Gen_glslang_tab.o: ../Include/intermediate.h ../Include/Common.h
Gen_glslang_tab.o: ../Include/PoolAlloc.h ../Include/Types.h
Gen_glslang_tab.o: ../Include/BaseTypes.h ../Include/ConstantUnion.h
Gen_glslang_tab.o: ../Include/InfoSink.h ParseHelper.h ../Include/ShHandle.h
Gen_glslang_tab.o: ../Public/ShaderLang.h
Gen_glslang_tab.o: ../Include/InfoSink.h localintermediate.h
Gen_glslang_tab.o: ../Include/intermediate.h ../Public/ShaderLang.h
Initialize.o: ../Include/intermediate.h Initialize.h
Initialize.o: ../Include/ResourceLimits.h ../Include/Common.h
Initialize.o: ../Include/PoolAlloc.h ../Include/ShHandle.h
Initialize.o: ../Public/ShaderLang.h
Initialize.o: ../Include/InfoSink.h SymbolTable.h ../Include/Common.h
Initialize.o: ../Include/intermediate.h ../Include/Types.h
Initialize.o: ../Include/BaseTypes.h ../Include/ConstantUnion.h
Initialize.o: ../Include/InfoSink.h
IntermTraverse.o: ../Include/intermediate.h
Intermediate.o: ../Include/ShHandle.h
Intermediate.o: ../Public/ShaderLang.h ../Include/InfoSink.h
Intermediate.o: ../Include/Common.h ../Include/PoolAlloc.h
Intermediate.o: localintermediate.h ../Include/intermediate.h
Intermediate.o: ../Public/ShaderLang.h SymbolTable.h ../Include/Common.h
Intermediate.o: ../Include/intermediate.h ../Include/Types.h
Intermediate.o: ../Include/BaseTypes.h ../Include/ConstantUnion.h
Intermediate.o: ../Include/InfoSink.h QualifierAlive.h RemoveTree.h
ParseHelper.o: ParseHelper.h ../Include/ShHandle.h
ParseHelper.o: ../Public/ShaderLang.h ../Include/InfoSink.h
ParseHelper.o: ../Include/Common.h ../Include/PoolAlloc.h SymbolTable.h
ParseHelper.o: ../Include/Common.h ../Include/intermediate.h
ParseHelper.o: ../Include/Types.h ../Include/BaseTypes.h
ParseHelper.o: ../Include/ConstantUnion.h ../Include/InfoSink.h
ParseHelper.o: localintermediate.h ../Include/intermediate.h
ParseHelper.o: ../Public/ShaderLang.h ../Include/InitializeParseContext.h
ParseHelper.o: ../OSDependent/Linux/osinclude.h
ParseHelper.o: ../Include/InitializeGlobals.h ../Include/PoolAlloc.h
QualifierAlive.o: ../Include/intermediate.h
RemoveTree.o: ../Include/intermediate.h RemoveTree.h
ShaderLang.o: SymbolTable.h ../Include/Common.h ../Include/intermediate.h
ShaderLang.o: ../Include/Common.h ../Include/PoolAlloc.h ../Include/Types.h
ShaderLang.o: ../Include/BaseTypes.h ../Include/ConstantUnion.h
ShaderLang.o: ../Include/InfoSink.h ParseHelper.h ../Include/ShHandle.h
ShaderLang.o: ../Public/ShaderLang.h
ShaderLang.o: ../Include/InfoSink.h localintermediate.h
ShaderLang.o: ../Include/intermediate.h ../Public/ShaderLang.h
ShaderLang.o: ../Include/ResourceLimits.h Initialize.h
SymbolTable.o: SymbolTable.h ../Include/Common.h ../Include/intermediate.h
SymbolTable.o: ../Include/Common.h ../Include/PoolAlloc.h ../Include/Types.h
SymbolTable.o: ../Include/BaseTypes.h ../Include/ConstantUnion.h
SymbolTable.o: ../Include/InfoSink.h
intermOut.o: localintermediate.h ../Include/intermediate.h
intermOut.o: ../Public/ShaderLang.h SymbolTable.h ../Include/Common.h
intermOut.o: ../Include/intermediate.h ../Include/Common.h
intermOut.o: ../Include/PoolAlloc.h ../Include/Types.h ../Include/BaseTypes.h
intermOut.o: ../Include/ConstantUnion.h ../Include/InfoSink.h
intermOut.o: ../Include/ShHandle.h
intermOut.o: ../Public/ShaderLang.h ../Include/InfoSink.h
parseConst.o: ParseHelper.h ../Include/ShHandle.h
parseConst.o: ../Public/ShaderLang.h ../Include/InfoSink.h
parseConst.o: ../Include/Common.h ../Include/PoolAlloc.h SymbolTable.h
parseConst.o: ../Include/Common.h ../Include/intermediate.h
parseConst.o: ../Include/Types.h ../Include/BaseTypes.h
parseConst.o: ../Include/ConstantUnion.h ../Include/InfoSink.h
parseConst.o: localintermediate.h ../Include/intermediate.h
parseConst.o: ../Public/ShaderLang.h
InfoSink.o: ../Include/InfoSink.h

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,150 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
#ifndef _PARSER_HELPER_INCLUDED_
#define _PARSER_HELPER_INCLUDED_
#include "../Include/ShHandle.h"
#include "SymbolTable.h"
#include "localintermediate.h"
struct TMatrixFields {
bool wholeRow;
bool wholeCol;
int row;
int col;
};
typedef enum {
EBhRequire,
EBhEnable,
EBhWarn,
EBhDisable
} TBehavior;
struct TPragma {
TPragma(bool o, bool d) : optimize(o), debug(d) { }
bool optimize;
bool debug;
TPragmaTable pragmaTable;
};
//
// The following are extra variables needed during parsing, grouped together so
// they can be passed to the parser without needing a global.
//
struct TParseContext {
TParseContext(TSymbolTable& symt, TIntermediate& interm, EShLanguage L, TInfoSink& is) :
intermediate(interm), symbolTable(symt), infoSink(is), language(L), treeRoot(0),
recoveredFromError(false), numErrors(0), lexAfterType(false), loopNestingLevel(0),
inTypeParen(false), contextPragma(true, false) { }
TIntermediate& intermediate; // to hold and build a parse tree
TSymbolTable& symbolTable; // symbol table that goes with the language currently being parsed
TInfoSink& infoSink;
EShLanguage language; // vertex or fragment language (future: pack or unpack)
TIntermNode* treeRoot; // root of parse tree being created
bool recoveredFromError; // true if a parse error has occurred, but we continue to parse
int numErrors;
bool lexAfterType; // true if we've recognized a type, so can only be looking for an identifier
int loopNestingLevel; // 0 if outside all loops
bool inTypeParen; // true if in parentheses, looking only for an identifier
const TType* currentFunctionType; // the return type of the function that's currently being parsed
bool functionReturnsValue; // true if a non-void function has a return
TMap<TString, TBehavior> extensionBehavior;
void initializeExtensionBehavior();
void C_DECL error(TSourceLoc, const char *szReason, const char *szToken,
const char *szExtraInfoFormat, ...);
bool reservedErrorCheck(int line, const TString& identifier);
void recover();
bool parseVectorFields(const TString&, int vecSize, TVectorFields&, int line);
bool parseMatrixFields(const TString&, int matSize, TMatrixFields&, int line);
void assignError(int line, const char* op, TString left, TString right);
void unaryOpError(int line, char* op, TString operand);
void binaryOpError(int line, char* op, TString left, TString right);
bool lValueErrorCheck(int line, char* op, TIntermTyped*);
bool constErrorCheck(TIntermTyped* node);
bool integerErrorCheck(TIntermTyped* node, char* token);
bool globalErrorCheck(int line, bool global, char* token);
bool constructorErrorCheck(int line, TIntermNode*, TFunction&, TOperator, TType*);
bool arraySizeErrorCheck(int line, TIntermTyped* expr, int& size);
bool arrayQualifierErrorCheck(int line, TPublicType type);
bool arrayTypeErrorCheck(int line, TPublicType type);
bool arrayErrorCheck(int line, TString& identifier, TPublicType type, TVariable*& variable);
bool insertBuiltInArrayAtGlobalLevel();
bool voidErrorCheck(int, const TString&, const TPublicType&);
bool boolErrorCheck(int, const TIntermTyped*);
bool boolErrorCheck(int, const TPublicType&);
bool samplerErrorCheck(int line, const TPublicType& pType, const char* reason);
bool structQualifierErrorCheck(int line, const TPublicType& pType);
bool parameterSamplerErrorCheck(int line, TQualifier qualifier, const TType& type);
bool containsSampler(TType& type);
bool nonInitConstErrorCheck(int line, TString& identifier, TPublicType& type);
bool nonInitErrorCheck(int line, TString& identifier, TPublicType& type);
bool paramErrorCheck(int line, TQualifier qualifier, TQualifier paramQualifier, TType* type);
bool extensionErrorCheck(int line, const char*);
const TFunction* findFunction(int line, TFunction* pfnCall, bool *builtIn = 0);
bool executeInitializer(TSourceLoc line, TString& identifier, TPublicType& pType,
TIntermTyped* initializer, TIntermNode*& intermNode, TVariable* variable = 0);
bool areAllChildConst(TIntermAggregate* aggrNode);
TIntermTyped* addConstructor(TIntermNode*, const TType*, TOperator, TFunction*, TSourceLoc);
TIntermTyped* foldConstConstructor(TIntermAggregate* aggrNode, const TType& type);
TIntermTyped* constructStruct(TIntermNode*, TType*, int, TSourceLoc, bool subset);
TIntermTyped* constructBuiltIn(const TType*, TOperator, TIntermNode*, TSourceLoc, bool subset);
TIntermTyped* addConstVectorNode(TVectorFields&, TIntermTyped*, TSourceLoc);
TIntermTyped* addConstMatrixNode(int , TIntermTyped*, TSourceLoc);
TIntermTyped* addConstArrayNode(int index, TIntermTyped* node, TSourceLoc line);
TIntermTyped* addConstStruct(TString& , TIntermTyped*, TSourceLoc);
bool arraySetMaxSize(TIntermSymbol*, TType*, int, bool, TSourceLoc);
struct TPragma contextPragma;
TString HashErrMsg;
bool AfterEOF;
};
int PaParseStrings(char* argv[], int strLen[], int argc, TParseContext&);
void PaReservedWord();
int PaIdentOrType(TString& id, TParseContext&, TSymbol*&);
int PaParseComment(int &lineno, TParseContext&);
void setInitialState();
typedef TParseContext* TParseContextPointer;
extern TParseContextPointer& GetGlobalParseContext();
#define GlobalParseContext GetGlobalParseContext()
typedef struct TThreadParseContextRec
{
TParseContext *lpGlobalParseContext;
} TThreadParseContext;
#endif // _PARSER_HELPER_INCLUDED_

View file

@ -0,0 +1,342 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
#include "../Include/PoolAlloc.h"
#include "../Include/Common.h"
#include "Include/InitializeGlobals.h"
#include "osinclude.h"
OS_TLSIndex PoolIndex;
void InitializeGlobalPools()
{
TThreadGlobalPools* globalPools= static_cast<TThreadGlobalPools*>(OS_GetTLSValue(PoolIndex));
if (globalPools)
return;
TPoolAllocator *globalPoolAllocator = new TPoolAllocator(true);
TThreadGlobalPools* threadData = new TThreadGlobalPools();
threadData->globalPoolAllocator = globalPoolAllocator;
OS_SetTLSValue(PoolIndex, threadData);
globalPoolAllocator->push();
}
void FreeGlobalPools()
{
// Release the allocated memory for this thread.
TThreadGlobalPools* globalPools= static_cast<TThreadGlobalPools*>(OS_GetTLSValue(PoolIndex));
if (!globalPools)
return;
GlobalPoolAllocator.popAll();
delete &GlobalPoolAllocator;
delete globalPools;
}
bool InitializePoolIndex()
{
// Allocate a TLS index.
if ((PoolIndex = OS_AllocTLSIndex()) == OS_INVALID_TLS_INDEX)
return false;
return true;
}
void FreePoolIndex()
{
// Release the TLS index.
OS_FreeTLSIndex(PoolIndex);
}
TPoolAllocator& GetGlobalPoolAllocator()
{
TThreadGlobalPools* threadData = static_cast<TThreadGlobalPools*>(OS_GetTLSValue(PoolIndex));
return *threadData->globalPoolAllocator;
}
void SetGlobalPoolAllocatorPtr(TPoolAllocator* poolAllocator)
{
TThreadGlobalPools* threadData = static_cast<TThreadGlobalPools*>(OS_GetTLSValue(PoolIndex));
threadData->globalPoolAllocator = poolAllocator;
}
//
// Implement the functionality of the TPoolAllocator class, which
// is documented in PoolAlloc.h.
//
TPoolAllocator::TPoolAllocator(bool g, int growthIncrement, int allocationAlignment) :
global(g),
pageSize(growthIncrement),
alignment(allocationAlignment),
freeList(0),
inUseList(0),
numCalls(0)
{
//
// Don't allow page sizes we know are smaller than all common
// OS page sizes.
//
if (pageSize < 4*1024)
pageSize = 4*1024;
//
// A large currentPageOffset indicates a new page needs to
// be obtained to allocate memory.
//
currentPageOffset = pageSize;
//
// Adjust alignment to be at least pointer aligned and
// power of 2.
//
size_t minAlign = sizeof(void*);
alignment &= ~(minAlign - 1);
if (alignment < minAlign)
alignment = minAlign;
size_t a = 1;
while (a < alignment)
a <<= 1;
alignment = a;
alignmentMask = a - 1;
//
// Align header skip
//
headerSkip = minAlign;
if (headerSkip < sizeof(tHeader)) {
headerSkip = (sizeof(tHeader) + alignmentMask) & ~alignmentMask;
}
}
TPoolAllocator::~TPoolAllocator()
{
if (!global) {
//
// Then we know that this object is not being
// allocated after other, globally scoped objects
// that depend on it. So we can delete the "in use" memory.
//
while (inUseList) {
tHeader* next = inUseList->nextPage;
inUseList->~tHeader();
delete [] reinterpret_cast<char*>(inUseList);
inUseList = next;
}
}
//
// Always delete the free list memory - it can't be being
// (correctly) referenced, whether the pool allocator was
// global or not. We should not check the guard blocks
// here, because we did it already when the block was
// placed into the free list.
//
while (freeList) {
tHeader* next = freeList->nextPage;
delete [] reinterpret_cast<char*>(freeList);
freeList = next;
}
}
// Support MSVC++ 6.0
const unsigned char TAllocation::guardBlockBeginVal = 0xfb;
const unsigned char TAllocation::guardBlockEndVal = 0xfe;
const unsigned char TAllocation::userDataFill = 0xcd;
# ifdef GUARD_BLOCKS
const size_t TAllocation::guardBlockSize = 16;
# else
const size_t TAllocation::guardBlockSize = 0;
# endif
//
// Check a single guard block for damage
//
void TAllocation::checkGuardBlock(unsigned char* blockMem, unsigned char val, char* locText) const
{
for (int x = 0; x < guardBlockSize; x++) {
if (blockMem[x] != val) {
char assertMsg[80];
// We don't print the assert message. It's here just to be helpful.
sprintf(assertMsg, "PoolAlloc: Damage %s %lu byte allocation at 0x%p\n",
locText, size, data());
assert(0 && "PoolAlloc: Damage in guard block");
}
}
}
void TPoolAllocator::push()
{
tAllocState state = { currentPageOffset, inUseList };
stack.push_back(state);
//
// Indicate there is no current page to allocate from.
//
currentPageOffset = pageSize;
}
//
// Do a mass-deallocation of all the individual allocations
// that have occurred since the last push(), or since the
// last pop(), or since the object's creation.
//
// The deallocated pages are saved for future allocations.
//
void TPoolAllocator::pop()
{
if (stack.size() < 1)
return;
tHeader* page = stack.back().page;
currentPageOffset = stack.back().offset;
while (inUseList != page) {
// invoke destructor to free allocation list
inUseList->~tHeader();
tHeader* nextInUse = inUseList->nextPage;
if (inUseList->pageCount > 1)
delete [] reinterpret_cast<char*>(inUseList);
else {
inUseList->nextPage = freeList;
freeList = inUseList;
}
inUseList = nextInUse;
}
stack.pop_back();
}
//
// Do a mass-deallocation of all the individual allocations
// that have occurred.
//
void TPoolAllocator::popAll()
{
while (stack.size() > 0)
pop();
}
void* TPoolAllocator::allocate(size_t numBytes)
{
// If we are using guard blocks, all allocations are bracketed by
// them: [guardblock][allocation][guardblock]. numBytes is how
// much memory the caller asked for. allocationSize is the total
// size including guard blocks. In release build,
// guardBlockSize=0 and this all gets optimized away.
size_t allocationSize = TAllocation::allocationSize(numBytes);
//
// Just keep some interesting statistics.
//
++numCalls;
totalBytes += numBytes;
//
// Do the allocation, most likely case first, for efficiency.
// This step could be moved to be inline sometime.
//
if (currentPageOffset + allocationSize <= pageSize) {
//
// Safe to allocate from currentPageOffset.
//
unsigned char* memory = reinterpret_cast<unsigned char *>(inUseList) + currentPageOffset;
currentPageOffset += allocationSize;
currentPageOffset = (currentPageOffset + alignmentMask) & ~alignmentMask;
return initializeAllocation(inUseList, memory, numBytes);
}
if (allocationSize + headerSkip > pageSize) {
//
// Do a multi-page allocation. Don't mix these with the others.
// The OS is efficient and allocating and free-ing multiple pages.
//
size_t numBytesToAlloc = allocationSize + headerSkip;
tHeader* memory = reinterpret_cast<tHeader*>(::new char[numBytesToAlloc]);
if (memory == 0)
return 0;
// Use placement-new to initialize header
new(memory) tHeader(inUseList, (numBytesToAlloc + pageSize - 1) / pageSize);
inUseList = memory;
currentPageOffset = pageSize; // make next allocation come from a new page
// No guard blocks for multi-page allocations (yet)
return reinterpret_cast<void*>(reinterpret_cast<UINT_PTR>(memory) + headerSkip);
}
//
// Need a simple page to allocate from.
//
tHeader* memory;
if (freeList) {
memory = freeList;
freeList = freeList->nextPage;
} else {
memory = reinterpret_cast<tHeader*>(::new char[pageSize]);
if (memory == 0)
return 0;
}
// Use placement-new to initialize header
new(memory) tHeader(inUseList, 1);
inUseList = memory;
unsigned char* ret = reinterpret_cast<unsigned char *>(inUseList) + headerSkip;
currentPageOffset = (headerSkip + allocationSize + alignmentMask) & ~alignmentMask;
return initializeAllocation(inUseList, ret, numBytes);
}
//
// Check all allocations in a list for damage by calling check on each.
//
void TAllocation::checkAllocList() const
{
for (const TAllocation* alloc = this; alloc != 0; alloc = alloc->prevAlloc)
alloc->check();
}

View file

@ -0,0 +1,91 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
#include "../Include/intermediate.h"
class TAliveTraverser : public TIntermTraverser {
public:
TAliveTraverser(TQualifier q) : TIntermTraverser(), found(false), qualifier(q)
{
visitSymbol = AliveSymbol;
visitSelection = AliveSelection;
rightToLeft = true;
}
bool wasFound() { return found; }
protected:
bool found;
TQualifier qualifier;
friend void AliveSymbol(TIntermSymbol*, TIntermTraverser*);
friend bool AliveSelection(bool, TIntermSelection*, TIntermTraverser*);
};
//
// Report whether or not a variable of the given qualifier type
// is guaranteed written. Not always possible to determine if
// it is written conditionally.
//
// ?? It does not do this well yet, this is just a place holder
// that simply determines if it was reference at all, anywhere.
//
bool QualifierWritten(TIntermNode* node, TQualifier qualifier)
{
TAliveTraverser it(qualifier);
if (node)
node->traverse(&it);
return it.wasFound();
}
void AliveSymbol(TIntermSymbol* node, TIntermTraverser* it)
{
TAliveTraverser* lit = static_cast<TAliveTraverser*>(it);
//
// If it's what we're looking for, record it.
//
if (node->getQualifier() == lit->qualifier)
lit->found = true;
}
bool AliveSelection(bool preVisit, TIntermSelection* node, TIntermTraverser* it)
{
TAliveTraverser* lit = static_cast<TAliveTraverser*>(it);
if (lit->wasFound())
return false;
return true;
}

View file

@ -0,0 +1,35 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
bool QualifierWritten(TIntermNode* root, TQualifier);

View file

@ -0,0 +1,98 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
#include "../Include/intermediate.h"
#include "RemoveTree.h"
//
// Code to recursively delete the intermediate tree.
//
void RemoveSymbol(TIntermSymbol* node, TIntermTraverser* it)
{
delete node;
}
bool RemoveBinary(bool /*preVisit*/ , TIntermBinary* node, TIntermTraverser*)
{
delete node;
return true;
}
bool RemoveUnary(bool /*preVisit */, TIntermUnary* node, TIntermTraverser*)
{
delete node;
return true;
}
bool RemoveAggregate(bool /*preVisit*/ , TIntermAggregate* node, TIntermTraverser*)
{
delete node;
return true;
}
bool RemoveSelection(bool /*preVisit*/ , TIntermSelection* node, TIntermTraverser*)
{
delete node;
return true;
}
void RemoveConstantUnion(TIntermConstantUnion* node, TIntermTraverser*)
{
delete node;
}
//
// Entry point.
//
void RemoveAllTreeNodes(TIntermNode* root)
{
TIntermTraverser it;
it.visitAggregate = RemoveAggregate;
it.visitBinary = RemoveBinary;
it.visitConstantUnion = RemoveConstantUnion;
it.visitSelection = RemoveSelection;
it.visitSymbol = RemoveSymbol;
it.visitUnary = RemoveUnary;
it.preVisit = false;
it.postVisit = true;
root->traverse(&it);
}

View file

@ -0,0 +1,35 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
void RemoveAllTreeNodes(TIntermNode*);

View file

@ -0,0 +1,586 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
//
// Implement the top-level of interface to the compiler/linker,
// as defined in ShaderLang.h
//
#include "SymbolTable.h"
#include "ParseHelper.h"
#include "../Include/ShHandle.h"
#include "InitializeDll.h"
#define SH_EXPORTING
#include "../Public/ShaderLang.h"
#include "Initialize.h"
//
// A symbol table for each language. Each has a different
// set of built-ins, and we want to preserve that from
// compile to compile.
//
TSymbolTable SymbolTables[EShLangCount];
TPoolAllocator* PerProcessGPA = 0;
//
// This is the platform independent interface between an OGL driver
// and the shading language compiler/linker.
//
//
// Driver must call this first, once, before doing any other
// compiler/linker operations.
//
int ShInitialize()
{
TInfoSink infoSink;
bool ret = true;
if (!InitProcess())
return 0;
// This method should be called once per process. If its called by multiple threads, then
// we need to have thread synchronization code around the initialization of per process
// global pool allocator
if (!PerProcessGPA) {
TPoolAllocator *builtInPoolAllocator = new TPoolAllocator(true);
builtInPoolAllocator->push();
TPoolAllocator* gPoolAllocator = &GlobalPoolAllocator;
SetGlobalPoolAllocatorPtr(builtInPoolAllocator);
TSymbolTable symTables[EShLangCount];
GenerateBuiltInSymbolTable(0, infoSink, symTables);
PerProcessGPA = new TPoolAllocator(true);
PerProcessGPA->push();
SetGlobalPoolAllocatorPtr(PerProcessGPA);
SymbolTables[EShLangVertex].copyTable(symTables[EShLangVertex]);
SymbolTables[EShLangFragment].copyTable(symTables[EShLangFragment]);
SetGlobalPoolAllocatorPtr(gPoolAllocator);
symTables[EShLangVertex].pop();
symTables[EShLangFragment].pop();
builtInPoolAllocator->popAll();
delete builtInPoolAllocator;
}
return ret ? 1 : 0;
}
//
// Driver calls these to create and destroy compiler/linker
// objects.
//
ShHandle ShConstructCompiler(const EShLanguage language, int debugOptions)
{
if (!InitThread())
return 0;
TShHandleBase* base = static_cast<TShHandleBase*>(ConstructCompiler(language, debugOptions));
return reinterpret_cast<void*>(base);
}
ShHandle ShConstructLinker(const EShExecutable executable, int debugOptions)
{
if (!InitThread())
return 0;
TShHandleBase* base = static_cast<TShHandleBase*>(ConstructLinker(executable, debugOptions));
return reinterpret_cast<void*>(base);
}
ShHandle ShConstructUniformMap()
{
if (!InitThread())
return 0;
TShHandleBase* base = static_cast<TShHandleBase*>(ConstructUniformMap());
return reinterpret_cast<void*>(base);
}
void ShDestruct(ShHandle handle)
{
if (handle == 0)
return;
TShHandleBase* base = static_cast<TShHandleBase*>(handle);
if (base->getAsCompiler())
DeleteCompiler(base->getAsCompiler());
else if (base->getAsLinker())
DeleteLinker(base->getAsLinker());
else if (base->getAsUniformMap())
DeleteUniformMap(base->getAsUniformMap());
}
//
// Cleanup symbol tables
//
int __fastcall ShFinalize()
{
if (PerProcessGPA) {
PerProcessGPA->popAll();
delete PerProcessGPA;
}
return 1;
}
bool GenerateBuiltInSymbolTable(const TBuiltInResource* resources, TInfoSink& infoSink, TSymbolTable* symbolTables, EShLanguage language)
{
TBuiltIns builtIns;
if (resources) {
builtIns.initialize(*resources);
InitializeSymbolTable(builtIns.getBuiltInStrings(), language, infoSink, resources, symbolTables);
} else {
builtIns.initialize();
InitializeSymbolTable(builtIns.getBuiltInStrings(), EShLangVertex, infoSink, resources, symbolTables);
InitializeSymbolTable(builtIns.getBuiltInStrings(), EShLangFragment, infoSink, resources, symbolTables);
}
return true;
}
bool InitializeSymbolTable(TBuiltInStrings* BuiltInStrings, EShLanguage language, TInfoSink& infoSink, const TBuiltInResource* resources, TSymbolTable* symbolTables)
{
TIntermediate intermediate(infoSink);
TSymbolTable* symbolTable;
if (resources)
symbolTable = symbolTables;
else
symbolTable = &symbolTables[language];
TParseContext parseContext(*symbolTable, intermediate, language, infoSink);
GlobalParseContext = &parseContext;
setInitialState();
assert(symbolTable->isEmpty() || symbolTable->atSharedBuiltInLevel());
//
// Parse the built-ins. This should only happen once per
// language symbol table.
//
// Push the symbol table to give it an initial scope. This
// push should not have a corresponding pop, so that built-ins
// are preserved, and the test for an empty table fails.
//
symbolTable->push();
//Initialize the Preprocessor
int ret = InitPreprocessor();
if (ret) {
infoSink.info.message(EPrefixInternalError, "Unable to intialize the Preprocessor");
return false;
}
for (TBuiltInStrings::iterator i = BuiltInStrings[parseContext.language].begin();
i != BuiltInStrings[parseContext.language].end();
++i) {
const char* builtInShaders[1];
int builtInLengths[1];
builtInShaders[0] = (*i).c_str();
builtInLengths[0] = (int) (*i).size();
if (PaParseStrings(const_cast<char**>(builtInShaders), builtInLengths, 1, parseContext) != 0) {
infoSink.info.message(EPrefixInternalError, "Unable to parse built-ins");
return false;
}
}
if (resources) {
IdentifyBuiltIns(parseContext.language, *symbolTable, *resources);
} else {
IdentifyBuiltIns(parseContext.language, *symbolTable);
}
FinalizePreprocessor();
return true;
}
//
// Do an actual compile on the given strings. The result is left
// in the given compile object.
//
// Return: The return value of ShCompile is really boolean, indicating
// success or failure.
//
int ShCompile(
const ShHandle handle,
const char* const shaderStrings[],
const int numStrings,
const EShOptimizationLevel optLevel,
const TBuiltInResource* resources,
int debugOptions
)
{
if (!InitThread())
return 0;
if (handle == 0)
return 0;
TShHandleBase* base = reinterpret_cast<TShHandleBase*>(handle);
TCompiler* compiler = base->getAsCompiler();
if (compiler == 0)
return 0;
GlobalPoolAllocator.push();
compiler->infoSink.info.erase();
compiler->infoSink.debug.erase();
if (numStrings == 0)
return 1;
TIntermediate intermediate(compiler->infoSink);
TSymbolTable symbolTable(SymbolTables[compiler->getLanguage()]);
GenerateBuiltInSymbolTable(resources, compiler->infoSink, &symbolTable, compiler->getLanguage());
TParseContext parseContext(symbolTable, intermediate, compiler->getLanguage(), compiler->infoSink);
parseContext.initializeExtensionBehavior();
GlobalParseContext = &parseContext;
setInitialState();
InitPreprocessor();
//
// Parse the application's shaders. All the following symbol table
// work will be throw-away, so push a new allocation scope that can
// be thrown away, then push a scope for the current shader's globals.
//
bool success = true;
symbolTable.push();
if (!symbolTable.atGlobalLevel())
parseContext.infoSink.info.message(EPrefixInternalError, "Wrong symbol table level");
if (parseContext.insertBuiltInArrayAtGlobalLevel())
success = false;
int ret = PaParseStrings(const_cast<char**>(shaderStrings), 0, numStrings, parseContext);
if (ret)
success = false;
if (success && parseContext.treeRoot) {
if (optLevel == EShOptNoGeneration)
parseContext.infoSink.info.message(EPrefixNone, "No errors. No code generation or linking was requested.");
else {
success = intermediate.postProcess(parseContext.treeRoot, parseContext.language);
if (success) {
if (debugOptions & EDebugOpIntermediate)
intermediate.outputTree(parseContext.treeRoot);
//
// Call the machine dependent compiler
//
if (! compiler->compile(parseContext.treeRoot))
success = false;
}
}
} else if (!success) {
parseContext.infoSink.info.prefix(EPrefixError);
parseContext.infoSink.info << parseContext.numErrors << " compilation errors. No code generated.\n\n";
success = false;
if (debugOptions & EDebugOpIntermediate)
intermediate.outputTree(parseContext.treeRoot);
}
intermediate.remove(parseContext.treeRoot);
//
// Ensure symbol table is returned to the built-in level,
// throwing away all but the built-ins.
//
while (! symbolTable.atSharedBuiltInLevel())
symbolTable.pop();
FinalizePreprocessor();
//
// Throw away all the temporary memory used by the compilation process.
//
GlobalPoolAllocator.pop();
return success ? 1 : 0;
}
//
// Do an actual link on the given compile objects.
//
// Return: The return value of is really boolean, indicating
// success or failure.
//
int ShLink(
const ShHandle linkHandle,
const ShHandle compHandles[],
const int numHandles,
ShHandle uniformMapHandle,
short int** uniformsAccessed,
int* numUniformsAccessed)
{
if (!InitThread())
return 0;
TShHandleBase* base = reinterpret_cast<TShHandleBase*>(linkHandle);
TLinker* linker = static_cast<TLinker*>(base->getAsLinker());
if (linker == 0)
return 0;
int returnValue;
GlobalPoolAllocator.push();
returnValue = ShLinkExt(linkHandle, compHandles, numHandles);
GlobalPoolAllocator.pop();
if (returnValue)
return 1;
return 0;
}
//
// This link method will be eventually used once the ICD supports the new linker interface
//
int ShLinkExt(
const ShHandle linkHandle,
const ShHandle compHandles[],
const int numHandles)
{
if (linkHandle == 0 || numHandles == 0)
return 0;
THandleList cObjects;
{// support MSVC++6.0
for (int i = 0; i < numHandles; ++i) {
if (compHandles[i] == 0)
return 0;
TShHandleBase* base = reinterpret_cast<TShHandleBase*>(compHandles[i]);
if (base->getAsLinker()) {
cObjects.push_back(base->getAsLinker());
}
if (base->getAsCompiler())
cObjects.push_back(base->getAsCompiler());
if (cObjects[i] == 0)
return 0;
}
}
TShHandleBase* base = reinterpret_cast<TShHandleBase*>(linkHandle);
TLinker* linker = static_cast<TLinker*>(base->getAsLinker());
if (linker == 0)
return 0;
linker->infoSink.info.erase();
{// support MSVC++6.0
for (int i = 0; i < numHandles; ++i) {
if (cObjects[i]->getAsCompiler()) {
if (! cObjects[i]->getAsCompiler()->linkable()) {
linker->infoSink.info.message(EPrefixError, "Not all shaders have valid object code.");
return 0;
}
}
}
}
bool ret = linker->link(cObjects);
return ret ? 1 : 0;
}
//
// ShSetEncrpytionMethod is a place-holder for specifying
// how source code is encrypted.
//
void ShSetEncryptionMethod(ShHandle handle)
{
if (handle == 0)
return;
}
//
// Return any compiler/linker/uniformmap log of messages for the application.
//
const char* ShGetInfoLog(const ShHandle handle)
{
if (!InitThread())
return 0;
if (handle == 0)
return 0;
TShHandleBase* base = static_cast<TShHandleBase*>(handle);
TInfoSink* infoSink;
if (base->getAsCompiler())
infoSink = &(base->getAsCompiler()->getInfoSink());
else if (base->getAsLinker())
infoSink = &(base->getAsLinker()->getInfoSink());
infoSink->info << infoSink->debug.c_str();
return infoSink->info.c_str();
}
//
// Return the resulting binary code from the link process. Structure
// is machine dependent.
//
const void* ShGetExecutable(const ShHandle handle)
{
if (!InitThread())
return 0;
if (handle == 0)
return 0;
TShHandleBase* base = reinterpret_cast<TShHandleBase*>(handle);
TLinker* linker = static_cast<TLinker*>(base->getAsLinker());
if (linker == 0)
return 0;
return linker->getObjectCode();
}
//
// Let the linker know where the application said it's attributes are bound.
// The linker does not use these values, they are remapped by the ICD or
// hardware. It just needs them to know what's aliased.
//
// Return: The return value of is really boolean, indicating
// success or failure.
//
int ShSetVirtualAttributeBindings(const ShHandle handle, const ShBindingTable* table)
{
if (!InitThread())
return 0;
if (handle == 0)
return 0;
TShHandleBase* base = reinterpret_cast<TShHandleBase*>(handle);
TLinker* linker = static_cast<TLinker*>(base->getAsLinker());
if (linker == 0)
return 0;
linker->setAppAttributeBindings(table);
return 1;
}
//
// Let the linker know where the predefined attributes have to live.
//
int ShSetFixedAttributeBindings(const ShHandle handle, const ShBindingTable* table)
{
if (!InitThread())
return 0;
if (handle == 0)
return 0;
TShHandleBase* base = reinterpret_cast<TShHandleBase*>(handle);
TLinker* linker = static_cast<TLinker*>(base->getAsLinker());
if (linker == 0)
return 0;
linker->setFixedAttributeBindings(table);
return 1;
}
//
// Some attribute locations are off-limits to the linker...
//
int ShExcludeAttributes(const ShHandle handle, int *attributes, int count)
{
if (!InitThread())
return 0;
if (handle == 0)
return 0;
TShHandleBase* base = reinterpret_cast<TShHandleBase*>(handle);
TLinker* linker = static_cast<TLinker*>(base->getAsLinker());
if (linker == 0)
return 0;
linker->setExcludedAttributes(attributes, count);
return 1;
}
//
// Return the index for OpenGL to use for knowing where a uniform lives.
//
// Return: The return value of is really boolean, indicating
// success or failure.
//
int ShGetUniformLocation(const ShHandle handle, const char* name)
{
if (!InitThread())
return 0;
if (handle == 0)
return -1;
TShHandleBase* base = reinterpret_cast<TShHandleBase*>(handle);
TUniformMap* uniformMap= base->getAsUniformMap();
if (uniformMap == 0)
return -1;
return uniformMap->getLocation(name);
}

View file

@ -0,0 +1,245 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
//
// Symbol table for parsing. Most functionaliy and main ideas
// are documented in the header file.
//
#include "SymbolTable.h"
//
// TType helper function needs a place to live.
//
//
// Recursively generate mangled names.
//
void TType::buildMangledName(TString& mangledName)
{
if (isMatrix())
mangledName += 'm';
else if (isVector())
mangledName += 'v';
switch (type) {
case EbtFloat: mangledName += 'f'; break;
case EbtInt: mangledName += 'i'; break;
case EbtBool: mangledName += 'b'; break;
case EbtSampler1D: mangledName += "s1"; break;
case EbtSampler2D: mangledName += "s2"; break;
case EbtSampler3D: mangledName += "s3"; break;
case EbtSamplerCube: mangledName += "sC"; break;
case EbtSampler1DShadow: mangledName += "sS1"; break;
case EbtSampler2DShadow: mangledName += "sS2"; break;
case EbtSamplerRect: mangledName += "sR2"; break; // ARB_texture_rectangle
case EbtSamplerRectShadow: mangledName += "sSR2"; break; // ARB_texture_rectangle
case EbtStruct:
mangledName += "struct-";
if (typeName)
mangledName += *typeName;
{// support MSVC++6.0
for (unsigned int i = 0; i < structure->size(); ++i) {
mangledName += '-';
(*structure)[i].type->buildMangledName(mangledName);
}
}
default:
break;
}
mangledName += static_cast<char>('0' + getNominalSize());
if (isArray()) {
char buf[10];
sprintf(buf, "%d", arraySize);
mangledName += '[';
mangledName += buf;
mangledName += ']';
}
}
int TType::getStructSize() const
{
if (!getStruct()) {
assert(false && "Not a struct");
return 0;
}
if (structureSize == 0)
for (TTypeList::iterator tl = getStruct()->begin(); tl != getStruct()->end(); tl++)
structureSize += ((*tl).type)->getObjectSize();
return structureSize;
}
//
// Dump functions.
//
void TVariable::dump(TInfoSink& infoSink) const
{
infoSink.debug << getName().c_str() << ": " << type.getQualifierString() << " " << type.getBasicString();
if (type.isArray()) {
infoSink.debug << "[0]";
}
infoSink.debug << "\n";
}
void TFunction::dump(TInfoSink &infoSink) const
{
infoSink.debug << getName().c_str() << ": " << returnType.getBasicString() << " " << getMangledName().c_str() << "\n";
}
void TSymbolTableLevel::dump(TInfoSink &infoSink) const
{
tLevel::const_iterator it;
for (it = level.begin(); it != level.end(); ++it)
(*it).second->dump(infoSink);
}
void TSymbolTable::dump(TInfoSink &infoSink) const
{
for (int level = currentLevel(); level >= 0; --level) {
infoSink.debug << "LEVEL " << level << "\n";
table[level]->dump(infoSink);
}
}
//
// Functions have buried pointers to delete.
//
TFunction::~TFunction()
{
for (TParamList::iterator i = parameters.begin(); i != parameters.end(); ++i)
delete (*i).type;
}
//
// Symbol table levels are a map of pointers to symbols that have to be deleted.
//
TSymbolTableLevel::~TSymbolTableLevel()
{
for (tLevel::iterator it = level.begin(); it != level.end(); ++it)
delete (*it).second;
}
//
// Change all function entries in the table with the non-mangled name
// to be related to the provided built-in operation. This is a low
// performance operation, and only intended for symbol tables that
// live across a large number of compiles.
//
void TSymbolTableLevel::relateToOperator(const char* name, TOperator op)
{
tLevel::iterator it;
for (it = level.begin(); it != level.end(); ++it) {
if ((*it).second->isFunction()) {
TFunction* function = static_cast<TFunction*>((*it).second);
if (function->getName() == name)
function->relateToOperator(op);
}
}
}
TSymbol::TSymbol(const TSymbol& copyOf)
{
name = NewPoolTString(copyOf.name->c_str());
uniqueId = copyOf.uniqueId;
}
TVariable::TVariable(const TVariable& copyOf, TStructureMap& remapper) : TSymbol(copyOf)
{
type.copyType(copyOf.type, remapper);
userType = copyOf.userType;
// for builtIn symbol table level, unionArray and arrayInformation pointers should be NULL
assert(copyOf.arrayInformationType == 0);
arrayInformationType = 0;
if (copyOf.unionArray) {
assert(!copyOf.type.getStruct());
assert(copyOf.type.getObjectSize() == 1);
unionArray = new constUnion[1];
unionArray[0] = copyOf.unionArray[0];
} else
unionArray = 0;
}
TVariable* TVariable::clone(TStructureMap& remapper)
{
TVariable *variable = new TVariable(*this, remapper);
return variable;
}
TFunction::TFunction(const TFunction& copyOf, TStructureMap& remapper) : TSymbol(copyOf)
{
for (unsigned int i = 0; i < copyOf.parameters.size(); ++i) {
TParameter param;
parameters.push_back(param);
parameters.back().copyParam(copyOf.parameters[i], remapper);
}
returnType.copyType(copyOf.returnType, remapper);
mangledName = copyOf.mangledName;
op = copyOf.op;
defined = copyOf.defined;
}
TFunction* TFunction::clone(TStructureMap& remapper)
{
TFunction *function = new TFunction(*this, remapper);
return function;
}
TSymbolTableLevel* TSymbolTableLevel::clone(TStructureMap& remapper)
{
TSymbolTableLevel *symTableLevel = new TSymbolTableLevel();
tLevel::iterator iter;
for (iter = level.begin(); iter != level.end(); ++iter) {
symTableLevel->insert(*iter->second->clone(remapper));
}
return symTableLevel;
}
void TSymbolTable::copyTable(const TSymbolTable& copyOf)
{
TStructureMap remapper;
uniqueId = copyOf.uniqueId;
for (unsigned int i = 0; i < copyOf.table.size(); ++i) {
table.push_back(copyOf.table[i]->clone(remapper));
}
}

View file

@ -0,0 +1,318 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
#ifndef _SYMBOL_TABLE_INCLUDED_
#define _SYMBOL_TABLE_INCLUDED_
//
// Symbol table for parsing. Has these design characteristics:
//
// * Same symbol table can be used to compile many shaders, to preserve
// effort of creating and loading with the large numbers of built-in
// symbols.
//
// * Name mangling will be used to give each function a unique name
// so that symbol table lookups are never ambiguous. This allows
// a simpler symbol table structure.
//
// * Pushing and popping of scope, so symbol table will really be a stack
// of symbol tables. Searched from the top, with new inserts going into
// the top.
//
// * Constants: Compile time constant symbols will keep their values
// in the symbol table. The parser can substitute constants at parse
// time, including doing constant folding and constant propagation.
//
// * No temporaries: Temporaries made from operations (+, --, .xy, etc.)
// are tracked in the intermediate representation, not the symbol table.
//
#include "Include/Common.h"
#include "Include/intermediate.h"
#include "Include/InfoSink.h"
//
// Symbol base class. (Can build functions or variables out of these...)
//
class TSymbol {
public:
POOL_ALLOCATOR_NEW_DELETE(GlobalPoolAllocator)
TSymbol(const TString *n) : name(n) { }
virtual ~TSymbol() { /* don't delete name, it's from the pool */ }
const TString& getName() const { return *name; }
virtual const TString& getMangledName() const { return getName(); }
virtual bool isFunction() const { return false; }
virtual bool isVariable() const { return false; }
void setUniqueId(int id) { uniqueId = id; }
int getUniqueId() const { return uniqueId; }
virtual void dump(TInfoSink &infoSink) const = 0;
TSymbol(const TSymbol&);
virtual TSymbol* clone(TStructureMap& remapper) = 0;
protected:
const TString *name;
unsigned int uniqueId; // For real comparing during code generation
};
//
// Variable class, meaning a symbol that's not a function.
//
// There could be a separate class heirarchy for Constant variables;
// Only one of int, bool, or float, (or none) is correct for
// any particular use, but it's easy to do this way, and doesn't
// seem worth having separate classes, and "getConst" can't simply return
// different values for different types polymorphically, so this is
// just simple and pragmatic.
//
class TVariable : public TSymbol {
public:
TVariable(const TString *name, const TType& t, bool uT = false ) : TSymbol(name), type(t), userType(uT), unionArray(0), arrayInformationType(0) { }
virtual ~TVariable() { }
virtual bool isVariable() const { return true; }
TType& getType() { return type; }
const TType& getType() const { return type; }
bool isUserType() const { return userType; }
void changeQualifier(TQualifier qualifier) { type.changeQualifier(qualifier); }
void updateArrayInformationType(TType *t) { arrayInformationType = t; }
TType* getArrayInformationType() { return arrayInformationType; }
virtual void dump(TInfoSink &infoSink) const;
constUnion* getConstPointer() {
if (!unionArray)
unionArray = new constUnion[type.getObjectSize()];
return unionArray;
}
constUnion* getConstPointer() const { return unionArray; }
void shareConstPointer( constUnion *constArray)
{
delete unionArray;
unionArray = constArray;
}
TVariable(const TVariable&, TStructureMap& remapper); // copy constructor
virtual TVariable* clone(TStructureMap& remapper);
protected:
TType type;
bool userType;
// we are assuming that Pool Allocator will free the memory allocated to unionArray
// when this object is destroyed
constUnion *unionArray;
TType *arrayInformationType; // this is used for updating maxArraySize in all the references to a given symbol
};
//
// The function sub-class of symbols and the parser will need to
// share this definition of a function parameter.
//
struct TParameter {
TString *name;
TType* type;
void copyParam(const TParameter& param, TStructureMap& remapper) {
name = NewPoolTString(param.name->c_str());
type = param.type->clone(remapper);
}
};
//
// The function sub-class of a symbol.
//
class TFunction : public TSymbol {
public:
TFunction(TOperator o) :
TSymbol(0),
returnType(TType(EbtVoid)),
op(o),
defined(false) { }
TFunction(const TString *name, TType& retType, TOperator tOp = EOpNull) :
TSymbol(name),
returnType(retType),
mangledName(*name + '('),
op(tOp),
defined(false) { }
virtual ~TFunction();
virtual bool isFunction() const { return true; }
void addParameter(TParameter& p)
{
parameters.push_back(p);
mangledName = mangledName + p.type->getMangledName();
}
const TString& getMangledName() const { return mangledName; }
const TType& getReturnType() const { return returnType; }
void relateToOperator(TOperator o) { op = o; }
TOperator getBuiltInOp() const { return op; }
void setDefined() { defined = true; }
bool isDefined() { return defined; }
int getParamCount() const { return static_cast<int>(parameters.size()); }
TParameter& operator [](int i) { return parameters[i]; }
const TParameter& operator [](int i) const { return parameters[i]; }
virtual void dump(TInfoSink &infoSink) const;
TFunction(const TFunction&, TStructureMap& remapper);
virtual TFunction* clone(TStructureMap& remapper);
protected:
typedef TVector<TParameter> TParamList;
TParamList parameters;
TType returnType;
TString mangledName;
TOperator op;
bool defined;
};
class TSymbolTableLevel {
public:
POOL_ALLOCATOR_NEW_DELETE(GlobalPoolAllocator)
TSymbolTableLevel() { }
~TSymbolTableLevel();
bool insert(TSymbol& symbol)
{
//
// returning true means symbol was added to the table
//
tInsertResult result;
result = level.insert(tLevelPair(symbol.getMangledName(), &symbol));
return result.second;
}
TSymbol* find(const TString& name) const
{
tLevel::const_iterator it = level.find(name);
if (it == level.end())
return 0;
else
return (*it).second;
}
void relateToOperator(const char* name, TOperator op);
void dump(TInfoSink &infoSink) const;
TSymbolTableLevel* clone(TStructureMap& remapper);
protected:
typedef std::map<TString, TSymbol*, std::less<TString>, pool_allocator<std::pair<const TString, TSymbol*> > > tLevel;
typedef const tLevel::value_type tLevelPair;
typedef std::pair<tLevel::iterator, bool> tInsertResult;
tLevel level;
};
class TSymbolTable {
public:
TSymbolTable() : uniqueId(0)
{
//
// The symbol table cannot be used until push() is called, but
// the lack of an initial call to push() can be used to detect
// that the symbol table has not been preloaded with built-ins.
//
}
TSymbolTable(TSymbolTable& symTable)
{
table.push_back(symTable.table[0]);
uniqueId = symTable.uniqueId;
}
~TSymbolTable()
{
// level 0 is always built In symbols, so we never pop that out
while (table.size() > 1)
pop();
}
//
// When the symbol table is initialized with the built-ins, there should
// 'push' calls, so that built-ins are at level 0 and the shader
// globals are at level 1.
//
bool isEmpty() { return table.size() == 0; }
bool atBuiltInLevel() { return atSharedBuiltInLevel() || atDynamicBuiltInLevel(); }
bool atSharedBuiltInLevel() { return table.size() == 1; }
bool atGlobalLevel() { return table.size() <= 3; }
void push() {
table.push_back(new TSymbolTableLevel);
}
void pop() {
delete table[currentLevel()];
table.pop_back();
}
bool insert(TSymbol& symbol)
{
symbol.setUniqueId(++uniqueId);
return table[currentLevel()]->insert(symbol);
}
TSymbol* find(const TString& name, bool* builtIn = 0, bool *sameScope = 0)
{
int level = currentLevel();
TSymbol* symbol;
do {
symbol = table[level]->find(name);
--level;
} while (symbol == 0 && level >= 0);
level++;
if (builtIn)
*builtIn = level == 0;
if (sameScope)
*sameScope = level == currentLevel();
return symbol;
}
TSymbolTableLevel* getGlobalLevel() { assert(table.size() >= 3); return table[2]; }
void relateToOperator(const char* name, TOperator op) { table[0]->relateToOperator(name, op); }
int getMaxSymbolId() { return uniqueId; }
void dump(TInfoSink &infoSink) const;
void copyTable(const TSymbolTable& copyOf);
protected:
int currentLevel() const { return static_cast<int>(table.size()) - 1; }
bool atDynamicBuiltInLevel() { return table.size() == 2; }
std::vector<TSymbolTableLevel*> table;
int uniqueId; // for unique identification in code generation
};
#endif // _SYMBOL_TABLE_INCLUDED_

View file

@ -0,0 +1,637 @@
/*
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
*/
/* Based on
ANSI C grammar, Lex specification
In 1985, Jeff Lee published this Lex specification together with a Yacc
grammar for the April 30, 1985 ANSI C draft. Tom Stockfisch reposted
both to net.sources in 1987; that original, as mentioned in the answer
to question 17.25 of the comp.lang.c FAQ, can be ftp'ed from ftp.uu.net,
file usenet/net.sources/ansi.c.grammar.Z.
I intend to keep this version as close to the current C Standard grammar
as possible; please let me know if you discover discrepancies.
Jutta Degener, 1995
*/
D [0-9]
L [a-zA-Z_]
H [a-fA-F0-9]
E [Ee][+-]?{D}+
O [0-7]
%option nounput
%{
#include <stdio.h>
#include <stdlib.h>
#include "ParseHelper.h"
#include "glslang_tab.h"
/* windows only pragma */
#ifdef _MSC_VER
#pragma warning(disable : 4102)
#endif
int yy_input(char* buf, int max_size);
TSourceLoc yylineno;
#ifdef _WIN32
extern int yyparse(TParseContext&);
#define YY_DECL int yylex(YYSTYPE* pyylval, TParseContext& parseContext)
#else
extern int yyparse(void*);
#define YY_DECL int yylex(YYSTYPE* pyylval, void* parseContextLocal)
#define parseContext (*((TParseContext*)(parseContextLocal)))
#endif
#define YY_INPUT(buf,result,max_size) (result = yy_input(buf, max_size))
%}
%option noyywrap
%option never-interactive
%option outfile="Gen_glslang.cpp"
%x FIELDS
%%
<*>"//"[^\n]*"\n" { /* ?? carriage and/or line-feed? */ };
"attribute" { pyylval->lex.line = yylineno; return(ATTRIBUTE); }
"const" { pyylval->lex.line = yylineno; return(CONST_QUAL); }
"uniform" { pyylval->lex.line = yylineno; return(UNIFORM); }
"varying" { pyylval->lex.line = yylineno; return(VARYING); }
"break" { pyylval->lex.line = yylineno; return(BREAK); }
"continue" { pyylval->lex.line = yylineno; return(CONTINUE); }
"do" { pyylval->lex.line = yylineno; return(DO); }
"for" { pyylval->lex.line = yylineno; return(FOR); }
"while" { pyylval->lex.line = yylineno; return(WHILE); }
"if" { pyylval->lex.line = yylineno; return(IF); }
"else" { pyylval->lex.line = yylineno; return(ELSE); }
"in" { pyylval->lex.line = yylineno; return(IN_QUAL); }
"out" { pyylval->lex.line = yylineno; return(OUT_QUAL); }
"inout" { pyylval->lex.line = yylineno; return(INOUT_QUAL); }
"float" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return(FLOAT_TYPE); }
"int" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return(INT_TYPE); }
"void" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return(VOID_TYPE); }
"bool" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return(BOOL_TYPE); }
"true" { pyylval->lex.line = yylineno; pyylval->lex.b = true; return(BOOLCONSTANT); }
"false" { pyylval->lex.line = yylineno; pyylval->lex.b = false; return(BOOLCONSTANT); }
"discard" { pyylval->lex.line = yylineno; return(DISCARD); }
"return" { pyylval->lex.line = yylineno; return(RETURN); }
"mat2" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return(MATRIX2); }
"mat3" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return(MATRIX3); }
"mat4" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return(MATRIX4); }
"vec2" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return (VEC2); }
"vec3" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return (VEC3); }
"vec4" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return (VEC4); }
"ivec2" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return (IVEC2); }
"ivec3" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return (IVEC3); }
"ivec4" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return (IVEC4); }
"bvec2" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return (BVEC2); }
"bvec3" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return (BVEC3); }
"bvec4" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return (BVEC4); }
"sampler1D" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return SAMPLER1D; }
"sampler2D" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return SAMPLER2D; }
"sampler3D" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return SAMPLER3D; }
"samplerCube" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return SAMPLERCUBE; }
"sampler1DShadow" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return SAMPLER1DSHADOW; }
"sampler2DShadow" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return SAMPLER2DSHADOW; }
"sampler2DRect" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return SAMPLERRECTARB; /* ARB_texture_rectangle */ }
"sampler2DRectShadow" { pyylval->lex.line = yylineno; parseContext.lexAfterType = true; return SAMPLERRECTSHADOWARB; /* ARB_texture_rectangle */ }
"struct" { pyylval->lex.line = yylineno; return(STRUCT); }
"asm" { PaReservedWord(); return 0; }
"class" { PaReservedWord(); return 0; }
"union" { PaReservedWord(); return 0; }
"enum" { PaReservedWord(); return 0; }
"typedef" { PaReservedWord(); return 0; }
"template" { PaReservedWord(); return 0; }
"this" { PaReservedWord(); return 0; }
"packed" { PaReservedWord(); return 0; }
"goto" { PaReservedWord(); return 0; }
"switch" { PaReservedWord(); return 0; }
"default" { PaReservedWord(); return 0; }
"inline" { PaReservedWord(); return 0; }
"noinline" { PaReservedWord(); return 0; }
"volatile" { PaReservedWord(); return 0; }
"public" { PaReservedWord(); return 0; }
"static" { PaReservedWord(); return 0; }
"extern" { PaReservedWord(); return 0; }
"external" { PaReservedWord(); return 0; }
"interface" { PaReservedWord(); return 0; }
"long" { PaReservedWord(); return 0; }
"short" { PaReservedWord(); return 0; }
"double" { PaReservedWord(); return 0; }
"half" { PaReservedWord(); return 0; }
"fixed" { PaReservedWord(); return 0; }
"unsigned" { PaReservedWord(); return 0; }
"input" { PaReservedWord(); return 0; }
"output" { PaReservedWord(); return 0; }
"hvec2" { PaReservedWord(); return 0; }
"hvec3" { PaReservedWord(); return 0; }
"hvec4" { PaReservedWord(); return 0; }
"fvec2" { PaReservedWord(); return 0; }
"fvec3" { PaReservedWord(); return 0; }
"fvec4" { PaReservedWord(); return 0; }
"dvec2" { PaReservedWord(); return 0; }
"dvec3" { PaReservedWord(); return 0; }
"dvec4" { PaReservedWord(); return 0; }
"sampler3DRect" { PaReservedWord(); return 0; }
"sizeof" { PaReservedWord(); return 0; }
"cast" { PaReservedWord(); return 0; }
"namespace" { PaReservedWord(); return 0; }
"using" { PaReservedWord(); return 0; }
{L}({L}|{D})* {
pyylval->lex.line = yylineno;
pyylval->lex.string = NewPoolTString(yytext);
return PaIdentOrType(*pyylval->lex.string, parseContext, pyylval->lex.symbol);
}
0[xX]{H}+ { pyylval->lex.line = yylineno; pyylval->lex.i = strtol(yytext, 0, 0); return(INTCONSTANT); }
0{O}+ { pyylval->lex.line = yylineno; pyylval->lex.i = strtol(yytext, 0, 0); return(INTCONSTANT); }
0{D}+ { pyylval->lex.line = yylineno; parseContext.error(yylineno, "Invalid Octal number.", yytext, "", ""); parseContext.recover(); return 0;}
{D}+ { pyylval->lex.line = yylineno; pyylval->lex.i = strtol(yytext, 0, 0); return(INTCONSTANT); }
{D}+{E} { pyylval->lex.line = yylineno; pyylval->lex.f = static_cast<float>(atof(yytext)); return(FLOATCONSTANT); }
{D}+"."{D}*({E})? { pyylval->lex.line = yylineno; pyylval->lex.f = static_cast<float>(atof(yytext)); return(FLOATCONSTANT); }
"."{D}+({E})? { pyylval->lex.line = yylineno; pyylval->lex.f = static_cast<float>(atof(yytext)); return(FLOATCONSTANT); }
"/*" { int ret = PaParseComment(pyylval->lex.line, parseContext); if (!ret) return ret; }
"+=" { pyylval->lex.line = yylineno; return(ADD_ASSIGN); }
"-=" { pyylval->lex.line = yylineno; return(SUB_ASSIGN); }
"*=" { pyylval->lex.line = yylineno; return(MUL_ASSIGN); }
"/=" { pyylval->lex.line = yylineno; return(DIV_ASSIGN); }
"%=" { pyylval->lex.line = yylineno; return(MOD_ASSIGN); }
"<<=" { pyylval->lex.line = yylineno; return(LEFT_ASSIGN); }
">>=" { pyylval->lex.line = yylineno; return(RIGHT_ASSIGN); }
"&=" { pyylval->lex.line = yylineno; return(AND_ASSIGN); }
"^=" { pyylval->lex.line = yylineno; return(XOR_ASSIGN); }
"|=" { pyylval->lex.line = yylineno; return(OR_ASSIGN); }
"++" { pyylval->lex.line = yylineno; return(INC_OP); }
"--" { pyylval->lex.line = yylineno; return(DEC_OP); }
"&&" { pyylval->lex.line = yylineno; return(AND_OP); }
"||" { pyylval->lex.line = yylineno; return(OR_OP); }
"^^" { pyylval->lex.line = yylineno; return(XOR_OP); }
"<=" { pyylval->lex.line = yylineno; return(LE_OP); }
">=" { pyylval->lex.line = yylineno; return(GE_OP); }
"==" { pyylval->lex.line = yylineno; return(EQ_OP); }
"!=" { pyylval->lex.line = yylineno; return(NE_OP); }
"<<" { pyylval->lex.line = yylineno; return(LEFT_OP); }
">>" { pyylval->lex.line = yylineno; return(RIGHT_OP); }
";" { pyylval->lex.line = yylineno; parseContext.lexAfterType = false; return(SEMICOLON); }
("{"|"<%") { pyylval->lex.line = yylineno; parseContext.lexAfterType = false; return(LEFT_BRACE); }
("}"|"%>") { pyylval->lex.line = yylineno; return(RIGHT_BRACE); }
"," { pyylval->lex.line = yylineno; if (parseContext.inTypeParen) parseContext.lexAfterType = false; return(COMMA); }
":" { pyylval->lex.line = yylineno; return(COLON); }
"=" { pyylval->lex.line = yylineno; parseContext.lexAfterType = false; return(EQUAL); }
"(" { pyylval->lex.line = yylineno; parseContext.lexAfterType = false; parseContext.inTypeParen = true; return(LEFT_PAREN); }
")" { pyylval->lex.line = yylineno; parseContext.inTypeParen = false; return(RIGHT_PAREN); }
("["|"<:") { pyylval->lex.line = yylineno; return(LEFT_BRACKET); }
("]"|":>") { pyylval->lex.line = yylineno; return(RIGHT_BRACKET); }
"." { BEGIN(FIELDS); return(DOT); }
"!" { pyylval->lex.line = yylineno; return(BANG); }
"-" { pyylval->lex.line = yylineno; return(DASH); }
"~" { pyylval->lex.line = yylineno; return(TILDE); }
"+" { pyylval->lex.line = yylineno; return(PLUS); }
"*" { pyylval->lex.line = yylineno; return(STAR); }
"/" { pyylval->lex.line = yylineno; return(SLASH); }
"%" { pyylval->lex.line = yylineno; return(PERCENT); }
"<" { pyylval->lex.line = yylineno; return(LEFT_ANGLE); }
">" { pyylval->lex.line = yylineno; return(RIGHT_ANGLE); }
"|" { pyylval->lex.line = yylineno; return(VERTICAL_BAR); }
"^" { pyylval->lex.line = yylineno; return(CARET); }
"&" { pyylval->lex.line = yylineno; return(AMPERSAND); }
"?" { pyylval->lex.line = yylineno; return(QUESTION); }
<FIELDS>{L}({L}|{D})* {
BEGIN(INITIAL);
pyylval->lex.line = yylineno;
pyylval->lex.string = NewPoolTString(yytext);
return FIELD_SELECTION; }
<FIELDS>[ \t\v\f\r] {}
[ \t\v\n\f\r] { }
<*><<EOF>> { (&parseContext)->AfterEOF = true; yy_delete_buffer(YY_CURRENT_BUFFER); yyterminate();}
<*>. { parseContext.infoSink.info << "FLEX: Unknown char " << yytext << "\n";
return 0; }
%%
//Including Pre-processor.
extern "C" {
#include "./preprocessor/preprocess.h"
}
//
// The YY_INPUT macro just calls this. Maybe this could be just put into
// the macro directly.
//
int yy_input(char* buf, int max_size)
{
char *char_token =NULL;
int len;
if ((len = yylex_CPP(buf, max_size)) == 0)
return 0;
if (len >= max_size)
YY_FATAL_ERROR( "input buffer overflow, can't enlarge buffer because scanner uses REJECT" );
buf[len] = ' ';
return len+1;
}
//
// Parse an array of strings using yyparse. We set up globals used by
// yywrap.
//
// Returns 0 for success, as per yyparse().
//
int PaParseStrings(char* argv[], int strLen[], int argc, TParseContext& parseContextLocal)
{
int argv0len;
ScanFromString(argv[0]);
//Storing the Current Compiler Parse context into the cpp structure.
cpp->pC = (void*)&parseContextLocal;
if (!argv || argc == 0)
return 1;
for (int i = 0; i < argc; ++i) {
if (!argv[i]) {
parseContextLocal.error(0, "Null shader source string", "", "");
parseContextLocal.recover();
return 1;
}
}
if (!strLen) {
argv0len = (int) strlen(argv[0]);
strLen = &argv0len;
}
yyrestart(0);
(&parseContextLocal)->AfterEOF = false;
cpp->PaWhichStr = 0;
cpp->PaArgv = argv;
cpp->PaArgc = argc;
cpp->PaStrLen = strLen;
cpp->notAVersionToken = 0;
yylineno = 1;
if (*cpp->PaStrLen >= 0) {
int ret;
#ifdef _WIN32
ret = yyparse(parseContextLocal);
#else
ret = yyparse((void*)(&parseContextLocal));
#endif
if (cpp->CompileError == 1 || parseContextLocal.recoveredFromError || parseContextLocal.numErrors > 0)
return 1;
else
return 0;
}
else
return 0;
}
void yyerror(char *s)
{
if (((TParseContext *)cpp->pC)->AfterEOF) {
if (cpp->tokensBeforeEOF == 1) {
GlobalParseContext->error(yylineno, "syntax error", "pre-mature EOF", s, "");
GlobalParseContext->recover();
}
} else {
GlobalParseContext->error(yylineno, "syntax error", yytext, s, "");
GlobalParseContext->recover();
}
}
void PaReservedWord()
{
GlobalParseContext->error(yylineno, "Reserved word.", yytext, "", "");
GlobalParseContext->recover();
}
int PaIdentOrType(TString& id, TParseContext& parseContextLocal, TSymbol*& symbol)
{
symbol = parseContextLocal.symbolTable.find(id);
if (parseContextLocal.lexAfterType == false && symbol && symbol->isVariable()) {
TVariable* variable = static_cast<TVariable*>(symbol);
if (variable->isUserType()) {
parseContextLocal.lexAfterType = true;
return TYPE_NAME;
}
}
return IDENTIFIER;
}
int PaParseComment(int &lineno, TParseContext& parseContextLocal)
{
int transitionFlag = 0;
int nextChar;
while (transitionFlag != 2) {
nextChar = yyinput();
if (nextChar == '\n')
lineno++;
switch (nextChar) {
case '*' :
transitionFlag = 1;
break;
case '/' : /* if star is the previous character, then it is the end of comment */
if (transitionFlag == 1) {
return 1 ;
}
break;
case EOF :
/* Raise error message here */
parseContextLocal.error(yylineno, "End of shader found before end of comment.", "", "", "");
GlobalParseContext->recover();
return YY_NULL;
default : /* Any other character will be a part of the comment */
transitionFlag = 0;
}
}
return 1;
}
extern "C" {
void CPPDebugLogMsg(const char *msg)
{
((TParseContext *)cpp->pC)->infoSink.debug.message(EPrefixNone, msg);
}
void CPPWarningToInfoLog(const char *msg)
{
((TParseContext *)cpp->pC)->infoSink.info.message(EPrefixWarning, msg, yylineno);
}
void CPPShInfoLogMsg(const char *msg)
{
((TParseContext *)cpp->pC)->error(yylineno,"", "",msg,"");
GlobalParseContext->recover();
}
void CPPErrorToInfoLog(char *msg)
{
((TParseContext *)cpp->pC)->error(yylineno,"syntax error", "",msg,"");
GlobalParseContext->recover();
}
void SetLineNumber(int line)
{
yylineno &= ~SourceLocLineMask;
yylineno |= line;
}
void SetStringNumber(int string)
{
yylineno = (string << SourceLocStringShift) | (yylineno & SourceLocLineMask);
}
int GetStringNumber(void)
{
return yylineno >> 16;
}
int GetLineNumber(void)
{
return yylineno & SourceLocLineMask;
}
void IncLineNumber(void)
{
if ((yylineno & SourceLocLineMask) <= SourceLocLineMask)
++yylineno;
}
void DecLineNumber(void)
{
if ((yylineno & SourceLocLineMask) > 0)
--yylineno;
}
void HandlePragma(const char **tokens, int numTokens)
{
if (!strcmp(tokens[0], "optimize")) {
if (numTokens != 4) {
CPPShInfoLogMsg("optimize pragma syntax is incorrect");
return;
}
if (strcmp(tokens[1], "(")) {
CPPShInfoLogMsg("\"(\" expected after 'optimize' keyword");
return;
}
if (!strcmp(tokens[2], "on"))
((TParseContext *)cpp->pC)->contextPragma.optimize = true;
else if (!strcmp(tokens[2], "off"))
((TParseContext *)cpp->pC)->contextPragma.optimize = false;
else {
CPPShInfoLogMsg("\"on\" or \"off\" expected after '(' for 'optimize' pragma");
return;
}
if (strcmp(tokens[3], ")")) {
CPPShInfoLogMsg("\")\" expected to end 'optimize' pragma");
return;
}
} else if (!strcmp(tokens[0], "debug")) {
if (numTokens != 4) {
CPPShInfoLogMsg("debug pragma syntax is incorrect");
return;
}
if (strcmp(tokens[1], "(")) {
CPPShInfoLogMsg("\"(\" expected after 'debug' keyword");
return;
}
if (!strcmp(tokens[2], "on"))
((TParseContext *)cpp->pC)->contextPragma.debug = true;
else if (!strcmp(tokens[2], "off"))
((TParseContext *)cpp->pC)->contextPragma.debug = false;
else {
CPPShInfoLogMsg("\"on\" or \"off\" expected after '(' for 'debug' pragma");
return;
}
if (strcmp(tokens[3], ")")) {
CPPShInfoLogMsg("\")\" expected to end 'debug' pragma");
return;
}
} else {
#ifdef PRAGMA_TABLE
//
// implementation specific pragma
// use ((TParseContext *)cpp->pC)->contextPragma.pragmaTable to store the information about pragma
// For now, just ignore the pragma that the implementation cannot recognize
// An Example of one such implementation for a pragma that has a syntax like
// #pragma pragmaname(pragmavalue)
// This implementation stores the current pragmavalue against the pragma name in pragmaTable.
//
if (numTokens == 4 && !strcmp(tokens[1], "(") && !strcmp(tokens[3], ")")) {
TPragmaTable& pragmaTable = ((TParseContext *)cpp->pC)->contextPragma.pragmaTable;
TPragmaTable::iterator iter;
iter = pragmaTable.find(TString(tokens[0]));
if (iter != pragmaTable.end()) {
iter->second = tokens[2];
} else {
pragmaTable[tokens[0]] = tokens[2];
}
} else if (numTokens >= 2) {
TPragmaTable& pragmaTable = ((TParseContext *)cpp->pC)->contextPragma.pragmaTable;
TPragmaTable::iterator iter;
iter = pragmaTable.find(TString(tokens[0]));
if (iter != pragmaTable.end()) {
iter->second = tokens[1];
} else {
pragmaTable[tokens[0]] = tokens[1];
}
}
#endif // PRAGMA_TABLE
}
}
void StoreStr(char *string)
{
TString strSrc;
strSrc = TString(string);
((TParseContext *)cpp->pC)->HashErrMsg = ((TParseContext *)cpp->pC)->HashErrMsg + " " + strSrc;
}
const char* GetStrfromTStr(void)
{
cpp->ErrMsg = (((TParseContext *)cpp->pC)->HashErrMsg).c_str();
return cpp->ErrMsg;
}
void ResetTString(void)
{
((TParseContext *)cpp->pC)->HashErrMsg = "";
}
TBehavior GetBehavior(const char* behavior)
{
if (!strcmp("require", behavior))
return EBhRequire;
else if (!strcmp("enable", behavior))
return EBhEnable;
else if (!strcmp("disable", behavior))
return EBhDisable;
else if (!strcmp("warn", behavior))
return EBhWarn;
else {
CPPShInfoLogMsg((TString("behavior '") + behavior + "' is not supported").c_str());
return EBhDisable;
}
}
void updateExtensionBehavior(const char* extName, const char* behavior)
{
TBehavior behaviorVal = GetBehavior(behavior);
TMap<TString, TBehavior>:: iterator iter;
TString msg;
// special cased for all extension
if (!strcmp(extName, "all")) {
if (behaviorVal == EBhRequire || behaviorVal == EBhEnable) {
CPPShInfoLogMsg("extension 'all' cannot have 'require' or 'enable' behavior");
return;
} else {
for (iter = ((TParseContext *)cpp->pC)->extensionBehavior.begin(); iter != ((TParseContext *)cpp->pC)->extensionBehavior.end(); ++iter)
iter->second = behaviorVal;
}
} else {
iter = ((TParseContext *)cpp->pC)->extensionBehavior.find(TString(extName));
if (iter == ((TParseContext *)cpp->pC)->extensionBehavior.end()) {
switch (behaviorVal) {
case EBhRequire:
CPPShInfoLogMsg((TString("extension '") + extName + "' is not supported").c_str());
break;
case EBhEnable:
case EBhWarn:
case EBhDisable:
msg = TString("extension '") + extName + "' is not supported";
((TParseContext *)cpp->pC)->infoSink.info.message(EPrefixWarning, msg.c_str(), yylineno);
break;
}
return;
} else
iter->second = behaviorVal;
}
}
} // extern "C"
void setInitialState()
{
yy_start = 1;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,491 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
#include "localintermediate.h"
//
// Two purposes:
// 1. Show an example of how to iterate tree. Functions can
// also directly call Traverse() on children themselves to
// have finer grained control over the process than shown here.
// See the last function for how to get started.
// 2. Print out a text based description of the tree.
//
//
// Use this class to carry along data from node to node in
// the traversal
//
class TOutputTraverser : public TIntermTraverser {
public:
TOutputTraverser(TInfoSink& i) : infoSink(i) { }
TInfoSink& infoSink;
};
TString TType::getCompleteString() const
{
char buf[100];
char *p = &buf[0];
if (qualifier != EvqTemporary && qualifier != EvqGlobal)
p += sprintf(p, "%s ", getQualifierString());
if (array)
p += sprintf(p, "array of ");
if (matrix)
p += sprintf(p, "%dX%d matrix of ", size, size);
else if (size > 1)
p += sprintf(p, "%d-component vector of ", size);
sprintf(p, "%s", getBasicString());
return TString(buf);
}
//
// Helper functions for printing, not part of traversing.
//
void OutputTreeText(TInfoSink& infoSink, TIntermNode* node, const int depth)
{
int i;
infoSink.debug << FormatSourceLoc(node->getLine());
for (i = 0; i < depth; ++i)
infoSink.debug << " ";
}
//
// The rest of the file are the traversal functions. The last one
// is the one that starts the traversal.
//
// Return true from interior nodes to have the external traversal
// continue on to children. If you process children yourself,
// return false.
//
void OutputSymbol(TIntermSymbol* node, TIntermTraverser* it)
{
TOutputTraverser* oit = static_cast<TOutputTraverser*>(it);
OutputTreeText(oit->infoSink, node, oit->depth);
char buf[100];
sprintf(buf, "'%s' (%s)\n",
node->getSymbol().c_str(),
node->getCompleteString().c_str());
oit->infoSink.debug << buf;
}
bool OutputBinary(bool /* preVisit */, TIntermBinary* node, TIntermTraverser* it)
{
TOutputTraverser* oit = static_cast<TOutputTraverser*>(it);
TInfoSink& out = oit->infoSink;
OutputTreeText(out, node, oit->depth);
switch (node->getOp()) {
case EOpAssign: out.debug << "move second child to first child"; break;
case EOpAddAssign: out.debug << "add second child into first child"; break;
case EOpSubAssign: out.debug << "subtract second child into first child"; break;
case EOpMulAssign: out.debug << "multiply second child into first child"; break;
case EOpVectorTimesMatrixAssign: out.debug << "matrix mult second child into first child"; break;
case EOpVectorTimesScalarAssign: out.debug << "vector scale second child into first child"; break;
case EOpMatrixTimesScalarAssign: out.debug << "matrix scale second child into first child"; break;
case EOpMatrixTimesMatrixAssign: out.debug << "matrix mult second child into first child"; break;
case EOpDivAssign: out.debug << "divide second child into first child"; break;
case EOpModAssign: out.debug << "mod second child into first child"; break;
case EOpAndAssign: out.debug << "and second child into first child"; break;
case EOpInclusiveOrAssign: out.debug << "or second child into first child"; break;
case EOpExclusiveOrAssign: out.debug << "exclusive or second child into first child"; break;
case EOpLeftShiftAssign: out.debug << "left shift second child into first child"; break;
case EOpRightShiftAssign: out.debug << "right shift second child into first child"; break;
case EOpIndexDirect: out.debug << "direct index"; break;
case EOpIndexIndirect: out.debug << "indirect index"; break;
case EOpIndexDirectStruct: out.debug << "direct index for structure"; break;
case EOpVectorSwizzle: out.debug << "vector swizzle"; break;
case EOpAdd: out.debug << "add"; break;
case EOpSub: out.debug << "subtract"; break;
case EOpMul: out.debug << "component-wise multiply"; break;
case EOpDiv: out.debug << "divide"; break;
case EOpMod: out.debug << "mod"; break;
case EOpRightShift: out.debug << "right-shift"; break;
case EOpLeftShift: out.debug << "left-shift"; break;
case EOpAnd: out.debug << "bitwise and"; break;
case EOpInclusiveOr: out.debug << "inclusive-or"; break;
case EOpExclusiveOr: out.debug << "exclusive-or"; break;
case EOpEqual: out.debug << "Compare Equal"; break;
case EOpNotEqual: out.debug << "Compare Not Equal"; break;
case EOpLessThan: out.debug << "Compare Less Than"; break;
case EOpGreaterThan: out.debug << "Compare Greater Than"; break;
case EOpLessThanEqual: out.debug << "Compare Less Than or Equal"; break;
case EOpGreaterThanEqual: out.debug << "Compare Greater Than or Equal"; break;
case EOpVectorTimesScalar: out.debug << "vector-scale"; break;
case EOpVectorTimesMatrix: out.debug << "vector-times-matrix"; break;
case EOpMatrixTimesVector: out.debug << "matrix-times-vector"; break;
case EOpMatrixTimesScalar: out.debug << "matrix-scale"; break;
case EOpMatrixTimesMatrix: out.debug << "matrix-multiply"; break;
case EOpLogicalOr: out.debug << "logical-or"; break;
case EOpLogicalXor: out.debug << "logical-xor"; break;
case EOpLogicalAnd: out.debug << "logical-and"; break;
default: out.debug << "<unknown op>";
}
out.debug << " (" << node->getCompleteString() << ")";
out.debug << "\n";
return true;
}
bool OutputUnary(bool /* preVisit */, TIntermUnary* node, TIntermTraverser* it)
{
TOutputTraverser* oit = static_cast<TOutputTraverser*>(it);
TInfoSink& out = oit->infoSink;
OutputTreeText(out, node, oit->depth);
switch (node->getOp()) {
case EOpNegative: out.debug << "Negate value"; break;
case EOpVectorLogicalNot:
case EOpLogicalNot: out.debug << "Negate conditional"; break;
case EOpBitwiseNot: out.debug << "Bitwise not"; break;
case EOpPostIncrement: out.debug << "Post-Increment"; break;
case EOpPostDecrement: out.debug << "Post-Decrement"; break;
case EOpPreIncrement: out.debug << "Pre-Increment"; break;
case EOpPreDecrement: out.debug << "Pre-Decrement"; break;
case EOpConvIntToBool: out.debug << "Convert int to bool"; break;
case EOpConvFloatToBool:out.debug << "Convert float to bool";break;
case EOpConvBoolToFloat:out.debug << "Convert bool to float";break;
case EOpConvIntToFloat: out.debug << "Convert int to float"; break;
case EOpConvFloatToInt: out.debug << "Convert float to int"; break;
case EOpConvBoolToInt: out.debug << "Convert bool to int"; break;
case EOpRadians: out.debug << "radians"; break;
case EOpDegrees: out.debug << "degrees"; break;
case EOpSin: out.debug << "sine"; break;
case EOpCos: out.debug << "cosine"; break;
case EOpTan: out.debug << "tangent"; break;
case EOpAsin: out.debug << "arc sine"; break;
case EOpAcos: out.debug << "arc cosine"; break;
case EOpAtan: out.debug << "arc tangent"; break;
case EOpExp: out.debug << "exp"; break;
case EOpLog: out.debug << "log"; break;
case EOpExp2: out.debug << "exp2"; break;
case EOpLog2: out.debug << "log2"; break;
case EOpSqrt: out.debug << "sqrt"; break;
case EOpInverseSqrt: out.debug << "inverse sqrt"; break;
case EOpAbs: out.debug << "Absolute value"; break;
case EOpSign: out.debug << "Sign"; break;
case EOpFloor: out.debug << "Floor"; break;
case EOpCeil: out.debug << "Ceiling"; break;
case EOpFract: out.debug << "Fraction"; break;
case EOpLength: out.debug << "length"; break;
case EOpNormalize: out.debug << "normalize"; break;
case EOpDPdx: out.debug << "dPdx"; break;
case EOpDPdy: out.debug << "dPdy"; break;
case EOpFwidth: out.debug << "fwidth"; break;
case EOpAny: out.debug << "any"; break;
case EOpAll: out.debug << "all"; break;
default: out.debug.message(EPrefixError, "Bad unary op");
}
out.debug << " (" << node->getCompleteString() << ")";
out.debug << "\n";
return true;
}
bool OutputAggregate(bool /* preVisit */, TIntermAggregate* node, TIntermTraverser* it)
{
TOutputTraverser* oit = static_cast<TOutputTraverser*>(it);
TInfoSink& out = oit->infoSink;
if (node->getOp() == EOpNull) {
out.debug.message(EPrefixError, "node is still EOpNull!");
return true;
}
OutputTreeText(out, node, oit->depth);
switch (node->getOp()) {
case EOpSequence: out.debug << "Sequence\n"; return true;
case EOpComma: out.debug << "Comma\n"; return true;
case EOpFunction: out.debug << "Function Definition: " << node->getName(); break;
case EOpFunctionCall: out.debug << "Function Call: " << node->getName(); break;
case EOpParameters: out.debug << "Function Parameters: "; break;
case EOpConstructFloat: out.debug << "Construct float"; break;
case EOpConstructVec2: out.debug << "Construct vec2"; break;
case EOpConstructVec3: out.debug << "Construct vec3"; break;
case EOpConstructVec4: out.debug << "Construct vec4"; break;
case EOpConstructBool: out.debug << "Construct bool"; break;
case EOpConstructBVec2: out.debug << "Construct bvec2"; break;
case EOpConstructBVec3: out.debug << "Construct bvec3"; break;
case EOpConstructBVec4: out.debug << "Construct bvec4"; break;
case EOpConstructInt: out.debug << "Construct int"; break;
case EOpConstructIVec2: out.debug << "Construct ivec2"; break;
case EOpConstructIVec3: out.debug << "Construct ivec3"; break;
case EOpConstructIVec4: out.debug << "Construct ivec4"; break;
case EOpConstructMat2: out.debug << "Construct mat2"; break;
case EOpConstructMat3: out.debug << "Construct mat3"; break;
case EOpConstructMat4: out.debug << "Construct mat4"; break;
case EOpConstructStruct: out.debug << "Construct structure"; break;
case EOpLessThan: out.debug << "Compare Less Than"; break;
case EOpGreaterThan: out.debug << "Compare Greater Than"; break;
case EOpLessThanEqual: out.debug << "Compare Less Than or Equal"; break;
case EOpGreaterThanEqual: out.debug << "Compare Greater Than or Equal"; break;
case EOpVectorEqual: out.debug << "Equal"; break;
case EOpVectorNotEqual: out.debug << "NotEqual"; break;
case EOpMod: out.debug << "mod"; break;
case EOpPow: out.debug << "pow"; break;
case EOpAtan: out.debug << "arc tangent"; break;
case EOpMin: out.debug << "min"; break;
case EOpMax: out.debug << "max"; break;
case EOpClamp: out.debug << "clamp"; break;
case EOpMix: out.debug << "mix"; break;
case EOpStep: out.debug << "step"; break;
case EOpSmoothStep: out.debug << "smoothstep"; break;
case EOpDistance: out.debug << "distance"; break;
case EOpDot: out.debug << "dot-product"; break;
case EOpCross: out.debug << "cross-product"; break;
case EOpFaceForward: out.debug << "face-forward"; break;
case EOpReflect: out.debug << "reflect"; break;
case EOpRefract: out.debug << "refract"; break;
case EOpMul: out.debug << "component-wise multiply"; break;
case EOpItof: out.debug << "itof"; break;
case EOpFtoi: out.debug << "ftoi"; break;
case EOpSkipPixels: out.debug << "skipPixels"; break;
case EOpReadInput: out.debug << "readInput"; break;
case EOpWritePixel: out.debug << "writePixel"; break;
case EOpBitmapLsb: out.debug << "bitmapLSB"; break;
case EOpBitmapMsb: out.debug << "bitmapMSB"; break;
case EOpWriteOutput: out.debug << "writeOutput"; break;
case EOpReadPixel: out.debug << "readPixel"; break;
default: out.debug.message(EPrefixError, "Bad aggregation op");
}
if (node->getOp() != EOpSequence && node->getOp() != EOpParameters)
out.debug << " (" << node->getCompleteString() << ")";
out.debug << "\n";
return true;
}
bool OutputSelection(bool /* preVisit */, TIntermSelection* node, TIntermTraverser* it)
{
TOutputTraverser* oit = static_cast<TOutputTraverser*>(it);
TInfoSink& out = oit->infoSink;
OutputTreeText(out, node, oit->depth);
out.debug << "Test condition and select";
out.debug << " (" << node->getCompleteString() << ")\n";
++oit->depth;
OutputTreeText(oit->infoSink, node, oit->depth);
out.debug << "Condition\n";
node->getCondition()->traverse(it);
OutputTreeText(oit->infoSink, node, oit->depth);
if (node->getTrueBlock()) {
out.debug << "true case\n";
node->getTrueBlock()->traverse(it);
} else
out.debug << "true case is null\n";
if (node->getFalseBlock()) {
OutputTreeText(oit->infoSink, node, oit->depth);
out.debug << "false case\n";
node->getFalseBlock()->traverse(it);
}
--oit->depth;
return false;
}
void OutputConstantUnion(TIntermConstantUnion* node, TIntermTraverser* it)
{
TOutputTraverser* oit = static_cast<TOutputTraverser*>(it);
TInfoSink& out = oit->infoSink;
int size = node->getType().getObjectSize();
for (int i = 0; i < size; i++) {
OutputTreeText(out, node, oit->depth);
switch (node->getUnionArrayPointer()[i].getType()) {
case EbtBool:
if (node->getUnionArrayPointer()[i].getBConst())
out.debug << "true";
else
out.debug << "false";
out.debug << " (" << "const bool" << ")";
out.debug << "\n";
break;
case EbtFloat:
{
char buf[300];
sprintf(buf, "%f (%s)", node->getUnionArrayPointer()[i].getFConst(), "const float");
out.debug << buf << "\n";
}
break;
case EbtInt:
{
char buf[300];
sprintf(buf, "%d (%s)", node->getUnionArrayPointer()[i].getIConst(), "const int");
out.debug << buf << "\n";
break;
}
default:
out.info.message(EPrefixInternalError, "Unknown constant", node->getLine());
break;
}
}
}
bool OutputLoop(bool /* preVisit */, TIntermLoop* node, TIntermTraverser* it)
{
TOutputTraverser* oit = static_cast<TOutputTraverser*>(it);
TInfoSink& out = oit->infoSink;
OutputTreeText(out, node, oit->depth);
out.debug << "Loop with condition ";
if (! node->testFirst())
out.debug << "not ";
out.debug << "tested first\n";
++oit->depth;
OutputTreeText(oit->infoSink, node, oit->depth);
if (node->getTest()) {
out.debug << "Loop Condition\n";
node->getTest()->traverse(it);
} else
out.debug << "No loop condition\n";
OutputTreeText(oit->infoSink, node, oit->depth);
if (node->getBody()) {
out.debug << "Loop Body\n";
node->getBody()->traverse(it);
} else
out.debug << "No loop body\n";
if (node->getTerminal()) {
OutputTreeText(oit->infoSink, node, oit->depth);
out.debug << "Loop Terminal Expression\n";
node->getTerminal()->traverse(it);
}
--oit->depth;
return false;
}
bool OutputBranch(bool /* previsit*/, TIntermBranch* node, TIntermTraverser* it)
{
TOutputTraverser* oit = static_cast<TOutputTraverser*>(it);
TInfoSink& out = oit->infoSink;
OutputTreeText(out, node, oit->depth);
switch (node->getFlowOp()) {
case EOpKill: out.debug << "Branch: Kill"; break;
case EOpBreak: out.debug << "Branch: Break"; break;
case EOpContinue: out.debug << "Branch: Continue"; break;
case EOpReturn: out.debug << "Branch: Return"; break;
default: out.debug << "Branch: Unknown Branch"; break;
}
if (node->getExpression()) {
out.debug << " with expression\n";
++oit->depth;
node->getExpression()->traverse(it);
--oit->depth;
} else
out.debug << "\n";
return false;
}
//
// This function is the one to call externally to start the traversal.
// Individual functions can be initialized to 0 to skip processing of that
// type of node. It's children will still be processed.
//
void TIntermediate::outputTree(TIntermNode* root)
{
if (root == 0)
return;
TOutputTraverser it(infoSink);
it.visitAggregate = OutputAggregate;
it.visitBinary = OutputBinary;
it.visitConstantUnion = OutputConstantUnion;
it.visitSelection = OutputSelection;
it.visitSymbol = OutputSymbol;
it.visitUnary = OutputUnary;
it.visitLoop = OutputLoop;
it.visitBranch = OutputBranch;
root->traverse(&it);
}

View file

@ -0,0 +1,86 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
#ifndef _LOCAL_INTERMEDIATE_INCLUDED_
#define _LOCAL_INTERMEDIATE_INCLUDED_
#include "../Include/intermediate.h"
#include "../Public/ShaderLang.h"
#include "SymbolTable.h"
struct TVectorFields {
int offsets[4];
int num;
};
//
// Set of helper functions to help parse and build the tree.
//
class TInfoSink;
class TIntermediate {
public:
POOL_ALLOCATOR_NEW_DELETE(GlobalPoolAllocator)
TIntermediate(TInfoSink& i) : infoSink(i) { }
TIntermSymbol* addSymbol(int Id, const TString&, const TType&, TSourceLoc);
TIntermTyped* addConversion(TOperator, const TType&, TIntermTyped*);
TIntermTyped* addBinaryMath(TOperator op, TIntermTyped* left, TIntermTyped* right, TSourceLoc, TSymbolTable&);
TIntermTyped* addAssign(TOperator op, TIntermTyped* left, TIntermTyped* right, TSourceLoc);
TIntermTyped* addIndex(TOperator op, TIntermTyped* base, TIntermTyped* index, TSourceLoc);
TIntermTyped* addUnaryMath(TOperator op, TIntermNode* child, TSourceLoc, TSymbolTable&);
TIntermAggregate* growAggregate(TIntermNode* left, TIntermNode* right, TSourceLoc);
TIntermAggregate* makeAggregate(TIntermNode* node, TSourceLoc);
TIntermAggregate* setAggregateOperator(TIntermNode*, TOperator, TSourceLoc);
TIntermNode* addSelection(TIntermTyped* cond, TIntermNodePair code, TSourceLoc);
TIntermTyped* addSelection(TIntermTyped* cond, TIntermTyped* trueBlock, TIntermTyped* falseBlock, TSourceLoc);
TIntermTyped* addComma(TIntermTyped* left, TIntermTyped* right, TSourceLoc);
TIntermConstantUnion* addConstantUnion(constUnion*, const TType&, TSourceLoc);
TIntermTyped* promoteConstantUnion(TBasicType, TIntermConstantUnion*) ;
bool parseConstTree(TSourceLoc, TIntermNode*, constUnion*, TOperator, TSymbolTable&, TType, bool singleConstantParam = false);
TIntermNode* addLoop(TIntermNode*, TIntermTyped*, TIntermTyped*, bool testFirst, TSourceLoc);
TIntermBranch* addBranch(TOperator, TSourceLoc);
TIntermBranch* addBranch(TOperator, TIntermTyped*, TSourceLoc);
TIntermTyped* addSwizzle(TVectorFields&, TSourceLoc);
bool postProcess(TIntermNode*, EShLanguage);
void remove(TIntermNode*);
void outputTree(TIntermNode*);
protected:
TInfoSink& infoSink;
private:
void operator=(TIntermediate&); // prevent assignments
};
#endif // _LOCAL_INTERMEDIATE_INCLUDED_

View file

@ -0,0 +1,266 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
#include "ParseHelper.h"
//
// Use this class to carry along data from node to node in
// the traversal
//
class TConstTraverser : public TIntermTraverser {
public:
TConstTraverser(constUnion* cUnion, bool singleConstParam, TOperator constructType, TInfoSink& sink, TSymbolTable& symTable, TType& t) : unionArray(cUnion), type(t),
constructorType(constructType), singleConstantParam(singleConstParam), infoSink(sink), symbolTable(symTable), error(false), isMatrix(false), matrixSize(0) { index = 0; tOp = EOpNull;}
int index ;
constUnion *unionArray;
TOperator tOp;
TType type;
TOperator constructorType;
bool singleConstantParam;
TInfoSink& infoSink;
TSymbolTable& symbolTable;
bool error;
int size; // size of the constructor ( 4 for vec4)
bool isMatrix;
int matrixSize; // dimension of the matrix (nominal size and not the instance size)
};
//
// The rest of the file are the traversal functions. The last one
// is the one that starts the traversal.
//
// Return true from interior nodes to have the external traversal
// continue on to children. If you process children yourself,
// return false.
//
void ParseSymbol(TIntermSymbol* node, TIntermTraverser* it)
{
TConstTraverser* oit = static_cast<TConstTraverser*>(it);
oit->infoSink.info.message(EPrefixInternalError, "Symbol Node found in constant constructor", node->getLine());
return;
}
bool ParseBinary(bool /* preVisit */, TIntermBinary* node, TIntermTraverser* it)
{
TConstTraverser* oit = static_cast<TConstTraverser*>(it);
TQualifier qualifier = node->getType().getQualifier();
if (qualifier != EvqConst) {
char buf[200];
sprintf(buf, "'constructor' : assigning non-constant to %s", oit->type.getCompleteString().c_str());
oit->infoSink.info.message(EPrefixError, buf, node->getLine());
oit->error = true;
return false;
}
oit->infoSink.info.message(EPrefixInternalError, "Binary Node found in constant constructor", node->getLine());
return false;
}
bool ParseUnary(bool /* preVisit */, TIntermUnary* node, TIntermTraverser* it)
{
TConstTraverser* oit = static_cast<TConstTraverser*>(it);
char buf[200];
sprintf(buf, "'constructor' : assigning non-constant to '%s'", oit->type.getCompleteString().c_str());
oit->infoSink.info.message(EPrefixError, buf, node->getLine());
oit->error = true;
return false;
}
bool ParseAggregate(bool /* preVisit */, TIntermAggregate* node, TIntermTraverser* it)
{
TConstTraverser* oit = static_cast<TConstTraverser*>(it);
if (!node->isConstructor() && node->getOp() != EOpComma) {
char buf[200];
sprintf(buf, "'constructor' : assigning non-constant to '%s'", oit->type.getCompleteString().c_str());
oit->infoSink.info.message(EPrefixError, buf, node->getLine());
oit->error = true;
return false;
}
if (node->getSequence().size() == 0) {
oit->error = true;
return false;
}
bool flag = node->getSequence().size() == 1 && node->getSequence()[0]->getAsTyped()->getAsConstantUnion();
if (flag)
{
oit->singleConstantParam = true;
oit->constructorType = node->getOp();
oit->size = node->getType().getObjectSize();
if (node->getType().isMatrix()) {
oit->isMatrix = true;
oit->matrixSize = node->getType().getNominalSize();
}
}
for (TIntermSequence::iterator p = node->getSequence().begin();
p != node->getSequence().end(); p++) {
if (node->getOp() == EOpComma)
oit->index = 0;
(*p)->traverse(oit);
}
if (flag)
{
oit->singleConstantParam = false;
oit->constructorType = EOpNull;
oit->size = 0;
oit->isMatrix = false;
oit->matrixSize = 0;
}
return false;
}
bool ParseSelection(bool /* preVisit */, TIntermSelection* node, TIntermTraverser* it)
{
TConstTraverser* oit = static_cast<TConstTraverser*>(it);
oit->infoSink.info.message(EPrefixInternalError, "Selection Node found in constant constructor", node->getLine());
oit->error = true;
return false;
}
void ParseConstantUnion(TIntermConstantUnion* node, TIntermTraverser* it)
{
TConstTraverser* oit = static_cast<TConstTraverser*>(it);
constUnion* leftUnionArray = oit->unionArray;
int instanceSize = oit->type.getObjectSize();
if (oit->index >= instanceSize)
return;
if (!oit->singleConstantParam) {
int size = node->getType().getObjectSize();
constUnion *rightUnionArray = node->getUnionArrayPointer();
for (int i=0; i < size; i++) {
if (oit->index >= instanceSize)
return;
leftUnionArray[oit->index] = rightUnionArray[i];
(oit->index)++;
}
} else {
int size, totalSize, matrixSize;
bool isMatrix = false;
size = oit->size;
matrixSize = oit->matrixSize;
isMatrix = oit->isMatrix;
totalSize = oit->index + size ;
constUnion *rightUnionArray = node->getUnionArrayPointer();
if (!isMatrix) {
int count = 0;
for (int i = oit->index; i < totalSize; i++) {
if (i >= instanceSize)
return;
leftUnionArray[i] = rightUnionArray[count];
(oit->index)++;
if (node->getType().getObjectSize() > 1)
count++;
}
} else { // for matrix constructors
int count = 0;
int index = oit->index;
for (int i = index; i < totalSize; i++) {
if (i >= instanceSize)
return;
if (index - i == 0 || (i - index) % (matrixSize + 1) == 0 )
leftUnionArray[i] = rightUnionArray[count];
else
leftUnionArray[i].setFConst(0.0f);
(oit->index)++;
if (node->getType().getObjectSize() > 1)
count++;
}
}
}
}
bool ParseLoop(bool /* preVisit */, TIntermLoop* node, TIntermTraverser* it)
{
TConstTraverser* oit = static_cast<TConstTraverser*>(it);
oit->infoSink.info.message(EPrefixInternalError, "Loop Node found in constant constructor", node->getLine());
oit->error = true;
return false;
}
bool ParseBranch(bool /* previsit*/, TIntermBranch* node, TIntermTraverser* it)
{
TConstTraverser* oit = static_cast<TConstTraverser*>(it);
oit->infoSink.info.message(EPrefixInternalError, "Branch Node found in constant constructor", node->getLine());
oit->error = true;
return false;
}
//
// This function is the one to call externally to start the traversal.
// Individual functions can be initialized to 0 to skip processing of that
// type of node. It's children will still be processed.
//
bool TIntermediate::parseConstTree(TSourceLoc line, TIntermNode* root, constUnion* unionArray, TOperator constructorType, TSymbolTable& symbolTable, TType t, bool singleConstantParam)
{
if (root == 0)
return false;
TConstTraverser it(unionArray, singleConstantParam, constructorType, infoSink, symbolTable, t);
it.visitAggregate = ParseAggregate;
it.visitBinary = ParseBinary;
it.visitConstantUnion = ParseConstantUnion;
it.visitSelection = ParseSelection;
it.visitSymbol = ParseSymbol;
it.visitUnary = ParseUnary;
it.visitLoop = ParseLoop;
it.visitBranch = ParseBranch;
root->traverse(&it);
if (it.error)
return true;
else
return false;
}

View file

@ -0,0 +1,38 @@
CC = gcc
OBJECTS = atom.o cpp.o cppstruct.o memory.o scanner.o symbols.o tokens.o
AR=ar
SRCS=scanner.c atom.c memory.c tokens. cpp.c cppstruct.c symbols.c
default: all
all : libPreprocessor.a
libPreprocessor.a : $(OBJECTS)
$(AR) rvu $@ $(OBJECTS)
ranlib $@
%.o : %.c
$(CC) -c $<
#
# Cleanup
#
.PHONY : clean
clean :
$(RM) *.o *.a
depend:
makedepend -Y -- $(SRCS)
# DO NOT DELETE
scanner.o: slglobals.h memory.h atom.h scanner.h parser.h cpp.h tokens.h
scanner.o: symbols.h compile.h
atom.o: slglobals.h memory.h atom.h scanner.h parser.h cpp.h tokens.h
atom.o: symbols.h compile.h
memory.o: memory.h
cpp.o: slglobals.h memory.h atom.h scanner.h parser.h cpp.h tokens.h
cpp.o: symbols.h compile.h
cppstruct.o: slglobals.h memory.h atom.h scanner.h parser.h cpp.h tokens.h
cppstruct.o: symbols.h compile.h
symbols.o: slglobals.h memory.h atom.h scanner.h parser.h cpp.h tokens.h
symbols.o: symbols.h compile.h

View file

@ -0,0 +1,768 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
/****************************************************************************\
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.
\****************************************************************************/
//
// atom.c
//
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "slglobals.h"
#undef malloc
#undef realloc
#undef free
///////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////// String table: //////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
static const struct {
int val;
const char *str;
} tokens[] = {
{ CPP_AND_OP, "&&" },
{ CPP_AND_ASSIGN, "&=" },
{ CPP_SUB_ASSIGN, "-=" },
{ CPP_MOD_ASSIGN, "%=" },
{ CPP_ADD_ASSIGN, "+=" },
{ CPP_DIV_ASSIGN, "/=" },
{ CPP_MUL_ASSIGN, "*=" },
{ CPP_RIGHT_BRACKET, ":>" },
{ CPP_EQ_OP, "==" },
{ CPP_XOR_OP, "^^" },
{ CPP_XOR_ASSIGN, "^=" },
{ CPP_FLOATCONSTANT, "<float-const>" },
{ CPP_GE_OP, ">=" },
{ CPP_RIGHT_OP, ">>" },
{ CPP_RIGHT_ASSIGN, ">>=" },
{ CPP_IDENTIFIER, "<ident>" },
{ CPP_INTCONSTANT, "<int-const>" },
{ CPP_LE_OP, "<=" },
{ CPP_LEFT_OP, "<<" },
{ CPP_LEFT_ASSIGN, "<<=" },
{ CPP_LEFT_BRACKET, "<:" },
{ CPP_LEFT_BRACE, "<%" },
{ CPP_DEC_OP, "--" },
{ CPP_RIGHT_BRACE, "%>" },
{ CPP_NE_OP, "!=" },
{ CPP_OR_OP, "||" },
{ CPP_OR_ASSIGN, "|=" },
{ CPP_INC_OP, "++" },
{ CPP_STRCONSTANT, "<string-const>" },
{ CPP_TYPEIDENTIFIER, "<type-ident>" },
};
///////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////// String table: //////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
#define INIT_STRING_TABLE_SIZE 16384
typedef struct StringTable_Rec {
char *strings;
int nextFree;
int size;
} StringTable;
/*
* InitStringTable() - Initialize the string table.
*
*/
static int InitStringTable(StringTable *stable)
{
stable->strings = (char *) malloc(INIT_STRING_TABLE_SIZE);
if (!stable->strings)
return 0;
// Zero-th offset means "empty" so don't use it.
stable->nextFree = 1;
stable->size = INIT_STRING_TABLE_SIZE;
return 1;
} // InitStringTable
/*
* FreeStringTable() - Free the string table.
*
*/
static void FreeStringTable(StringTable *stable)
{
if (stable->strings)
free(stable->strings);
stable->strings = NULL;
stable->nextFree = 0;
stable->size = 0;
} // FreeStringTable
/*
* HashString() - Hash a string with the base hash function.
*
*/
static int HashString(const char *s)
{
int hval = 0;
while (*s) {
hval = (hval*13507 + *s*197) ^ (hval >> 2);
s++;
}
return hval & 0x7fffffff;
} // HashString
/*
* HashString2() - Hash a string with the incrimenting hash function.
*
*/
static int HashString2(const char *s)
{
int hval = 0;
while (*s) {
hval = (hval*729 + *s*37) ^ (hval >> 1);
s++;
}
return hval;
} // HashString2
/*
* AddString() - Add a string to a string table. Return it's offset.
*
*/
static int AddString(StringTable *stable, const char *s)
{
int len, loc;
char *str;
len = (int) strlen(s);
if (stable->nextFree + len + 1 >= stable->size) {
assert(stable->size < 1000000);
str = (char *) malloc(stable->size*2);
memcpy(str, stable->strings, stable->size);
free(stable->strings);
stable->strings = str;
}
loc = stable->nextFree;
strcpy(&stable->strings[loc], s);
stable->nextFree += len + 1;
return loc;
} // AddString
///////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////// Hash table: ///////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
#define INIT_HASH_TABLE_SIZE 2047
#define HASH_TABLE_MAX_COLLISIONS 3
typedef struct HashEntry_Rec {
int index; // String table offset of string representation
int value; // Atom (symbol) value
} HashEntry;
typedef struct HashTable_Rec {
HashEntry *entry;
int size;
int entries;
int counts[HASH_TABLE_MAX_COLLISIONS + 1];
} HashTable;
/*
* InitHashTable() - Initialize the hash table.
*
*/
static int InitHashTable(HashTable *htable, int fsize)
{
int ii;
htable->entry = (HashEntry *) malloc(sizeof(HashEntry)*fsize);
if (!htable->entry)
return 0;
htable->size = fsize;
for (ii = 0; ii < fsize; ii++) {
htable->entry[ii].index = 0;
htable->entry[ii].value = 0;
}
htable->entries = 0;
for (ii = 0; ii <= HASH_TABLE_MAX_COLLISIONS; ii++)
htable->counts[ii] = 0;
return 1;
} // InitHashTable
/*
* FreeHashTable() - Free the hash table.
*
*/
static void FreeHashTable(HashTable *htable)
{
if (htable->entry)
free(htable->entry);
htable->entry = NULL;
htable->size = 0;
htable->entries = 0;
} // FreeHashTable
/*
* Empty() - See if a hash table entry is empty.
*
*/
static int Empty(HashTable *htable, int hashloc)
{
assert(hashloc >= 0 && hashloc < htable->size);
if (htable->entry[hashloc].index == 0) {
return 1;
} else {
return 0;
}
} // Empty
/*
* Match() - See if a hash table entry is matches a string.
*
*/
static int Match(HashTable *htable, StringTable *stable, const char *s, int hashloc)
{
int strloc;
strloc = htable->entry[hashloc].index;
if (!strcmp(s, &stable->strings[strloc])) {
return 1;
} else {
return 0;
}
} // Match
///////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////// Atom table: ///////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
#define INIT_ATOM_TABLE_SIZE 1024
struct AtomTable_Rec {
StringTable stable; // String table.
HashTable htable; // Hashes string to atom number and token value. Multiple strings can
// have the same token value but each unique string is a unique atom.
int *amap; // Maps atom value to offset in string table. Atoms all map to unique
// strings except for some undefined values in the lower, fixed part
// of the atom table that map to "<undefined>". The lowest 256 atoms
// correspond to single character ASCII values except for alphanumeric
// characters and '_', which can be other tokens. Next come the
// language tokens with their atom values equal to the token value.
// Then come predefined atoms, followed by user specified identifiers.
int *arev; // Reversed atom for symbol table use.
int nextFree;
int size;
};
static AtomTable latable = { { 0 } };
AtomTable *atable = &latable;
static int AddAtomFixed(AtomTable *atable, const char *s, int atom);
/*
* GrowAtomTable() - Grow the atom table to at least "size" if it's smaller.
*
*/
static int GrowAtomTable(AtomTable *atable, int size)
{
int *newmap, *newrev;
if (atable->size < size) {
if (atable->amap) {
newmap = realloc(atable->amap, sizeof(int)*size);
newrev = realloc(atable->arev, sizeof(int)*size);
} else {
newmap = malloc(sizeof(int)*size);
newrev = malloc(sizeof(int)*size);
atable->size = 0;
}
if (!newmap || !newrev) {
/* failed to grow -- error */
if (newmap)
atable->amap = newmap;
if (newrev)
atable->amap = newrev;
return -1;
}
memset(&newmap[atable->size], 0, (size - atable->size) * sizeof(int));
memset(&newrev[atable->size], 0, (size - atable->size) * sizeof(int));
atable->amap = newmap;
atable->arev = newrev;
atable->size = size;
}
return 0;
} // GrowAtomTable
/*
* lReverse() - Reverse the bottom 20 bits of a 32 bit int.
*
*/
static int lReverse(int fval)
{
unsigned int in = fval;
int result = 0, cnt = 0;
while(in) {
result <<= 1;
result |= in&1;
in >>= 1;
cnt++;
}
// Don't use all 31 bits. One million atoms is plenty and sometimes the
// upper bits are used for other things.
if (cnt < 20)
result <<= 20 - cnt;
return result;
} // lReverse
/*
* AllocateAtom() - Allocate a new atom. Associated with the "undefined" value of -1.
*
*/
static int AllocateAtom(AtomTable *atable)
{
if (atable->nextFree >= atable->size)
GrowAtomTable(atable, atable->nextFree*2);
atable->amap[atable->nextFree] = -1;
atable->arev[atable->nextFree] = lReverse(atable->nextFree);
atable->nextFree++;
return atable->nextFree - 1;
} // AllocateAtom
/*
* SetAtomValue() - Allocate a new atom associated with "hashindex".
*
*/
static void SetAtomValue(AtomTable *atable, int atomnumber, int hashindex)
{
atable->amap[atomnumber] = atable->htable.entry[hashindex].index;
atable->htable.entry[hashindex].value = atomnumber;
} // SetAtomValue
/*
* FindHashLoc() - Find the hash location for this string. Return -1 it hash table is full.
*
*/
static int FindHashLoc(AtomTable *atable, const char *s)
{
int hashloc, hashdelta, count;
int FoundEmptySlot = 0;
int collision[HASH_TABLE_MAX_COLLISIONS + 1];
hashloc = HashString(s) % atable->htable.size;
if (!Empty(&atable->htable, hashloc)) {
if (Match(&atable->htable, &atable->stable, s, hashloc))
return hashloc;
collision[0] = hashloc;
hashdelta = HashString2(s);
count = 0;
while (count < HASH_TABLE_MAX_COLLISIONS) {
hashloc = ((hashloc + hashdelta) & 0x7fffffff) % atable->htable.size;
if (!Empty(&atable->htable, hashloc)) {
if (Match(&atable->htable, &atable->stable, s, hashloc)) {
return hashloc;
}
} else {
FoundEmptySlot = 1;
break;
}
count++;
collision[count] = hashloc;
}
if (!FoundEmptySlot) {
if (cpp->options.DumpAtomTable) {
int ii;
char str[200];
sprintf(str, "*** Hash failed with more than %d collisions. Must increase hash table size. ***",
HASH_TABLE_MAX_COLLISIONS);
CPPShInfoLogMsg(str);
sprintf(str, "*** New string \"%s\", hash=%04x, delta=%04x", s, collision[0], hashdelta);
CPPShInfoLogMsg(str);
for (ii = 0; ii <= HASH_TABLE_MAX_COLLISIONS; ii++) {
sprintf(str, "*** Collides on try %d at hash entry %04x with \"%s\"",
ii + 1, collision[ii], GetAtomString(atable, atable->htable.entry[collision[ii]].value));
CPPShInfoLogMsg(str);
}
}
return -1;
} else {
atable->htable.counts[count]++;
}
}
return hashloc;
} // FindHashLoc
/*
* IncreaseHashTableSize()
*
*/
static int IncreaseHashTableSize(AtomTable *atable)
{
int ii, strloc, oldhashloc, value, size;
AtomTable oldtable;
char *s;
// Save the old atom table and create a new one:
oldtable = *atable;
size = oldtable.htable.size*2 + 1;
if (!InitAtomTable(atable, size))
return 0;
// Add all the existing values to the new atom table preserving their atom values:
for (ii = atable->nextFree; ii < oldtable.nextFree; ii++) {
strloc = oldtable.amap[ii];
s = &oldtable.stable.strings[strloc];
oldhashloc = FindHashLoc(&oldtable, s);
assert(oldhashloc >= 0);
value = oldtable.htable.entry[oldhashloc].value;
AddAtomFixed(atable, s, value);
}
FreeAtomTable(&oldtable);
return 1;
} // IncreaseHashTableSize
/*
* LookUpAddStringHash() - Lookup a string in the hash table. If it's not there, add it and
* initialize the atom value in the hash table to 0. Return the hash table index.
*/
static int LookUpAddStringHash(AtomTable *atable, const char *s)
{
int hashloc, strloc;
while(1) {
hashloc = FindHashLoc(atable, s);
if (hashloc >= 0)
break;
IncreaseHashTableSize(atable);
}
if (Empty(&atable->htable, hashloc)) {
atable->htable.entries++;
strloc = AddString(&atable->stable, s);
atable->htable.entry[hashloc].index = strloc;
atable->htable.entry[hashloc].value = 0;
}
return hashloc;
} // LookUpAddStringHash
/*
* LookUpAddString() - Lookup a string in the hash table. If it's not there, add it and
* initialize the atom value in the hash table to the next atom number.
* Return the atom value of string.
*/
int LookUpAddString(AtomTable *atable, const char *s)
{
int hashindex, atom;
hashindex = LookUpAddStringHash(atable, s);
atom = atable->htable.entry[hashindex].value;
if (atom == 0) {
atom = AllocateAtom(atable);
SetAtomValue(atable, atom, hashindex);
}
return atom;
} // LookUpAddString
/*
* GetAtomString()
*
*/
const char *GetAtomString(AtomTable *atable, int atom)
{
int soffset;
if (atom > 0 && atom < atable->nextFree) {
soffset = atable->amap[atom];
if (soffset > 0 && soffset < atable->stable.nextFree) {
return &atable->stable.strings[soffset];
} else {
return "<internal error: bad soffset>";
}
} else {
if (atom == 0) {
return "<null atom>";
} else {
if (atom == EOF) {
return "<EOF>";
} else {
return "<invalid atom>";
}
}
}
} // GetAtomString
/*
* GetReversedAtom()
*
*/
int GetReversedAtom(AtomTable *atable, int atom)
{
if (atom > 0 && atom < atable->nextFree) {
return atable->arev[atom];
} else {
return 0;
}
} // GetReversedAtom
/*
* AddAtom() - Add a string to the atom, hash and string tables if it isn't already there.
* Return it's atom index.
*/
int AddAtom(AtomTable *atable, const char *s)
{
int atom;
atom = LookUpAddString(atable, s);
return atom;
} // AddAtom
/*
* AddAtomFixed() - Add an atom to the hash and string tables if it isn't already there.
* Assign it the atom value of "atom".
*/
static int AddAtomFixed(AtomTable *atable, const char *s, int atom)
{
int hashindex, lsize;
hashindex = LookUpAddStringHash(atable, s);
if (atable->nextFree >= atable->size || atom >= atable->size) {
lsize = atable->size*2;
if (lsize <= atom)
lsize = atom + 1;
GrowAtomTable(atable, lsize);
}
atable->amap[atom] = atable->htable.entry[hashindex].index;
atable->htable.entry[hashindex].value = atom;
//if (atom >= atable->nextFree)
// atable->nextFree = atom + 1;
while (atom >= atable->nextFree) {
atable->arev[atable->nextFree] = lReverse(atable->nextFree);
atable->nextFree++;
}
return atom;
} // AddAtomFixed
/*
* InitAtomTable() - Initialize the atom table.
*
*/
int InitAtomTable(AtomTable *atable, int htsize)
{
int ii;
htsize = htsize <= 0 ? INIT_HASH_TABLE_SIZE : htsize;
if (!InitStringTable(&atable->stable))
return 0;
if (!InitHashTable(&atable->htable, htsize))
return 0;
atable->nextFree = 0;
atable->amap = NULL;
atable->size = 0;
GrowAtomTable(atable, INIT_ATOM_TABLE_SIZE);
if (!atable->amap)
return 0;
// Initialize lower part of atom table to "<undefined>" atom:
AddAtomFixed(atable, "<undefined>", 0);
for (ii = 0; ii < FIRST_USER_TOKEN_SY; ii++)
atable->amap[ii] = atable->amap[0];
// Add single character tokens to the atom table:
{
const char *s = "~!%^&*()-+=|,.<>/?;:[]{}#";
char t[2];
t[1] = '\0';
while (*s) {
t[0] = *s;
AddAtomFixed(atable, t, s[0]);
s++;
}
}
// Add multiple character scanner tokens :
for (ii = 0; ii < sizeof(tokens)/sizeof(tokens[0]); ii++)
AddAtomFixed(atable, tokens[ii].str, tokens[ii].val);
// Add error symbol if running in error mode:
if (cpp->options.ErrorMode)
AddAtomFixed(atable, "error", ERROR_SY);
AddAtom(atable, "<*** end fixed atoms ***>");
return 1;
} // InitAtomTable
///////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////// Debug Printing Functions: //////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
/*
* PrintAtomTable()
*
*/
void PrintAtomTable(AtomTable *atable)
{
int ii;
char str[200];
for (ii = 0; ii < atable->nextFree; ii++) {
sprintf(str, "%d: \"%s\"", ii, &atable->stable.strings[atable->amap[ii]]);
CPPDebugLogMsg(str);
}
sprintf(str, "Hash table: size=%d, entries=%d, collisions=",
atable->htable.size, atable->htable.entries);
CPPDebugLogMsg(str);
for (ii = 0; ii < HASH_TABLE_MAX_COLLISIONS; ii++) {
sprintf(str, " %d", atable->htable.counts[ii]);
CPPDebugLogMsg(str);
}
} // PrintAtomTable
/*
* GetStringOfAtom()
*
*/
char* GetStringOfAtom(AtomTable *atable, int atom)
{
char* chr_str;
chr_str=&atable->stable.strings[atable->amap[atom]];
return chr_str;
} // GetStringOfAtom
/*
* FreeAtomTable() - Free the atom table and associated memory
*
*/
void FreeAtomTable(AtomTable *atable)
{
FreeStringTable(&atable->stable);
FreeHashTable(&atable->htable);
if (atable->amap)
free(atable->amap);
if (atable->arev)
free(atable->arev);
atable->amap = NULL;
atable->arev = NULL;
atable->nextFree = 0;
atable->size = 0;
} // FreeAtomTable
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////// End of atom.c ///////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////

View file

@ -0,0 +1,96 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
/****************************************************************************\
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.
\****************************************************************************/
//
// atom.h
//
#if !defined(__ATOM_H)
#define __ATOM_H 1
typedef struct AtomTable_Rec AtomTable;
extern AtomTable *atable;
int InitAtomTable(AtomTable *atable, int htsize);
void FreeAtomTable(AtomTable *atable);
int AddAtom(AtomTable *atable, const char *s);
void PrintAtomTable(AtomTable *atable);
int LookUpAddString(AtomTable *atable, const char *s);
const char *GetAtomString(AtomTable *atable, int atom);
int GetReversedAtom(AtomTable *atable, int atom);
char* GetStringOfAtom(AtomTable *atable, int atom);
#endif // !defined(__ATOM_H)

View file

@ -0,0 +1,132 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
/****************************************************************************\
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.
\****************************************************************************/
//
// compile.h
//
#if !defined(__COMPILE_H)
#define __COMPILE_H 1
int InitCPPStruct(void);
typedef struct Options_Rec{
const char *profileString;
int ErrorMode;
int Quiet;
// Debug The Compiler options:
int DumpAtomTable;
} Options;
struct CPPStruct_Rec {
// Public members
SourceLoc *pLastSourceLoc; // Set at the start of each statement by the tree walkers
Options options; // Compile options and parameters
// Private members
SourceLoc lastSourceLoc;
// Scanner data:
SourceLoc *tokenLoc; // Source location of most recent token seen by the scanner
int mostRecentToken; // Most recent token seen by the scanner
InputSrc *currentInput;
int previous_token;
int notAVersionToken; // used to make sure that #version is the first token seen in the file, if present
void *pC; // storing the parseContext of the compile object in cpp.
// Private members:
SourceLoc ltokenLoc;
int ifdepth; //current #if-#else-#endif nesting in the cpp.c file (pre-processor)
int elsedepth[64]; //Keep a track of #if depth..Max allowed is 64.
int elsetracker; //#if-#else and #endif constructs...Counter.
const char *ErrMsg;
int CompileError; //Indicate compile error when #error, #else,#elif mismatch.
//
// Globals used to communicate between PaParseStrings() and yy_input()and
// also across the files.(gen_glslang.cpp and scanner.c)
//
int PaWhichStr; // which string we're parsing
int* PaStrLen; // array of lengths of the PaArgv strings
int PaArgc; // count of strings in the array
char** PaArgv; // our array of strings to parse
unsigned int tokensBeforeEOF : 1;
};
#endif // !defined(__COMPILE_H)

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,119 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
/****************************************************************************\
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.h
//
#if !defined(__CPP_H)
#define __CPP_H 1
#include "parser.h"
#include "tokens.h"
int InitCPP(void);
int FinalCPP(void);
int readCPPline(yystypepp * yylvalpp);
int MacroExpand(int atom, yystypepp * yylvalpp);
int ChkCorrectElseNesting(void);
typedef struct MacroSymbol {
int argc;
int *args;
TokenStream *body;
unsigned busy:1;
unsigned undef:1;
} MacroSymbol;
void FreeMacro(MacroSymbol *);
int PredefineMacro(char *);
void CPPDebugLogMsg(const char *msg); // Prints information into debug log
void CPPShInfoLogMsg(const char*); // Store cpp Err Msg into Sh.Info.Log
void CPPWarningToInfoLog(const char *msg); // Prints warning messages into info log
void HandlePragma(const char**, int numTokens); // #pragma directive container.
void ResetTString(void); // #error Message as TString.
void CPPErrorToInfoLog(char*); // Stick all cpp errors into Sh.Info.log .
void StoreStr(char*); // Store the TString in Parse Context.
void SetLineNumber(int); // Set line number.
void SetStringNumber(int); // Set string number.
int GetLineNumber(void); // Get the current String Number.
int GetStringNumber(void); // Get the current String Number.
const char* GetStrfromTStr(void); // Convert TString to String.
void updateExtensionBehavior(const char* extName, const char* behavior);
int FreeCPP(void);
#endif // !(defined(__CPP_H)

View file

@ -0,0 +1,185 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
/****************************************************************************\
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.
\****************************************************************************/
//
// cppstruct.c
//
#include <stdio.h>
#include <stdlib.h>
#include "slglobals.h"
CPPStruct *cpp = NULL;
static int refCount = 0;
int InitPreprocessor(void);
int ResetPreprocessor(void);
int FreeCPPStruct(void);
int FinalizePreprocessor(void);
/*
* InitCPPStruct() - Initilaize the CPP structure.
*
*/
int InitCPPStruct(void)
{
int len;
char *p;
cpp = (CPPStruct *) malloc(sizeof(CPPStruct));
if (cpp == NULL)
return 0;
refCount++;
// Initialize public members:
cpp->pLastSourceLoc = &cpp->lastSourceLoc;
p = (char *) &cpp->options;
len = sizeof(cpp->options);
while (--len >= 0)
p[len] = 0;
ResetPreprocessor();
return 1;
} // InitCPPStruct
int ResetPreprocessor(void)
{
// Initialize private members:
cpp->lastSourceLoc.file = 0;
cpp->lastSourceLoc.line = 0;
cpp->pC=0;
cpp->CompileError=0;
cpp->ifdepth=0;
for(cpp->elsetracker=0; cpp->elsetracker<64; cpp->elsetracker++)
cpp->elsedepth[cpp->elsetracker]=0;
cpp->elsetracker=0;
cpp->tokensBeforeEOF = 0;
return 1;
}
//Intializing the Preprocessor.
int InitPreprocessor(void)
{
# define CPP_STUFF true
# ifdef CPP_STUFF
FreeCPPStruct();
InitCPPStruct();
cpp->options.Quiet = 1;
cpp->options.profileString = "generic";
if (!InitAtomTable(atable, 0))
return 1;
if (!InitScanner(cpp))
return 1;
# endif
return 0;
}
//FreeCPPStruct() - Free the CPP structure.
int FreeCPPStruct(void)
{
if (refCount)
{
free(cpp);
refCount--;
}
return 1;
}
//Finalizing the Preprocessor.
int FinalizePreprocessor(void)
{
# define CPP_STUFF true
# ifdef CPP_STUFF
FreeAtomTable(atable);
FreeCPPStruct();
FreeScanner();
# endif
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////// End of cppstruct.c //////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////

View file

@ -0,0 +1,191 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
/****************************************************************************\
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.
\****************************************************************************/
//
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#ifdef __STDC99__
#include <stdint.h>
#elif defined (_WIN64)
typedef unsigned __int64 uintptr_t;
#else
typedef unsigned int uintptr_t;
#endif
#include "memory.h"
// default alignment and chunksize, if called with 0 arguments
#define CHUNKSIZE (64*1024)
#define ALIGN 8
// we need to call the `real' malloc and free, not our replacements
#undef malloc
#undef free
struct chunk {
struct chunk *next;
};
struct cleanup {
struct cleanup *next;
void (*fn)(void *);
void *arg;
};
struct MemoryPool_rec {
struct chunk *next;
uintptr_t free, end;
size_t chunksize;
uintptr_t alignmask;
struct cleanup *cleanup;
};
MemoryPool *mem_CreatePool(size_t chunksize, unsigned int align)
{
MemoryPool *pool;
if (align == 0) align = ALIGN;
if (chunksize == 0) chunksize = CHUNKSIZE;
if (align & (align-1)) return 0;
if (chunksize < sizeof(MemoryPool)) return 0;
if (chunksize & (align-1)) return 0;
if (!(pool = malloc(chunksize))) return 0;
pool->next = 0;
pool->chunksize = chunksize;
pool->alignmask = (uintptr_t)(align)-1;
pool->free = ((uintptr_t)(pool + 1) + pool->alignmask) & ~pool->alignmask;
pool->end = (uintptr_t)pool + chunksize;
pool->cleanup = 0;
return pool;
}
void mem_FreePool(MemoryPool *pool)
{
struct cleanup *cleanup;
struct chunk *p, *next;
for (cleanup = pool->cleanup; cleanup; cleanup = cleanup->next) {
cleanup->fn(cleanup->arg);
}
for (p = (struct chunk *)pool; p; p = next) {
next = p->next;
free(p);
}
}
void *mem_Alloc(MemoryPool *pool, size_t size)
{
struct chunk *ch;
void *rv = (void *)pool->free;
size = (size + pool->alignmask) & ~pool->alignmask;
if (size <= 0) size = pool->alignmask;
pool->free += size;
if (pool->free > pool->end || pool->free < (uintptr_t)rv) {
size_t minreq = (size + sizeof(struct chunk) + pool->alignmask)
& ~pool->alignmask;
pool->free = (uintptr_t)rv;
if (minreq >= pool->chunksize) {
// request size is too big for the chunksize, so allocate it as
// a single chunk of the right size
ch = malloc(minreq);
if (!ch) return 0;
} else {
ch = malloc(pool->chunksize);
if (!ch) return 0;
pool->free = (uintptr_t)ch + minreq;
pool->end = (uintptr_t)ch + pool->chunksize;
}
ch->next = pool->next;
pool->next = ch;
rv = (void *)(((uintptr_t)(ch+1) + pool->alignmask) & ~pool->alignmask);
}
return rv;
}
int mem_AddCleanup(MemoryPool *pool, void (*fn)(void *), void *arg) {
struct cleanup *cleanup;
pool->free = (pool->free + sizeof(void *) - 1) & ~(sizeof(void *)-1);
cleanup = mem_Alloc(pool, sizeof(struct cleanup));
if (!cleanup) return -1;
cleanup->next = pool->cleanup;
cleanup->fn = fn;
cleanup->arg = arg;
pool->cleanup = cleanup;
return 0;
}

View file

@ -0,0 +1,89 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
/****************************************************************************\
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.
\****************************************************************************/
//
#ifndef __MEMORY_H
#define __MEMORY_H
typedef struct MemoryPool_rec MemoryPool;
extern MemoryPool *mem_CreatePool(size_t chunksize, unsigned align);
extern void mem_FreePool(MemoryPool *);
extern void *mem_Alloc(MemoryPool *p, size_t size);
extern void *mem_Realloc(MemoryPool *p, void *old, size_t oldsize, size_t newsize);
extern int mem_AddCleanup(MemoryPool *p, void (*fn)(void *), void *arg);
#endif /* __MEMORY_H */

View file

@ -0,0 +1,126 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
/****************************************************************************\
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.
\****************************************************************************/
#ifndef BISON_PARSER_H
# define BISON_PARSER_H
#ifndef yystypepp
typedef struct {
int sc_int;
float sc_fval;
int sc_ident;
char symbol_name[MAX_SYMBOL_NAME_LEN+1];
} yystypepp;
# define YYSTYPE_IS_TRIVIAL 1
#endif
# define CPP_AND_OP 257
# define CPP_SUB_ASSIGN 259
# define CPP_MOD_ASSIGN 260
# define CPP_ADD_ASSIGN 261
# define CPP_DIV_ASSIGN 262
# define CPP_MUL_ASSIGN 263
# define CPP_EQ_OP 264
# define CPP_XOR_OP 265
# define ERROR_SY 266
# define CPP_FLOATCONSTANT 267
# define CPP_GE_OP 268
# define CPP_RIGHT_OP 269
# define CPP_IDENTIFIER 270
# define CPP_INTCONSTANT 271
# define CPP_LE_OP 272
# define CPP_LEFT_OP 273
# define CPP_DEC_OP 274
# define CPP_NE_OP 275
# define CPP_OR_OP 276
# define CPP_INC_OP 277
# define CPP_STRCONSTANT 278
# define CPP_TYPEIDENTIFIER 279
# define FIRST_USER_TOKEN_SY 289
# define CPP_RIGHT_ASSIGN 280
# define CPP_LEFT_ASSIGN 281
# define CPP_AND_ASSIGN 282
# define CPP_OR_ASSIGN 283
# define CPP_XOR_ASSIGN 284
# define CPP_LEFT_BRACKET 285
# define CPP_RIGHT_BRACKET 286
# define CPP_LEFT_BRACE 287
# define CPP_RIGHT_BRACE 288
#endif /* not BISON_PARSER_H */

View file

@ -0,0 +1,84 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
/****************************************************************************\
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.
\****************************************************************************/
# include "slglobals.h"
extern CPPStruct *cpp;
int InitCPPStruct(void);
int InitScanner(CPPStruct *cpp);
int InitAtomTable(AtomTable *atable, int htsize);
int ScanFromString(char *s);
char* GetStringOfAtom(AtomTable *atable, int atom);

View file

@ -0,0 +1,794 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
/****************************************************************************\
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.
\****************************************************************************/
//
// scanner.c
//
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if 0
#include <ieeefp.h>
#else
#define isinff(x) (((*(int *)&(x) & 0x7f800000L)==0x7f800000L) && \
((*(int *)&(x) & 0x007fffffL)==0000000000L))
#endif
#include "slglobals.h"
typedef struct StringInputSrc {
InputSrc base;
char *p;
} StringInputSrc;
static int eof_scan(InputSrc *is, yystypepp * yylvalpp)
{
return EOF;
} // eof_scan
static void noop(InputSrc *in, int ch, yystypepp * yylvalpp) {}
static InputSrc eof_inputsrc = { 0, &eof_scan, &eof_scan, &noop };
static int byte_scan(InputSrc *, yystypepp * yylvalpp);
#define EOL_SY '\n'
#if defined(_WIN32)
#define DBG_BREAKPOINT() __asm int 3
#elif defined(_M_AMD64)
#define DBG_BREAKPOINT() assert(!"Dbg_Breakpoint");
#else
#define DBG_BREAKPOINT()
#endif
#if defined(_WIN32) && !defined(_M_AMD64)
__int64 RDTSC ( void ) {
__int64 v;
__asm __emit 0x0f
__asm __emit 0x31
__asm mov dword ptr v, eax
__asm mov dword ptr v+4, edx
return v;
}
#endif
int InitScanner(CPPStruct *cpp)
{
// Add various atoms needed by the CPP line scanner:
if (!InitCPP())
return 0;
cpp->mostRecentToken = 0;
cpp->tokenLoc = &cpp->ltokenLoc;
cpp->ltokenLoc.file = 0;
cpp->ltokenLoc.line = 0;
cpp->currentInput = &eof_inputsrc;
cpp->previous_token = '\n';
cpp->notAVersionToken = 0;
return 1;
} // InitScanner
int FreeScanner(void)
{
return (FreeCPP());
}
/*
* str_getch()
* takes care of reading from multiple strings.
* returns the next-char from the input stream.
* returns EOF when the complete shader is parsed.
*/
static int str_getch(StringInputSrc *in)
{
for(;;){
if (*in->p){
if (*in->p == '\n') {
in->base.line++;
IncLineNumber();
}
return *in->p++;
}
if(++(cpp->PaWhichStr) < cpp->PaArgc){
free(in);
SetStringNumber(cpp->PaWhichStr);
SetLineNumber(1);
ScanFromString(cpp->PaArgv[cpp->PaWhichStr]);
in=(StringInputSrc*)cpp->currentInput;
continue;
}
else{
cpp->currentInput = in->base.prev;
cpp->PaWhichStr=0;
free(in);
return EOF;
}
}
} // str_getch
static void str_ungetch(StringInputSrc *in, int ch, yystypepp *type) {
if (in->p[-1] == ch)in->p--;
else {
*(in->p)='\0'; //this would take care of shifting to the previous string.
cpp->PaWhichStr--;
}
if (ch == '\n') {
in->base.line--;
DecLineNumber();
}
} // str_ungetch
int ScanFromString(char *s)
{
StringInputSrc *in = malloc(sizeof(StringInputSrc));
memset(in, 0, sizeof(StringInputSrc));
in->p = s;
in->base.line = 1;
in->base.scan = byte_scan;
in->base.getch = (int (*)(InputSrc *, yystypepp *))str_getch;
in->base.ungetch = (void (*)(InputSrc *, int, yystypepp *))str_ungetch;
in->base.prev = cpp->currentInput;
cpp->currentInput = &in->base;
return 1;
} // ScanFromString;
///////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////// Floating point constants: /////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
/*
* lBuildFloatValue() - Quick and dirty conversion to floating point. Since all
* we need is single precision this should be quite precise.
*/
static float lBuildFloatValue(const char *str, int len, int exp)
{
double val, expval, ten;
int ii, llen, absexp;
float rv;
val = 0.0;
llen = len;
for (ii = 0; ii < len; ii++)
val = val*10.0 + (str[ii] - '0');
if (exp != 0) {
absexp = exp > 0 ? exp : -exp;
expval = 1.0f;
ten = 10.0;
while (absexp) {
if (absexp & 1)
expval *= ten;
ten *= ten;
absexp >>= 1;
}
if (exp >= 0) {
val *= expval;
} else {
val /= expval;
}
}
rv = (float)val;
if (isinff(rv)) {
CPPErrorToInfoLog(" ERROR___FP_CONST_OVERFLOW");
}
return rv;
} // lBuildFloatValue
/*
* lFloatConst() - Scan a floating point constant. Assumes that the scanner
* has seen at least one digit, followed by either a decimal '.' or the
* letter 'e'.
*/
static int lFloatConst(char *str, int len, int ch, yystypepp * yylvalpp)
{
int HasDecimal, declen, exp, ExpSign;
int str_len;
float lval;
HasDecimal = 0;
declen = 0;
exp = 0;
str_len=len;
if (ch == '.') {
str[len++]=ch;
HasDecimal = 1;
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
while (ch >= '0' && ch <= '9') {
if (len < MAX_SYMBOL_NAME_LEN) {
declen++;
if (len > 0 || ch != '0') {
str[len] = ch;
len++;str_len++;
}
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
} else {
CPPErrorToInfoLog("ERROR___FP_CONST_TOO_LONG");
len = 1,str_len=1;
}
}
}
// Exponent:
if (ch == 'e' || ch == 'E') {
ExpSign = 1;
str[len++]=ch;
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if (ch == '+') {
str[len++]=ch;
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
} else if (ch == '-') {
ExpSign = -1;
str[len++]=ch;
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
}
if (ch >= '0' && ch <= '9') {
while (ch >= '0' && ch <= '9') {
exp = exp*10 + ch - '0';
str[len++]=ch;
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
}
} else {
CPPErrorToInfoLog("ERROR___ERROR_IN_EXPONENT");
}
exp *= ExpSign;
}
if (len == 0) {
lval = 0.0f;
strcpy(str,"0.0");
} else {
str[len]='\0';
lval = lBuildFloatValue(str, str_len, exp - declen);
}
// Suffix:
yylvalpp->sc_fval = lval;
strcpy(yylvalpp->symbol_name,str);
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
return CPP_FLOATCONSTANT;
} // lFloatConst
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////// Normal Scanner //////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
static int byte_scan(InputSrc *in, yystypepp * yylvalpp)
{
char symbol_name[MAX_SYMBOL_NAME_LEN + 1];
char string_val[MAX_STRING_LEN + 1];
int AlreadyComplained;
int len, ch, ii, ival = 0;
for (;;) {
yylvalpp->sc_int = 0;
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
while (ch == ' ' || ch == '\t' || ch == '\r') {
yylvalpp->sc_int = 1;
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
}
cpp->ltokenLoc.file = cpp->currentInput->name;
cpp->ltokenLoc.line = cpp->currentInput->line;
len = 0;
switch (ch) {
default:
return ch; // Single character token
case EOF:
return -1;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y':
case 'Z': case '_':
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y':
case 'z':
do {
if (len < MAX_SYMBOL_NAME_LEN) {
symbol_name[len] = ch;
len++;
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
} else {
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
}
} while ((ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') ||
ch == '_');
if (len >= MAX_SYMBOL_NAME_LEN)
len = MAX_SYMBOL_NAME_LEN - 1;
symbol_name[len] = '\0';
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
yylvalpp->sc_ident = LookUpAddString(atable, symbol_name);
return CPP_IDENTIFIER;
break;
case '0':
yylvalpp->symbol_name[len++] = ch;
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if (ch == 'x' || ch == 'X') {
yylvalpp->symbol_name[len++] = ch;
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if ((ch >= '0' && ch <= '9') ||
(ch >= 'A' && ch <= 'F') ||
(ch >= 'a' && ch <= 'f'))
{
AlreadyComplained = 0;
ival = 0;
do {
yylvalpp->symbol_name[len++] = ch;
if (ival <= 0x0fffffff) {
if (ch >= '0' && ch <= '9') {
ii = ch - '0';
} else if (ch >= 'A' && ch <= 'F') {
ii = ch - 'A' + 10;
} else {
ii = ch - 'a' + 10;
}
ival = (ival << 4) | ii;
} else {
if (!AlreadyComplained)
CPPErrorToInfoLog("ERROR___HEX_CONST_OVERFLOW");
AlreadyComplained = 1;
}
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
} while ((ch >= '0' && ch <= '9') ||
(ch >= 'A' && ch <= 'F') ||
(ch >= 'a' && ch <= 'f'));
} else {
CPPErrorToInfoLog("ERROR___ERROR_IN_HEX_CONSTANT");
}
yylvalpp->symbol_name[len] = '\0';
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
yylvalpp->sc_int = ival;
return CPP_INTCONSTANT;
} else if (ch >= '0' && ch <= '7') { // octal integer constants
AlreadyComplained = 0;
ival = 0;
do {
yylvalpp->symbol_name[len++] = ch;
if (ival <= 0x1fffffff) {
ii = ch - '0';
ival = (ival << 3) | ii;
} else {
if (!AlreadyComplained)
CPPErrorToInfoLog("ERROR___OCT_CONST_OVERFLOW");
AlreadyComplained = 1;
}
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
} while (ch >= '0' && ch <= '7');
if (ch == '.' || ch == 'e' || ch == 'f' || ch == 'h' || ch == 'x'|| ch == 'E')
return lFloatConst(yylvalpp->symbol_name, len, ch, yylvalpp);
yylvalpp->symbol_name[len] = '\0';
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
yylvalpp->sc_int = ival;
return CPP_INTCONSTANT;
} else {
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
ch = '0';
}
// Fall through...
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
do {
if (len < MAX_SYMBOL_NAME_LEN) {
if (len > 0 || ch != '0') {
yylvalpp->symbol_name[len] = ch;
len++;
}
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
}
} while (ch >= '0' && ch <= '9');
if (ch == '.' || ch == 'e' || ch == 'f' || ch == 'h' || ch == 'x'|| ch == 'E') {
return lFloatConst(yylvalpp->symbol_name, len, ch, yylvalpp);
} else {
yylvalpp->symbol_name[len] = '\0';
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
ival = 0;
AlreadyComplained = 0;
for (ii = 0; ii < len; ii++) {
ch = yylvalpp->symbol_name[ii] - '0';
if ((ival > 214748364) || (ival == 214748364 && ch >= 8)) {
if (!AlreadyComplained)
CPPErrorToInfoLog("ERROR___INTEGER_CONST_OVERFLOW");
AlreadyComplained = 1;
}
ival = ival*10 + ch;
}
yylvalpp->sc_int = ival;
if(ival==0)
strcpy(yylvalpp->symbol_name,"0");
return CPP_INTCONSTANT;
}
break;
case '-':
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if (ch == '-') {
return CPP_DEC_OP;
} else if (ch == '=') {
return CPP_SUB_ASSIGN;
} else {
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
return '-';
}
case '+':
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if (ch == '+') {
return CPP_INC_OP;
} else if (ch == '=') {
return CPP_ADD_ASSIGN;
} else {
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
return '+';
}
case '*':
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if (ch == '=') {
return CPP_MUL_ASSIGN;
} else {
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
return '*';
}
case '%':
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if (ch == '=') {
return CPP_MOD_ASSIGN;
} else if (ch == '>'){
return CPP_RIGHT_BRACE;
} else {
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
return '%';
}
case ':':
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if (ch == '>') {
return CPP_RIGHT_BRACKET;
} else {
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
return ':';
}
case '^':
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if (ch == '^') {
return CPP_XOR_OP;
} else {
if (ch == '=')
return CPP_XOR_ASSIGN;
else{
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
return '^';
}
}
case '=':
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if (ch == '=') {
return CPP_EQ_OP;
} else {
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
return '=';
}
case '!':
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if (ch == '=') {
return CPP_NE_OP;
} else {
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
return '!';
}
case '|':
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if (ch == '|') {
return CPP_OR_OP;
} else {
if (ch == '=')
return CPP_OR_ASSIGN;
else{
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
return '|';
}
}
case '&':
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if (ch == '&') {
return CPP_AND_OP;
} else {
if (ch == '=')
return CPP_AND_ASSIGN;
else{
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
return '&';
}
}
case '<':
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if (ch == '<') {
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if(ch == '=')
return CPP_LEFT_ASSIGN;
else{
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
return CPP_LEFT_OP;
}
} else {
if (ch == '=') {
return CPP_LE_OP;
} else {
if (ch == '%')
return CPP_LEFT_BRACE;
else if (ch == ':')
return CPP_LEFT_BRACKET;
else{
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
return '<';
}
}
}
case '>':
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if (ch == '>') {
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if(ch == '=')
return CPP_RIGHT_ASSIGN;
else{
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
return CPP_RIGHT_OP;
}
} else {
if (ch == '=') {
return CPP_GE_OP;
} else {
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
return '>';
}
}
case '.':
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if (ch >= '0' && ch <= '9') {
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
return lFloatConst(yylvalpp->symbol_name, 0, '.', yylvalpp);
} else {
if (ch == '.') {
return -1; // Special EOF hack
} else {
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
return '.';
}
}
case '/':
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if (ch == '/') {
do {
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
} while (ch != '\n' && ch != EOF);
if (ch == EOF)
return -1;
return '\n';
} else if (ch == '*') {
int nlcount = 0;
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
do {
while (ch != '*') {
if (ch == '\n') nlcount++;
if (ch == EOF) {
CPPErrorToInfoLog("ERROR___EOF_IN_COMMENT");
return -1;
}
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
}
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if (ch == EOF) {
CPPErrorToInfoLog("ERROR___EOF_IN_COMMENT");
return -1;
}
} while (ch != '/');
if (nlcount) {
return '\n';
}
// Go try it again...
} else if (ch == '=') {
return CPP_DIV_ASSIGN;
} else {
cpp->currentInput->ungetch(cpp->currentInput, ch, yylvalpp);
return '/';
}
break;
case '"':
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
while (ch != '"' && ch != '\n' && ch != EOF) {
if (ch == '\\') {
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
if (ch == '\n' || ch == EOF) {
break;
}
}
if (len < MAX_STRING_LEN) {
string_val[len] = ch;
len++;
ch = cpp->currentInput->getch(cpp->currentInput, yylvalpp);
}
};
string_val[len] = '\0';
if (ch == '"') {
yylvalpp->sc_ident = LookUpAddString(atable, string_val);
return CPP_STRCONSTANT;
} else {
CPPErrorToInfoLog("ERROR___CPP_EOL_IN_STRING");
return ERROR_SY;
}
}
}
} // byte_scan
int yylex_CPP(char* buf, int maxSize)
{
yystypepp yylvalpp;
int token = '\n';
for(;;) {
char* tokenString = 0;
token = cpp->currentInput->scan(cpp->currentInput, &yylvalpp);
if(check_EOF(token))
return 0;
if (token == '#') {
if (cpp->previous_token == '\n'|| cpp->previous_token == 0) {
token = readCPPline(&yylvalpp);
if(check_EOF(token))
return 0;
continue;
} else {
CPPErrorToInfoLog("preprocessor command must not be preceded by any other statement in that line");
return 0;
}
}
cpp->previous_token = token;
// expand macros
if (token == CPP_IDENTIFIER && MacroExpand(yylvalpp.sc_ident, &yylvalpp)) {
cpp->notAVersionToken = 1;
continue;
}
if (token == '\n')
continue;
if (token == CPP_IDENTIFIER) {
cpp->notAVersionToken = 1;
tokenString = GetStringOfAtom(atable,yylvalpp.sc_ident);
} else if (token == CPP_FLOATCONSTANT||token == CPP_INTCONSTANT){
cpp->notAVersionToken = 1;
tokenString = yylvalpp.symbol_name;
} else {
cpp->notAVersionToken = 1;
tokenString = GetStringOfAtom(atable,token);
}
if (tokenString) {
if ((signed)strlen(tokenString) >= maxSize) {
cpp->tokensBeforeEOF = 1;
return maxSize;
} else if (strlen(tokenString) > 0) {
strcpy(buf, tokenString);
cpp->tokensBeforeEOF = 1;
return (int)strlen(tokenString);
}
return 0;
}
}
return 0;
} // yylex
//Checks if the token just read is EOF or not.
int check_EOF(int token)
{
if(token==-1){
if(cpp->ifdepth >0){
CPPErrorToInfoLog("#endif missing!! Compilation stopped");
cpp->CompileError=1;
}
return 1;
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////// End of scanner.c //////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////

View file

@ -0,0 +1,118 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
/****************************************************************************\
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.
\****************************************************************************/
//
// scanner.h
//
#if !defined(__SCANNER_H)
#define __SCANNER_H 1
#define MAX_SYMBOL_NAME_LEN 128
#define MAX_STRING_LEN 512
#include "parser.h"
// Not really atom table stuff but needed first...
typedef struct SourceLoc_Rec {
unsigned short file, line;
} SourceLoc;
int yyparse (void);
int yylex_CPP(char* buf, int maxSize);
typedef struct InputSrc {
struct InputSrc *prev;
int (*scan)(struct InputSrc *, yystypepp *);
int (*getch)(struct InputSrc *, yystypepp *);
void (*ungetch)(struct InputSrc *, int, yystypepp *);
int name; /* atom */
int line;
} InputSrc;
int InitScanner(CPPStruct *cpp); // Intialise the cpp scanner.
int ScanFromString(char *); // Start scanning the input from the string mentioned.
int check_EOF(int); // check if we hit a EOF abruptly
void CPPErrorToInfoLog(char *); // sticking the msg,line into the Shader's.Info.log
void SetLineNumber(int);
void SetStringNumber(int);
void IncLineNumber(void);
void DecLineNumber(void);
int FreeScanner(void); // Free the cpp scanner
#endif // !(defined(__SCANNER_H)

View file

@ -0,0 +1,115 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
/****************************************************************************\
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.
\****************************************************************************/
//
// slglobals.h
//
#if !defined(__SLGLOBALS_H)
#define __SLGLOBALS_H 1
typedef struct CPPStruct_Rec CPPStruct;
extern CPPStruct *cpp;
#undef CPPC_DEBUG_THE_COMPILER
#if defined(_DEBUG)
#define CPPC_DEBUG_THE_COMPILER 1
#endif
#undef CPPC_ENABLE_TOOLS
#define CPPC_ENABLE_TOOLS 1
#include "memory.h"
#include "atom.h"
#include "scanner.h"
#include "cpp.h"
#include "tokens.h"
#include "symbols.h"
#include "compile.h"
#if !defined(NO_PARSER)
#include "parser.h"
#endif
#if !defined(NULL)
#define NULL 0
#endif
#endif // !(defined(__SLGLOBALS_H)

View file

@ -0,0 +1,318 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
/****************************************************************************\
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.
\****************************************************************************/
//
// symbols.c
//
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "slglobals.h"
///////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////// Symbol Table Variables: ///////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
Scope *ScopeList = NULL;
Scope *CurrentScope = NULL;
Scope *GlobalScope = NULL;
static void unlinkScope(void *_scope) {
Scope *scope = _scope;
if (scope->next)
scope->next->prev = scope->prev;
if (scope->prev)
scope->prev->next = scope->next;
else
ScopeList = scope->next;
}
/*
* NewScope()
*
*/
Scope *NewScopeInPool(MemoryPool *pool)
{
Scope *lScope;
lScope = mem_Alloc(pool, sizeof(Scope));
lScope->pool = pool;
lScope->parent = NULL;
lScope->funScope = NULL;
lScope->symbols = NULL;
lScope->level = 0;
lScope->programs = NULL;
if ((lScope->next = ScopeList))
ScopeList->prev = lScope;
lScope->prev = 0;
ScopeList = lScope;
mem_AddCleanup(pool, unlinkScope, lScope);
return lScope;
} // NewScope
/*
* PushScope()
*
*/
void PushScope(Scope *fScope)
{
Scope *lScope;
if (CurrentScope) {
fScope->level = CurrentScope->level + 1;
if (fScope->level == 1) {
if (!GlobalScope) {
/* HACK - CTD -- if GlobalScope==NULL and level==1, we're
* defining a function in the superglobal scope. Things
* will break if we leave the level as 1, so we arbitrarily
* set it to 2 */
fScope->level = 2;
}
}
if (fScope->level >= 2) {
lScope = fScope;
while (lScope->level > 2)
lScope = lScope->next;
fScope->funScope = lScope;
}
} else {
fScope->level = 0;
}
fScope->parent = CurrentScope;
CurrentScope = fScope;
} // PushScope
/*
* PopScope()
*
*/
Scope *PopScope(void)
{
Scope *lScope;
lScope = CurrentScope;
if (CurrentScope)
CurrentScope = CurrentScope->parent;
return lScope;
} // PopScope
/*
* NewSymbol() - Allocate a new symbol node;
*
*/
Symbol *NewSymbol(SourceLoc *loc, Scope *fScope, int name, symbolkind kind)
{
Symbol *lSymb;
char *pch;
int ii;
lSymb = (Symbol *) mem_Alloc(fScope->pool, sizeof(Symbol));
lSymb->left = NULL;
lSymb->right = NULL;
lSymb->next = NULL;
lSymb->name = name;
lSymb->loc = *loc;
lSymb->kind = kind;
// Clear union area:
pch = (char *) &lSymb->details;
for (ii = 0; ii < sizeof(lSymb->details); ii++)
*pch++ = 0;
return lSymb;
} // NewSymbol
/*
* lAddToTree() - Using a binary tree is not a good idea for basic atom values because they
* are generated in order. We'll fix this later (by reversing the bit pattern).
*/
static void lAddToTree(Symbol **fSymbols, Symbol *fSymb)
{
Symbol *lSymb;
int lrev, frev;
lSymb = *fSymbols;
if (lSymb) {
frev = GetReversedAtom(atable, fSymb->name);
while (lSymb) {
lrev = GetReversedAtom(atable, lSymb->name);
if (lrev == frev) {
CPPErrorToInfoLog("GetAtomString(atable, fSymb->name)");
break;
} else {
if (lrev > frev) {
if (lSymb->left) {
lSymb = lSymb->left;
} else {
lSymb->left = fSymb;
break;
}
} else {
if (lSymb->right) {
lSymb = lSymb->right;
} else {
lSymb->right = fSymb;
break;
}
}
}
}
} else {
*fSymbols = fSymb;
}
} // lAddToTree
/*
* AddSymbol() - Add a variable, type, or function name to a scope.
*
*/
Symbol *AddSymbol(SourceLoc *loc, Scope *fScope, int atom, symbolkind kind)
{
Symbol *lSymb;
if (!fScope)
fScope = CurrentScope;
lSymb = NewSymbol(loc, fScope, atom, kind);
lAddToTree(&fScope->symbols, lSymb);
return lSymb;
} // AddSymbol
/*********************************************************************************************/
/************************************ Symbol Semantic Functions ******************************/
/*********************************************************************************************/
/*
* LookUpLocalSymbol()
*
*/
Symbol *LookUpLocalSymbol(Scope *fScope, int atom)
{
Symbol *lSymb;
int rname, ratom;
ratom = GetReversedAtom(atable, atom);
if (!fScope)
fScope = CurrentScope;
lSymb = fScope->symbols;
while (lSymb) {
rname = GetReversedAtom(atable, lSymb->name);
if (rname == ratom) {
return lSymb;
} else {
if (rname > ratom) {
lSymb = lSymb->left;
} else {
lSymb = lSymb->right;
}
}
}
return NULL;
} // LookUpLocalSymbol
/*
* LookUpSymbol()
*
*/
Symbol *LookUpSymbol(Scope *fScope, int atom)
{
Symbol *lSymb;
if (!fScope)
fScope = CurrentScope;
while (fScope) {
lSymb = LookUpLocalSymbol(fScope, atom);
if (lSymb)
return lSymb;
fScope = fScope->parent;
}
return NULL;
} // LookUpSymbol

View file

@ -0,0 +1,145 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
/****************************************************************************\
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.
\****************************************************************************/
//
// symbols.h
//
#if !defined(__SYMBOLS_H)
#define __SYMBOLS_H 1
#include "memory.h"
typedef enum symbolkind {
MACRO_S
} symbolkind;
// Typedefs for things defined here in "symbols.h":
typedef struct Scope_Rec Scope;
typedef struct Symbol_Rec Symbol;
typedef struct SymbolList_Rec {
struct SymbolList_Rec *next;
Symbol *symb;
} SymbolList;
struct Scope_Rec {
Scope *next, *prev; // doubly-linked list of all scopes
Scope *parent;
Scope *funScope; // Points to base scope of enclosing function
MemoryPool *pool; // pool used for allocation in this scope
Symbol *symbols;
int level; // 0 = super globals, 1 = globals, etc.
// Only used at global scope (level 1):
SymbolList *programs; // List of programs for this compilation.
};
// Symbol table is a simple binary tree.
#include "cpp.h" // to get MacroSymbol def
struct Symbol_Rec {
Symbol *left, *right;
Symbol *next;
int name; // Name atom
SourceLoc loc;
symbolkind kind;
union {
MacroSymbol mac;
} details;
};
extern Scope *CurrentScope;
extern Scope *GlobalScope;
extern Scope *ScopeList;
Scope *NewScopeInPool(MemoryPool *);
#define NewScope() NewScopeInPool(CurrentScope->pool)
void PushScope(Scope *fScope);
Scope *PopScope(void);
Symbol *NewSymbol(SourceLoc *loc, Scope *fScope, int name, symbolkind kind);
Symbol *AddSymbol(SourceLoc *loc, Scope *fScope, int atom, symbolkind kind);
Symbol *LookUpLocalSymbol(Scope *fScope, int atom);
Symbol *LookUpSymbol(Scope *fScope, int atom);
void CPPErrorToInfoLog(char *);
#endif // !defined(__SYMBOLS_H)

View file

@ -0,0 +1,472 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
/****************************************************************************\
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.
\****************************************************************************/
//
// tokens.c
//
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "slglobals.h"
///////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////// Preprocessor and Token Recorder and Playback: ////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
/*
* idstr()
* Copy a string to a malloc'ed block and convert it into something suitable
* for an ID
*
*/
static char *idstr(const char *fstr, MemoryPool *pool)
{
size_t len;
char *str, *t;
const char *f;
len = strlen(fstr);
if (!pool)
str = (char *) malloc(len + 1);
else
str = (char *) mem_Alloc(pool, len + 1);
for (f=fstr, t=str; *f; f++) {
if (isalnum(*f)) *t++ = *f;
else if (*f == '.' || *f == '/') *t++ = '_';
}
*t = 0;
return str;
} // idstr
/*
* lNewBlock()
*
*/
static TokenBlock *lNewBlock(TokenStream *fTok, MemoryPool *pool)
{
TokenBlock *lBlock;
if (!pool)
lBlock = (TokenBlock *) malloc(sizeof(TokenBlock) + 256);
else
lBlock = (TokenBlock *) mem_Alloc(pool, sizeof(TokenBlock) + 256);
lBlock->count = 0;
lBlock->current = 0;
lBlock->data = (unsigned char *) lBlock + sizeof(TokenBlock);
lBlock->max = 256;
lBlock->next = NULL;
if (fTok->head) {
fTok->current->next = lBlock;
} else {
fTok->head = lBlock;
}
fTok->current = lBlock;
return lBlock;
} // lNewBlock
/*
* lAddByte()
*
*/
static void lAddByte(TokenStream *fTok, unsigned char fVal)
{
TokenBlock *lBlock;
lBlock = fTok->current;
if (lBlock->count >= lBlock->max)
lBlock = lNewBlock(fTok, 0);
lBlock->data[lBlock->count++] = fVal;
} // lAddByte
/*
* lReadByte() - Get the next byte from a stream.
*
*/
static int lReadByte(TokenStream *pTok)
{
TokenBlock *lBlock;
int lval = -1;
lBlock = pTok->current;
if (lBlock) {
if (lBlock->current >= lBlock->count) {
lBlock = lBlock->next;
if (lBlock)
lBlock->current = 0;
pTok->current = lBlock;
}
if (lBlock)
lval = lBlock->data[lBlock->current++];
}
return lval;
} // lReadByte
/////////////////////////////////////// Global Functions://////////////////////////////////////
/*
* NewTokenStream()
*
*/
TokenStream *NewTokenStream(const char *name, MemoryPool *pool)
{
TokenStream *pTok;
if (!pool)
pTok = (TokenStream *) malloc(sizeof(TokenStream));
else
pTok = (TokenStream*)mem_Alloc(pool, sizeof(TokenStream));
pTok->next = NULL;
pTok->name = idstr(name, pool);
pTok->head = NULL;
pTok->current = NULL;
lNewBlock(pTok, pool);
return pTok;
} // NewTokenStream
/*
* DeleteTokenStream()
*
*/
void DeleteTokenStream(TokenStream *pTok)
{
TokenBlock *pBlock, *nBlock;
if (pTok) {
pBlock = pTok->head;
while (pBlock) {
nBlock = pBlock->next;
free(pBlock);
pBlock = nBlock;
}
if (pTok->name)
free(pTok->name);
free(pTok);
}
} // DeleteTokenStream
/*
* RecordToken() - Add a token to the end of a list for later playback or printout.
*
*/
void RecordToken(TokenStream *pTok, int token, yystypepp * yylvalpp)
{
const char *s;
unsigned char *str=NULL;
if (token > 256)
lAddByte(pTok, (unsigned char)((token & 0x7f) + 0x80));
else
lAddByte(pTok, (unsigned char)(token & 0x7f));
switch (token) {
case CPP_IDENTIFIER:
case CPP_TYPEIDENTIFIER:
case CPP_STRCONSTANT:
s = GetAtomString(atable, yylvalpp->sc_ident);
while (*s)
lAddByte(pTok, (unsigned char) *s++);
lAddByte(pTok, 0);
break;
case CPP_FLOATCONSTANT:
case CPP_INTCONSTANT:
str=yylvalpp->symbol_name;
while (*str){
lAddByte(pTok,(unsigned char) *str);
*str++;
}
lAddByte(pTok, 0);
break;
case '(':
lAddByte(pTok, (unsigned char)(yylvalpp->sc_int ? 1 : 0));
default:
break;
}
} // RecordToken
/*
* RewindTokenStream() - Reset a token stream in preperation for reading.
*
*/
void RewindTokenStream(TokenStream *pTok)
{
if (pTok->head) {
pTok->current = pTok->head;
pTok->current->current = 0;
}
} // RewindTokenStream
/*
* ReadToken() - Read the next token from a stream.
*
*/
int ReadToken(TokenStream *pTok, yystypepp * yylvalpp)
{
char symbol_name[MAX_SYMBOL_NAME_LEN + 1];
char string_val[MAX_STRING_LEN + 1];
int ltoken, len;
char ch;
ltoken = lReadByte(pTok);
if (ltoken >= 0) {
if (ltoken > 127)
ltoken += 128;
switch (ltoken) {
case CPP_IDENTIFIER:
case CPP_TYPEIDENTIFIER:
len = 0;
ch = lReadByte(pTok);
while ((ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') ||
ch == '_')
{
if (len < MAX_SYMBOL_NAME_LEN) {
symbol_name[len] = ch;
len++;
ch = lReadByte(pTok);
}
}
symbol_name[len] = '\0';
assert(ch == '\0');
yylvalpp->sc_ident = LookUpAddString(atable, symbol_name);
return CPP_IDENTIFIER;
break;
case CPP_STRCONSTANT:
len = 0;
while ((ch = lReadByte(pTok)) != 0)
if (len < MAX_STRING_LEN)
string_val[len++] = ch;
string_val[len] = 0;
yylvalpp->sc_ident = LookUpAddString(atable, string_val);
break;
case CPP_FLOATCONSTANT:
len = 0;
ch = lReadByte(pTok);
while ((ch >= '0' && ch <= '9')||(ch=='e'||ch=='E'||ch=='.')||(ch=='+'||ch=='-'))
{
if (len < MAX_SYMBOL_NAME_LEN) {
symbol_name[len] = ch;
len++;
ch = lReadByte(pTok);
}
}
symbol_name[len] = '\0';
assert(ch == '\0');
strcpy(yylvalpp->symbol_name,symbol_name);
yylvalpp->sc_fval=(float)atof(yylvalpp->symbol_name);
break;
case CPP_INTCONSTANT:
len = 0;
ch = lReadByte(pTok);
while ((ch >= '0' && ch <= '9'))
{
if (len < MAX_SYMBOL_NAME_LEN) {
symbol_name[len] = ch;
len++;
ch = lReadByte(pTok);
}
}
symbol_name[len] = '\0';
assert(ch == '\0');
strcpy(yylvalpp->symbol_name,symbol_name);
yylvalpp->sc_int=atoi(yylvalpp->symbol_name);
break;
case '(':
yylvalpp->sc_int = lReadByte(pTok);
break;
}
return ltoken;
}
return EOF_SY;
} // ReadToken
typedef struct TokenInputSrc {
InputSrc base;
TokenStream *tokens;
int (*final)(CPPStruct *);
} TokenInputSrc;
static int scan_token(TokenInputSrc *in, yystypepp * yylvalpp)
{
int token = ReadToken(in->tokens, yylvalpp);
int (*final)(CPPStruct *);
cpp->tokenLoc->file = cpp->currentInput->name;
cpp->tokenLoc->line = cpp->currentInput->line;
if (token == '\n') {
in->base.line++;
return token;
}
if (token > 0) return token;
cpp->currentInput = in->base.prev;
final = in->final;
free(in);
if (final && !final(cpp)) return -1;
return cpp->currentInput->scan(cpp->currentInput, yylvalpp);
}
int ReadFromTokenStream(TokenStream *ts, int name, int (*final)(CPPStruct *))
{
TokenInputSrc *in = malloc(sizeof(TokenInputSrc));
memset(in, 0, sizeof(TokenInputSrc));
in->base.name = name;
in->base.prev = cpp->currentInput;
in->base.scan = (int (*)(InputSrc *, yystypepp *))scan_token;
in->base.line = 1;
in->tokens = ts;
in->final = final;
RewindTokenStream(ts);
cpp->currentInput = &in->base;
return 1;
}
typedef struct UngotToken {
InputSrc base;
int token;
yystypepp lval;
} UngotToken;
static int reget_token(UngotToken *t, yystypepp * yylvalpp)
{
int token = t->token;
*yylvalpp = t->lval;
cpp->currentInput = t->base.prev;
free(t);
return token;
}
void UngetToken(int token, yystypepp * yylvalpp) {
UngotToken *t = malloc(sizeof(UngotToken));
memset(t, 0, sizeof(UngotToken));
t->token = token;
t->lval = *yylvalpp;
t->base.scan = (void *)reget_token;
t->base.prev = cpp->currentInput;
t->base.name = cpp->currentInput->name;
t->base.line = cpp->currentInput->line;
cpp->currentInput = &t->base;
}
void DumpTokenStream(FILE *fp, TokenStream *s, yystypepp * yylvalpp) {
int token;
char str[100];
if (fp == 0) fp = stdout;
RewindTokenStream(s);
while ((token = ReadToken(s, yylvalpp)) > 0) {
switch (token) {
case CPP_IDENTIFIER:
case CPP_TYPEIDENTIFIER:
sprintf(str, "%s ", GetAtomString(atable, yylvalpp->sc_ident));
break;
case CPP_STRCONSTANT:
sprintf(str, "\"%s\"", GetAtomString(atable, yylvalpp->sc_ident));
break;
case CPP_FLOATCONSTANT:
//printf("%g9.6 ", yylvalpp->sc_fval);
break;
case CPP_INTCONSTANT:
//printf("%d ", yylvalpp->sc_int);
break;
default:
if (token >= 127)
sprintf(str, "%s ", GetAtomString(atable, token));
else
sprintf(str, "%c", token);
break;
}
CPPDebugLogMsg(str);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////// End of tokens.c ///////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////

View file

@ -0,0 +1,122 @@
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
/****************************************************************************\
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.
\****************************************************************************/
//
// tokens.h
//
#if !defined(__TOKENS_H)
#define __TOKENS_H 1
#include "parser.h"
#define EOF_SY (-1)
typedef struct TokenBlock_Rec TokenBlock;
typedef struct TokenStream_Rec {
struct TokenStream_Rec *next;
char *name;
TokenBlock *head;
TokenBlock *current;
} TokenStream;
struct TokenBlock_Rec {
TokenBlock *next;
int current;
int count;
int max;
unsigned char *data;
};
extern TokenStream stdlib_cpp_stream;
TokenStream *NewTokenStream(const char *name, MemoryPool *pool);
void DeleteTokenStream(TokenStream *pTok);
void RecordToken(TokenStream *pTok, int token, yystypepp * yylvalpp);
void RewindTokenStream(TokenStream *pTok);
int ReadToken(TokenStream *pTok, yystypepp * yylvalpp);
int ReadFromTokenStream(TokenStream *pTok, int name, int (*final)(CPPStruct *));
void UngetToken(int, yystypepp * yylvalpp);
#if defined(CPPC_ENABLE_TOOLS)
void DumpTokenStream(FILE *, TokenStream *, yystypepp * yylvalpp);
#endif // defined(CPPC_ENABLE_TOOLS)
#endif // !defined(__TOKENS_H)

View file

@ -0,0 +1 @@
// This is a NULL file and is meant to be empty