code
stringlengths
1
2.06M
language
stringclasses
1 value
#include "AABB.hpp" #include "Quaternion.hpp" #include "Renderer/VBO.hpp" namespace engine { AABB::AABB(Vector3F pOrigin, Vector3F pEnd) : mOrigin(pOrigin), mEnd(pEnd){ } void AABB::Init(Vector3F* pVertices, u32 pSize){ for(u32 i = 0; i < pSize; ++i){ mOrigin.x = Math::Min(pVertices[i].x, mOrigin.x); mOrigin.y = Math::Min(pVertices[i].y, mOrigin.y); mOrigin.z = Math::Min(pVertices[i].z, mOrigin.z); mEnd.x = Math::Max(pVertices[i].x, mEnd.x); mEnd.y = Math::Max(pVertices[i].y, mEnd.y); mEnd.z = Math::Max(pVertices[i].z, mEnd.z); } } void AABB::Scale(const Vector3F &pScaleFactor){ mOrigin.x *= pScaleFactor.x; mOrigin.y *= pScaleFactor.y; mOrigin.z *= pScaleFactor.z; mEnd.x *= pScaleFactor.x; mEnd.y *= pScaleFactor.y; mEnd.z *= pScaleFactor.z; } void AABB::Translate(const Vector3F &pTrans){ mOrigin += pTrans; mEnd += pTrans; } void AABB::GetVertices(Vector3F pTab[8]) const{ pTab[0] = mOrigin; pTab[1] = Vector3F(mEnd.x, mOrigin.y, mOrigin.z); pTab[2] = Vector3F(mOrigin.x, mEnd.y, mOrigin.z); pTab[3] = Vector3F(mOrigin.x, mOrigin.y, mEnd.z); pTab[4] = Vector3F(mOrigin.x, mEnd.y, mEnd.z); pTab[5] = Vector3F(mEnd.x, mOrigin.y, mEnd.z); pTab[6] = Vector3F(mEnd.x, mEnd.y, mOrigin.z); pTab[7] = mEnd; } void BSphere::Init(const AABB &pAABB){ mOrigin.x = (pAABB.mOrigin.x + pAABB.mEnd.x) / 2; mOrigin.y = (pAABB.mOrigin.y + pAABB.mEnd.y) / 2; mOrigin.z = (pAABB.mOrigin.z + pAABB.mEnd.z) / 2; mRadius = (pAABB.mEnd - pAABB.mOrigin).Norme(); } }
C++
inline engine::Quaternion::Quaternion(f32 X, f32 Y, f32 Z, f32 W) : x(X), y(Y), z(Z), w(W){ } inline engine::Quaternion::Quaternion(const Matrix4 &mat){ FromMatrix(mat); } inline engine::Quaternion::Quaternion(const Vector3F &Axis, f32 Angle){ FromAxisAngle(Axis, Angle); } inline Quaternion engine::Quaternion::Conjugate() const{ return Quaternion(-x, -y, -z, w); } inline void engine::Quaternion::Identity(){ x = y = z = 0.f; w = 1.f; } inline void engine::Quaternion::Normalize(){ f32 norme = x * x + y * y + z * z + w * w; if(norme != 0.f && (Math::Abs(norme) - 1.f) > Math::Epsilon){ norme = Math::Sqrt(norme); x /= norme; y /= norme; z /= norme; w /= norme; } } inline void engine::Quaternion::FromEulerAngle(f32 X, f32 Y, f32 Z){ Quaternion Qx(Math::Cos(X/2), Math::Sin(X/2), 0, 0); Quaternion Qy(Math::Cos(Y/2), 0, Math::Sin(Y/2), 0); Quaternion Qz(Math::Cos(Z/2), 0, 0, Math::Sin(Z/2)); *this = Qx * Qy * Qz; } inline void engine::Quaternion::FromMatrix(const Matrix4 &mat){ f32 trace = mat(0, 0) + mat(1, 1) + mat(2, 2) + 1; if(trace > 0){ f32 s = 0.5f / Math::Sqrt(trace); x = (mat(2,1) - mat(1,2)) * s; y = (mat(0,2) - mat(2,0)) * s; z = (mat(1,0) - mat(0,1)) * s; w = 0.25f / s; }else{ if (mat(0, 0) > mat(1, 1) && (mat(0, 0) > mat(2, 2))){ f32 s = Math::Sqrt(1 + mat(0, 0) - mat(1, 1) - mat(2, 2)) * 2; x = 0.5f / s; y = (mat(0, 1) + mat(1, 0)) / s; z = (mat(0, 2) + mat(2, 0)) / s; w = (mat(1, 2) + mat(2, 1)) / s; } else if (mat(1, 1) > mat(2, 2)){ f32 s = Math::Sqrt(1 - mat(0, 0) + mat(1, 1) - mat(2, 2)) * 2; x = (mat(0, 1) + mat(1, 0)) / s; y = 0.5f / s; z = (mat(1, 2) + mat(2, 1)) / s; w = (mat(0, 2) + mat(2, 0)) / s; } else{ f32 s = Math::Sqrt(1 - mat(0, 0) - mat(1, 1) + mat(2, 2)) * 2; x = (mat(0, 2) + mat(2, 0)) / s; y = (mat(1, 2) + mat(2, 1)) / s; z = 0.5f / s; w = (mat(0, 1) + mat(1, 0)) / s; } } } inline Matrix4 engine::Quaternion::ToMatrix() const{ f32 x2 = x * x; f32 y2 = y * y; f32 z2 = z * z; f32 xy = x * y; f32 wz = w * z; f32 xz = x * z; f32 wy = w * y; f32 yz = y * z; f32 wx = w * x; return Matrix4( 1 - 2*(y2+z2) , 2 * (xy - wz) , 2 * (xz + wy) , 0, 2 * (xy + wz) , 1 - 2*(x2 + z2) , 2*(yz - wx) , 0, 2 * (xz - wy) , 2 * (yz + wx) , 1 - 2*(x2 + y2) , 0, 0 , 0 , 0 , 1 ); } inline void engine::Quaternion::FromAxisAngle(const Vector3F &Axis, f32 Angle){ f32 Cos = Math::Cos(Angle / 2); f32 Sin = Math::Sin(Angle / 2); x = Axis.x * Sin; y = Axis.y * Sin; z = Axis.z * Sin; w = Cos; Normalize(); } inline void engine::Quaternion::ToAxisAngle(Vector3F &Axis, f32 &Angle) const{ if(w == 1){ Angle = 0; Axis.Set(0,1,0); // Axis arbitraire (pas de rotation anyway) }else{ Angle = Math::ACos(w) * 2; f32 norme = Math::Sqrt(1 - w * w); Axis.Set(x,y,z); Axis /= norme; } } inline Quaternion engine::Quaternion::operator*(const Quaternion &quat) const{ return Quaternion( w * quat.x + x * quat.w + y * quat.z - z * quat.y, w * quat.y + y * quat.w + z * quat.x - x * quat.z, w * quat.z + z * quat.w + x * quat.y - y * quat.x, w * quat.w - x * quat.x - y * quat.y - z * quat.z); } inline const Quaternion& engine::Quaternion::operator*=(const Quaternion &quat){ *this = *this * quat; return *this; } inline Vector3F engine::Quaternion::operator*(const Vector3F &pVec) const{ Vector3F vec(pVec); vec.Normalize(); Quaternion vectorQuat(vec.x, vec.y, vec.z, 0.f), resultQuat; resultQuat = vectorQuat * Conjugate(); resultQuat = *this * resultQuat; return Vector3F(resultQuat.x, resultQuat.y, resultQuat.z); } inline Quaternion engine::Quaternion::operator-() const{ Quaternion neg; neg.x = -x; neg.y = -y; neg.z = -z; neg.w = -w; return neg; } inline std::istream & operator>> (std::istream &iss, Quaternion &quat){ return iss >> quat.x >> quat.y >> quat.z >> quat.w; } inline std::ostream & operator<< (std::ostream &oss, const Quaternion &quat){ return oss << quat.x << " " << quat.y << " " << quat.z << " " << quat.w; }
C++
#ifndef QUATERNION_HPP #define QUATERNION_HPP #include "Mathlib.hpp" #include "Matrix4.hpp" namespace engine { class Quaternion{ public: /// \brief Ctor from 4 floats Quaternion(f32 X = 0, f32 Y = 0, f32 Z = 0, f32 W = 0); /// \brief Ctor from matrix Quaternion(const Matrix4 &mat); /// \brief Ctor from Axis-Angle Quaternion(const Vector3F &Axis, f32 Angle); /// \brief Returns the quaternion conjugate Quaternion Conjugate() const; /// \brief Make the quaternion an Identity quaternion void Identity(); /// \brief Normalize the quaternion void Normalize(); /// \brief Returns a Rotation matrix containing the quaternion orientation Matrix4 ToMatrix() const; /// \brief Create the quaternion from Matrix4 void FromMatrix(const Matrix4 &mat); /// \brief Create the quaternion from Axis-Angle void FromAxisAngle(const Vector3F &Axis, f32 Angle); /// \brief Create the quaternion from three Euler Angles void FromEulerAngle(f32 X, f32 Y, f32 Z); /// \brief Returns the Axis-Angle form of the quaternion /// \param Axis : Vector that'll contain the axis of the quaternion /// \param Angle : float that'll contain the angle of the quaternion void ToAxisAngle(Vector3F &Axis, f32 &Angle) const; /// \brief Multiply functions Quaternion operator*(const Quaternion &quat) const; const Quaternion& operator*=(const Quaternion& quat); /// \brief Returns the result of the multiplication with a vector Vector3F operator*(const Vector3F &pVec) const; /// \brief Returns the negate of the quaternion Quaternion operator-() const; f32 x; f32 y; f32 z; f32 w; }; /// \brief Stream Ops std::istream& operator >> (std::istream& iss, Quaternion &quat); std::ostream& operator << (std::ostream& oss, const Quaternion &quat); #include "Quaternion.inl" } #endif
C++
#ifndef VECTOR3_HPP #define VECTOR3_HPP #include "Mathlib.hpp" namespace engine { class Matrix4; template<class T> class Vector3{ public: Vector3(T x = 0, T y = 0, T z =0); // Sets vector components void Set(T x, T y, T z); // Returns the vector components in an array void XYZ(T pTab[]) const; // Returns the vector length T Norme() const; // Returns the squared length (used internally for Norme()) T NormeSq() const; // Normalize the vector void Normalize(); // Scale the vector from an Origin point and a scalle Factor void ScaleFrom(const Vector3<T> &pCenter, f32 pScaleFactor); // Returns the negate of the vector Vector3<T> operator- () const; // Binary operators Vector3<T> operator+ (const Vector3<T> &V) const; Vector3<T> operator- (const Vector3<T> &V) const; Vector3<T>& operator+= (const Vector3<T> &V) ; Vector3<T>& operator -= (const Vector3<T> &V) ; Vector3<T> operator*(T t) const; Vector3<T> operator/(T t) const; Vector3<T>& operator*= (T t); Vector3<T>& operator /= (T t); // Comparison operators bool operator==(const Vector3<T> &V) const; bool operator!=(const Vector3<T> &V) const; // Returns a pointer on x operator T*(); // Static constant // Zeroed Vector static const OOXAPI Vector3 ZERO; // Normal Vectors static const OOXAPI Vector3 UNIT_Z; // +Z static const OOXAPI Vector3 NEGUNIT_Z; // -Z static const OOXAPI Vector3 UNIT_X; // +X static const OOXAPI Vector3 NEGUNIT_X; // -X static const OOXAPI Vector3 UNIT_Y; // +Y static const OOXAPI Vector3 NEGUNIT_Y; // -Y // Data T x; T y; T z; }; // Result of multiplication between a vector and a T template<class T> Vector3<T> operator* (const Vector3<T> &V, T t); // Result of division between a vector and a T template<class T> Vector3<T> operator/ (const Vector3<T> &V, T t); // Result of multiplication between a T and a vector template<class T> Vector3<T> operator* (T t, const Vector3<T> &V); // Dot product between two vector3 template<class T> T Dot(const Vector3<T> &U, const Vector3<T> &V); // Cross product between two vector3 template<class T> Vector3<T> Cross(const Vector3<T> &U, const Vector3<T> &V); // Stream Ops template<class T> std::istream& operator >>(std::istream& iss, Vector3<T> &V); template<class T> std::ostream& operator <<(std::ostream& oss, const Vector3<T> &V); #include "Vector3.inl" typedef Vector3<s32> Vector3I; typedef Vector3<f32> Vector3F; } #endif
C++
#include "Image.hpp" #include "Core/ResourceManager.hpp" #include "Debug/Debug.hpp" namespace engine { Image::Image(const Vector2I &pSize) : mSize(pSize), mBPP(GL_RGBA8), mFormat(GL_RGBA){ } Image::Image(const std::string &pName, const Vector2I &pSize, sf::Image &pSurface) : mSize(pSize), mBPP(GL_RGBA8), mFormat(GL_RGBA), mSurface(pSurface){ SetName(pName); } Image::~Image(){ } const Vector2I& Image::GetSize() const{ return mSize; } u32 Image::GetBytesPerPixel() const{ return mBPP; } u32 Image::GetFormat() const{ return mFormat; } const u8* Image::GetData() const{ return const_cast<u8*>(mSurface.GetPixelsPtr()); } bool Image::LoadFromFile(const std::string &pFileName){ bool ret = true; // Try to find Image in ResourceManager first, so we don't load it twice Image* temp = ResourceManager::Call().Get<Image>(pFileName); // If image does not exist yet if(!temp){ // Try to find it in Image Resources Path std::string filePath = ResourceManager::Call().FindFile(pFileName, "Image"); // If it doesn't exist, Error and bad return. if(filePath == "0"){ ret = false; OmniLog << "File \"" << pFileName << "\" does not exist in Image directory." << eol; }else{ // If it exists but fail to load, Error and bad return if(!mSurface.LoadFromFile(filePath)){ ret = false; OmniLog << "File \"" << filePath << "\" is not a valid Image File." << eol; }else{ mSize = Vector2I(mSurface.GetWidth(), mSurface.GetHeight()); #ifdef _DEBUG BaseLog << "DEBUG : \"" << pFileName << "\" image loaded." << eol; #endif // Add it To the ResourceManager ResourceManager::Call().Add(pFileName, this); } } }else{ // If it exists already, send error message and bad return ret = false; OmniLog << "Image : \"" << pFileName << "\" has already been loaded" << eol; } return ret; } }
C++
#include "Camera.hpp" #include "Renderer/Renderer.hpp" namespace engine{ Camera::Camera() : mName("Camera1"), mPosition(Vector3F::ZERO) { Init(); } Camera::Camera(const Vector3F &Pos) : mPosition(Pos) { Init(); } Camera::~Camera(){ } void Camera::Init(){ mSpeed = 10.f; mSensivity = 0.1f; mRpm = 10.f; mCurrRenderer = Renderer::Get(); } void Camera::SetPosition(const Vector3F &Pos){ mPosition = Pos; Update(); } void Camera::SetOrientation(const Quaternion &Quat){ mOrientation = Quat; Update(); } const Vector3F Camera::GetAxisX() const{ Vector3F ret; ret.x = ViewMatrix.a11; ret.y = ViewMatrix.a21; ret.z = ViewMatrix.a31; return ret; } const Vector3F Camera::GetAxisY() const{ Vector3F ret; ret.x = ViewMatrix.a12; ret.y = ViewMatrix.a22; ret.z = ViewMatrix.a32; return ret; } const Vector3F Camera::GetAxisZ() const{ Vector3F ret; ret.x = ViewMatrix.a13; ret.y = ViewMatrix.a23; ret.z = ViewMatrix.a33; return ret; } const Matrix4& Camera::GetViewMatrix(){ if(mNeedUpdate) Update(); return ViewMatrix; } void Camera::Update(){ Matrix4 matTranslation, matRotation; // Calcul de la nouvelle matrice de vue matTranslation.SetTranslation(-mPosition.x, -mPosition.y, -mPosition.z); matRotation = mOrientation.ToMatrix(); ViewMatrix = matTranslation * matRotation; // Envoi de la matrice au renderer pour calcul de la ViewProjMatrix mCurrRenderer->Set3DViewMatrix(ViewMatrix); // Recuperation de la ViewProjMatrix pour calculer le nouveau Frustum mFrustum.SetFrustum(mCurrRenderer->Get3DViewProjMatrix()); mNeedUpdate = false; } void Camera::LookAt(const Vector3F &To, const Vector3F &From){ Matrix4 temp; temp.LookAt(From, To, Vector3F::UNIT_Y); mPosition = From; mOrientation.FromMatrix(temp); Update(); } void Camera::ApplyTranslation(f32 dist, eCamDir dir){ Vector3F direction; switch(dir){ case CD_Forward : direction = -GetAxisZ(); break; case CD_Up : direction = GetAxisY(); break; case CD_Right : direction = GetAxisX(); break; } mPosition += direction * mSpeed * dist; Update(); } void Camera::ApplyRotation(f32 angle, eCamRot rot){ angle *= (-mRpm / 60.f); // multiplie par la vitesse de rotation switch(rot){ case CR_Yaw : RotateYAxis(angle); break; case CR_Pitch : RotateXAxis(angle); break; case CR_Roll : RotateZAxis(angle); break; } mOrientation.Normalize(); Update(); } void Camera::RotateXAxis(f32 angle){ Quaternion temp; temp.FromAxisAngle(Vector3F::UNIT_X, angle); mOrientation *= temp; } void Camera::RotateYAxis(f32 angle){ Quaternion temp; temp.FromAxisAngle(Vector3F::UNIT_Y, angle); mOrientation = temp * mOrientation; // (Autour de UNIT_Y Global et non local) } void Camera::RotateZAxis(f32 angle){ Quaternion temp; temp.FromAxisAngle(Vector3F::UNIT_Z, angle); mOrientation *= temp; } }
C++
#ifndef CAMERA_HPP #define CAMERA_HPP #include "Frustum.hpp" #include "Utils/Shared.hpp" #include "Math/Quaternion.hpp" namespace engine { class Renderer; enum eCamDir{ CD_Forward, CD_Right, CD_Up }; enum eCamRot{ CR_Pitch, CR_Roll, CR_Yaw }; /// \brief Camera Class, Freefly only for now class OOXAPI Camera{ public: Camera(); Camera(const Vector3F &Pos); ~Camera(); /// \brief Initialise Camera with default values void Init(); /// \brief Set the Camera position /// \param Pos : new Position void SetPosition(const Vector3F &Pos); /// \brief Set the Camera orientation /// \param Quat : new Orientation void SetOrientation(const Quaternion &Quat); /// \brief Returns the X Normal Axis of the camera const Vector3F GetAxisX() const; /// \brief Returns the Y Normal Axis of the camera const Vector3F GetAxisY() const; /// \brief Returns the Z Normal Axis of the camera const Vector3F GetAxisZ() const; /// \brief Move the camera on the Right (X) Axis void MoveRight(f32 dist) { ApplyTranslation(dist, CD_Right); } /// \brief Move the camera on the Up (Y) Axis void MoveUp(f32 dist) { ApplyTranslation(dist, CD_Up); } /// \brief Move the camera on the Forward (Z) Axis void MoveForward(f32 dist) { ApplyTranslation(dist, CD_Forward); } /// \brief Rotate around the Right (X) Axis void Pitch(f32 angle) { ApplyRotation(angle, CR_Pitch); } /// \brief Rotate around the Up (Y) Axis void Yaw(f32 angle) { ApplyRotation(angle, CR_Yaw); } /// \brief Rotate around the Forward (Z) Axis void Roll(f32 angle) { ApplyRotation(angle, CR_Roll); } /// \brief Look At Function /// \param To : Position pointed by the camera /// \param From : Position of the camera void LookAt(const Vector3F &To, const Vector3F &From); /// \brief Change the rotation speed of the camera void SetRPM(f32 r) { mRpm = r; } /// \brief Change the movement speed of the camera void SetSpeed(f32 s) { mSpeed = s; } /// \brief Change the mouse sensitivity of the camera void SetSensivity(f32 s) { mSensivity = s; } /// \brief Change the name of the camera void SetName(const std::string &n) { mName = n; } /// Getters f32 GetSpeed() const { return mSpeed; } f32 GetSensivity() const { return mSensivity; } f32 GetRPM() const { return mRpm; } Vector3F GetPosition() const { return mPosition; } Quaternion GetOrientation() const { return mOrientation; } const std::string& GetName()const { return mName; } /// \brief Returns the ViewMatrix computed from the camera movement const Matrix4& GetViewMatrix(); /// \brief Returns the camera Frustum const Frustum& GetFrustum() const { return mFrustum; } private: std::string mName; Renderer* mCurrRenderer; void Update(); void ApplyRotation(f32 angle, eCamRot rot); void ApplyTranslation(f32 dist, eCamDir dir); void RotateXAxis(f32 angle); void RotateYAxis(f32 angle); void RotateZAxis(f32 angle); Matrix4 ViewMatrix; Frustum mFrustum; Vector3F mPosition; Quaternion mOrientation; f32 mSpeed; f32 mSensivity; f32 mRpm; bool mNeedUpdate; /// True if changes happened to camera position or orientation }; } #endif
C++
#include "Frustum.hpp" #include "Utils/String.hpp" #include "Debug/Debug.hpp" namespace engine { void Plane::Normalize(){ static f32 length = 0; length = 1.f / Math::Sqrt(A * A + B * B + C * C); A *= length; B *= length; C *= length; D *= length; } const Plane& Frustum::operator()(s32 pIndex) const{ switch(pIndex){ case 0: return mTop; case 1: return mBottom; case 2: return mLeft; case 3: return mRight; case 4: return mNear; case 5: return mFar; default: throw Exception(String("Frustum Plane No \"")+pIndex+"\" doesn't exist"); } } void Frustum::SetFrustum(const Matrix4 &pViewProj){ static s32 debug = 1; mLeft.A = pViewProj(0,3) + pViewProj(0,0); mLeft.B = pViewProj(1,3) + pViewProj(1,0); mLeft.C = pViewProj(2,3) + pViewProj(2,0); mLeft.D = pViewProj(3,3) + pViewProj(3,0); mLeft.Normalize(); if(!debug){ std::cout << "//////////////////////////////////////////////" << std::endl; std::cout << mLeft.A << " " << mLeft.B << " " << mLeft.C << " " << mLeft.D << eol; } mRight.A = pViewProj(0,3) - pViewProj(0,0); mRight.B = pViewProj(1,3) - pViewProj(1,0); mRight.C = pViewProj(2,3) - pViewProj(2,0); mRight.D = pViewProj(3,3) - pViewProj(3,0); mRight.Normalize(); if(!debug) std::cout << mRight.A << " " << mRight.B << " " << mRight.C << " " << mRight.D << eol; mBottom.A = pViewProj(0,3) + pViewProj(0,1); mBottom.B = pViewProj(1,3) + pViewProj(1,1); mBottom.C = pViewProj(2,3) + pViewProj(2,1); mBottom.D = pViewProj(3,3) + pViewProj(3,1); mBottom.Normalize(); if(!debug) std::cout << mBottom.A << " " << mBottom.B << " " << mBottom.C << " " << mBottom.D << eol; mTop.A = pViewProj(0,3) - pViewProj(0,1); mTop.B = pViewProj(1,3) - pViewProj(1,1); mTop.C = pViewProj(2,3) - pViewProj(2,1); mTop.D = pViewProj(3,3) - pViewProj(3,1); mTop.Normalize(); if(!debug) std::cout << mTop.A << " " << mTop.B << " " << mTop.C << " " << mTop.D << eol; mFar.A = pViewProj(0,3) - pViewProj(0,2); mFar.B = pViewProj(1,3) - pViewProj(1,2); mFar.C = pViewProj(2,3) - pViewProj(2,2); mFar.D = pViewProj(3,3) - pViewProj(3,2); mFar.Normalize(); if(!debug) std::cout << mFar.A << " " << mFar.B << " " << mFar.C << " " << mFar.D << eol; mNear.A = pViewProj(0,3) + pViewProj(0,2); mNear.B = pViewProj(1,3) + pViewProj(1,2); mNear.C = pViewProj(2,3) + pViewProj(2,2); mNear.D = pViewProj(3,3) + pViewProj(3,2); mNear.Normalize(); if(!debug){ std::cout << mNear.A << " " << mNear.B << " " << mNear.C << " " << mNear.D << eol; std::cout << "//////////////////////////////////////////////" << std::endl; } } bool Frustum::CubeInFrustum(const AABB &pCube) const { // Recuperation des vertices du cube AABB Vector3F corners[8]; pCube.GetVertices(corners); int inCount; // comptage des vertices a l'interieur du frustum pour // chaque plan for(int p = 0; p < 6; ++p){ inCount = 8; // Check du plan pour tous les vertices du cube for(int i = 0; i < 8; ++i){ if((Dot((*this)(p).GetNormal(), corners[i]) + (*this)(p).D) < 0){ --inCount; } } // Si le cube est completement en dehors d'un plan // L'objet n'est pas affiche if(inCount == 0) return false; } // Si au moins un point est dedans, on affiche return true; } }
C++
#ifndef FRUSTUM_HPP #define FRUSTUM_HPP #include "Math/AABB.hpp" #include "Math/Matrix4.hpp" namespace engine { /// \brief 3D Plane class Plane{ public: /// \brief Normalize the plane components void Normalize(); /// \brief Returns the plane normal Vector3F GetNormal() const { return Vector3F(A,B,C); } /// Components f32 A, /// N.x B, /// N.y C, /// N.z D; /// Distance }; /// \brief Camera Frustum used for Frustum Culling class OOXAPI Frustum{ public: /// \brief Sets the Frustum Planes from ViewProj Matrix void SetFrustum(const Matrix4 &pViewProj); /// \brief Check if a cube is in the Frustum bool CubeInFrustum(const AABB &pCube) const; const Plane& operator()(s32 pIndex) const; /// \brief The frustum's six planes Plane mTop, mBottom, mLeft, mRight, mNear, mFar; }; } #endif
C++
#include "ResourceManager.hpp" #include "Utils/File.hpp" #include "Utils/String.hpp" #include "Debug/Debug.hpp" namespace engine { ResourceManager::ResourceManager(){ } ResourceManager::~ResourceManager(){ if(!(mResources.empty())){ OmniLog << "Resources haven't been freed :" << eol << eol; for(ResourceMap::iterator it = mResources.begin(); it != mResources.end(); ++it){ OmniLog << "- " << it->first << eol; } } } void ResourceManager::Add(const std::string &pName, IResource* pResource){ Assert(pResource != NULL); if(mResources.find(pName) != mResources.end()) OmniLog << "Resource \"" << pName << "\" already loaded!" << eol; mResources[pName] = pResource; pResource->SetName(pName); #ifdef _DEBUG BaseLog << "DEBUG : Adding " << pName << " to ResourceManager." << eol; #endif } void ResourceManager::Remove(const std::string &pName){ ResourceMap::iterator it = mResources.find(pName); if(it != mResources.end()){ mResources.erase(it); #ifdef _DEBUG BaseLog << "DEBUG : Removing " << pName << " from ResourceManager." << eol; #endif } } void ResourceManager::AddPath(const std::string &pPath, const std::string &pFileType){ std::string fileType = pFileType.empty() ? "Generic" : pFileType; mLocations.insert(std::pair<std::string, std::string>(fileType, pPath)); #ifdef _DEBUG BaseLog << "DEBUG : Path \"" << pPath << "\" added for \"" << fileType << "\" type resources." << eol; #endif } std::string ResourceManager::FindFile(const std::string &pFileName, const std::string &pFileType){ std::string fileType = pFileType.empty() ? "Generic" : pFileType; String filePath; for(mLocationsIt = mLocations.begin(); mLocationsIt != mLocations.end(); ++mLocationsIt){ if(mLocationsIt->first == fileType || fileType == "Generic"){ filePath = String(mLocationsIt->second)+"/"+pFileName; if(File::Exists(filePath)) return filePath; } } return "0"; } }
C++
#include "Settings.hpp" #include "Utils/String.hpp" #include "Debug/Debug.hpp" namespace engine{ Settings::Settings(){ } bool Settings::Parse(){ bool ret = true; mSettingsFile.Open(settingsFileName, RWM_ReadOnly, FP_Top); if(mSettingsFile.IsOpened()){ std::string line; while(!mSettingsFile.End()){ line = mSettingsFile.GetLine(); if(!line.empty()) if(line[0] != '[' && line[0] != '\0'){ Setting set; if(FindKey(line, set.Key, set.Value)){ set.Key = StringUtils::ToLower(set.Key); AddSetting(set); }else{ ret = false; break; } } } mSettingsFile.Close(); }else{ OmniLog << "Settings Manager : Settings File not found. Creating default one" << eol; // Creation de fichier par defaut au cas ou l'on ne trouverai pas de fichier utilisateur Setting set; mSettingsFile.Open(settingsFileName, RWM_Write, FP_Top); mSettingsFile << "[Video]" << eol; mSettingsFile << "WindowWidth=800" << eol; set.Key = "WindowWidth"; set.Value = "800"; AddSetting(set); mSettingsFile << "WindowHeight=600" << eol; set.Key = "WindowHeight"; set.Value = "600"; AddSetting(set); mSettingsFile << "MultiSamples=0" << eol; set.Key = "MultiSamples"; set.Value = "0"; AddSetting(set); mSettingsFile << "CullFace=CCW" << eol; set.Key = "CullFace"; set.Value = "CCW"; AddSetting(set); mSettingsFile << "Anisotropy=1" << eol; set.Key = "Anisotropy"; set.Value = "1"; AddSetting(set); mSettingsFile << "VSync=on" << eol; set.Key = "VSync"; set.Value = "on"; AddSetting(set); mSettingsFile << "FOV=45" << eol; set.Key = "FOV"; set.Value = "45"; AddSetting(set); mSettingsFile << "NearPlane=0.1" << eol; set.Key = "NearPlane"; set.Value = "0.1"; AddSetting(set); mSettingsFile << "FarPlane=500.0" << eol; set.Key = "FarPlane"; set.Value = "500.0"; AddSetting(set); mSettingsFile << "AmbientColor=0.5,0.5,0.5" << eol; set.Key = "AmbientColor"; set.Value = "0.5,0.5,0.5"; AddSetting(set); mSettingsFile.Close(); } return ret; } void Settings::AddSetting(const Setting &set){ if(!set.Key.empty() && !set.Value.empty()) mSettings.push_back(set); } bool Settings::FindKey(std::string line, std::string &key, std::string &val) const { bool ret = true; size_t pos = line.find_first_of("="); if(pos <= 256){ key = line.substr(0,pos); val = line.substr(pos+1); }else{ ret = false; OmniLog << "Setting Manager : " << line << " is not a Valid Setting!" << eol; } return ret; } const std::string Settings::getSetting(const std::string key) const{ std::string lowered = StringUtils::ToLower(key); for(std::vector<Setting>::const_iterator it = mSettings.begin(); it != mSettings.end(); it++) if((*it).Key == lowered) return (*it).Value; OmniLog << "Setting Manager : The \"" << key << "\" does not exist in the configuration file." << eol; return ""; } const std::string Settings::GetSettingStr(const std::string key){ std::string ret = Settings::Call().getSetting(key); return ret; } const s32 Settings::GetSettingInt(const std::string key){ s32 ret = atoi(Settings::Call().getSetting(key).c_str()); return ret; } const f32 Settings::GetSettingFloat(const std::string key){ f32 ret = (f32)atof(Settings::Call().getSetting(key).c_str()); return ret; } const bool Settings::GetSettingBool(const std::string key){ bool ret = (Settings::Call().getSetting(key) == "yes" || Settings::Call().getSetting(key) == "on") ? true : false; return ret; } const Vector2F Settings::GetSettingVec2(const std::string key){ std::string all = Settings::Call().getSetting(key); Vector2F vec2 = StringConverter::ToVector2(all); return vec2; } const Vector3F Settings::GetSettingVec3(const std::string key){ std::string all = Settings::Call().getSetting(key); Vector3F vec3 = StringConverter::ToVector3(all); return vec3; } const Color Settings::GetSettingColor(const std::string key){ std::string all = Settings::Call().getSetting(key); Color col = StringConverter::ToColor(all); return col; } }
C++
#ifndef RESOURCEMANAGER_HPP #define RESOURCEMANAGER_HPP #include <map> #include <string> #include "Resource.hpp" #include "Utils/Singleton.hpp" namespace engine { /// \brief Singleton, Keep trace of all IResource inherited instances class OOXAPI ResourceManager : public Singleton<ResourceManager> { friend class Singleton<ResourceManager>; public: /// \brief Returns a Resource from its name /// \param pName : resource name template<class T> T* Get(const std::string &pName) const; /// \brief Add a resource to the manager /// \param pName : resource name /// \param pResource : resource pointer void Add(const std::string &pName, IResource* pResource); /// \brief Remove a resource from the manager /// \param pName : name of the resource to be removed void Remove(const std::string &pName); /// \brief Add a resource path /// \param pPath : path to reach the associated file type /// \param pFileType : File type associated to the path. Null means the path is for all files void AddPath(const std::string &pPath, const std::string &pFileType = ""); /// \brief Returns the full name (with path) of a resource if found /// \param pFileName : asked resource name /// \param pFileType : asked resource type. Null means searching il all paths std::string FindFile(const std::string &pFileName, const std::string &pFileType = ""); private: typedef std::map<std::string, std::string> LocationMap; LocationMap mLocations; /// Map of resource type associated to their directory path LocationMap::iterator mLocationsIt; typedef std::map<std::string, IResource*> ResourceMap; ResourceMap mResources; /// Map of resource associated to their name /// Private Ctor/Dtor, Singleton ~ResourceManager(); ResourceManager(); }; template<class T> inline T* ResourceManager::Get(const std::string &pName) const{ ResourceMap::const_iterator it = mResources.find(pName); if(it != mResources.end()){ it->second->AddRef(); return static_cast<T*>(it->second); }else return NULL; } } #endif
C++
#ifndef IMAGE_HPP #define IMAGE_HPP #include <vector> #include "Core/Resource.hpp" #include "Math/Vector2.hpp" #include "Utils/SPointer.hpp" namespace engine { //// \brief Wrapper Class between an SFML Image and the engine class OOXAPI Image : public IResource{ public: /// \brief Ctor with empty image Image(const Vector2I &pSize = Vector2I(1,1)); /// \brief Ctor from sf::Image Image(const std::string &pName, const Vector2I &pSize, sf::Image &pSurface); ~Image(); /// \brief Returns the image dimensions const Vector2I& GetSize() const; /// \brief Returns the BPP (OpenGL Format) u32 GetBytesPerPixel() const; /// \brief Returns the image format u32 GetFormat() const; /// \brief Returns the image pixels const u8* GetData() const; /// \brief Create the image from an image file /// \return true if image was succesfully loaded bool LoadFromFile(const std::string &pFilename); private: Vector2I mSize; /// Dimensions u32 mBPP; /// Bytes per pixel u32 mFormat; /// Image Format sf::Image mSurface; /// SFML Image Surface }; typedef SPointer<Image, ResourceTypePolicy> ImagePtr; } #endif
C++
#ifndef WINDOW_HPP #define WINDOW_HPP #include "Utils/Shared.hpp" namespace engine{ class OOXAPI Window{ public: Window(); ~Window(); /// \brief Return a pointer on the sf::Window sf::RenderWindow* GetWindowPtr() { return &mWindow; } /// \brief Return the reference of the sf::Window sf::RenderWindow& GetWindow() { return mWindow; } /// \brief Set the Mouse Position in window void SetCursorPosition(int x, int y) { mWindow.SetCursorPosition(x,y); } /// \brief Show or not the mouse cursor void ShowCursor(bool pVal) { mWindow.ShowMouseCursor(pVal); } /// \brief Actualize private variables when a Resized event occurs void Resize(); /// Getters u32 GetWidth() const { return mWidth; } u32 GetHeight() const { return mHeight; } s32 GetHalfWidth() const { return mHalfWidth; } s32 GetHalfHeight() const { return mHalfHeight; } /// Window State bool IsOpened() const { return mIsOpened; } void Close(); private: sf::RenderWindow mWindow; bool mIsOpened; /// False Opened state, does not really open or close anything u32 mWidth; u32 mHeight; s32 mHalfWidth; s32 mHalfHeight; u16 mAntiAliasLevel; }; } #endif
C++
#include "Input.hpp" #include "Window.hpp" #include "Debug/Debug.hpp" namespace engine{ Input::Input() : mInputs(0), mWheelPos(0){ } void Input::Init(Window &pWindow){ mWindow = &pWindow; mInputs = &mWindow->GetWindow().GetInput(); } bool Input::GetEvent(){ return mWindow->GetWindow().GetEvent(mEvents); } void Input::AddMouseBinding(const std::string &pName, sf::Event::EventType pEvent, MouseButton pButton){ InputBind iB; iB.mEventType = pEvent; iB.mInputType = IT_Mouse; iB.mMouseButton = pButton; mInputBinds.insert(std::pair<std::string, InputBind>(pName, iB)); } void Input::AddKeyBinding(const std::string &pName, sf::Event::EventType pEvent, Key pKey){ InputBind iB; iB.mEventType = pEvent; iB.mInputType = IT_Mouse; iB.mKeyCode = pKey; mInputBinds.insert(std::pair<std::string, InputBind>(pName, iB)); } inline void Input::SetInputs(Window &pWindow){ mInputs = &pWindow.GetWindow().GetInput(); } inline bool Input::IsKeyDown(Key pCode){ if(mInputs) return mInputs->IsKeyDown((sf::Key::Code)pCode); throw Exception("InputManager has been called but has not been initialized with SetInputs()"); } inline bool Input::IsKeyHit(Key pCode){ return (mEvents.Type == sf::Event::KeyPressed && mEvents.Key.Code == (sf::Key::Code)pCode); } inline bool Input::IsKeyUp(Key pCode){ return (mEvents.Type == sf::Event::KeyReleased && mEvents.Key.Code == (sf::Key::Code)pCode); } inline bool Input::IsMouseDown(MouseButton pButton){ if(mInputs) return mInputs->IsMouseButtonDown((sf::Mouse::Button)pButton); throw Exception("InputManager has been called but has not been initialized with SetInputs()"); } inline bool Input::IsMouseHit(MouseButton pCode){ return (mEvents.Type == sf::Event::MouseButtonPressed && mEvents.MouseButton.Button == pCode); } inline bool Input::IsMouseUp(MouseButton pCode){ return (mEvents.Type == sf::Event::MouseButtonReleased && mEvents.MouseButton.Button == pCode); } inline bool Input::IsWheelDown(){ return (mEvents.Type == sf::Event::MouseWheelMoved && mEvents.MouseWheel.Delta < 0); } }
C++
#ifndef RENDERENUMS_HPP #define RENDERENUMS_HPP #include "Utils/Shared.hpp" namespace engine { /// \brief OpenGL Primitive Types enum PrimitiveType { PT_TRIANGLELIST, PT_TRIANGLESTRIP, PT_TRIANGLEFAN, PT_LINELIST, PT_LINESTRIP, PT_POINTLIST }; /// \brief Matrix Types enum MatrixType{ MAT_WORLD, MAT_INVWORLD, MAT_VIEW, MAT_INVVIEW, MAT_PROJ, MAT_WORLDVIEW, MAT_WORLDVIEWPROJ, MAT_INVWORLDTRANSPOSE }; } #endif
C++
#ifndef SETTINGS_HPP #define SETTINGS_HPP #include <vector> #include <string> #include "Math/Vector2.hpp" #include "Math/Vector3.hpp" #include "Utils/Color.hpp" #include "Utils/File.hpp" #include "Utils/Singleton.hpp" namespace engine{ /// \brief Default config file const char settingsFileName[] = "Options.cfg"; /// \brief Structure conaining a key and its mapped value struct Setting{ Setting() : Key(""), Value(""){ } Setting(std::string key, std::string val) : Key(key), Value(val){ } std::string Key; std::string Value; }; /// \brief Class parsing and keeping in memory the settings of the engine. Singleton class, Parse function must be called early. Kill Singleton function must be called in the end of execution class OOXAPI Settings : public Singleton<Settings>{ friend class Singleton<Settings>; public: Settings(); ~Settings(){} /// \brief Parse the Option.cfg to store options. Or create it if it doesn't exist bool Parse(); /// \brief Returns one setting value from specified key /// \param key : Key of the asked value /// \return String static const std::string GetSettingStr(const std::string key); /// \brief Returns one setting value from specified key /// \param key : Key of the asked value /// \return Int static const s32 GetSettingInt(const std::string key); /// \brief Returns one setting value from specified key /// \param key : Key of the asked value /// \return Float static const f32 GetSettingFloat(const std::string key); /// \brief Returns one setting value from specified key /// \param key : Key of the asked value /// \return Bool static const bool GetSettingBool(const std::string key); /// \brief Returns one setting value from specified key /// \param key : Key of the asked value /// \return Vector2 static const Vector2F GetSettingVec2(const std::string key); /// \brief Returns one setting value from specified key /// \param key : Key of the asked value /// \return Vector3 static const Vector3F GetSettingVec3(const std::string key); /// \brief Returns one setting value from specified key /// \param key : Key of the asked value /// \return Color static const Color GetSettingColor(const std::string key); private: /// \brief Add a setting to the vector // \param set : Setting to be added void AddSetting(const Setting &set); /// \brief Function used by parse to parse one line and get a key and its value /// \param line : Complete Line /// \param key : Left Part of the line (Key) /// \param val : Right Part of the line (Value) bool FindKey(std::string line, std::string &key, std::string &val) const; /// \brief Function used by specific GetSetting*** public function /// \param key : Key of the asked value const std::string getSetting(const std::string key) const; std::vector<Setting> mSettings; File mSettingsFile; }; } #endif // SETTINGS_HPP
C++
#ifndef INPUT_HPP #define INPUT_HPP #include "Math/Vector2.hpp" #include "Utils/Keys.hpp" namespace engine{ class Window; /// \brief Input Type, Mouse or Keyboard only enum InputType{ IT_Mouse, IT_Keyboard }; /// \brief Structure used to store binding possibilities struct InputBind{ InputType mInputType; /// Input Type (Mouse or Keyboard) sf::Event::EventType mEventType; /// Event Type Key mKeyCode; /// If keyboard, its KeyCode MouseButton mMouseButton; /// If mouse, its ButtonCode }; class OOXAPI Input{ public: Input(); /// \brief Initialize the inputs with the reference of the main window void Init(Window &pWindow); /// \brief Add a Mouse binding to the map (TODO : Settings parser for key binding parser) void AddMouseBinding(const std::string &pName, sf::Event::EventType pEvent, MouseButton pButton); /// \brief Add a Keyboard binding to the map (TODO : Settings parser for key binding parser) void AddKeyBinding(const std::string &pName, sf::Event::EventType pEvent, Key pKey); // Returns the Mouse Movement since last frame //const f32 GetMouseMovementX() const { return mData.Mouse.movement.x; } //const f32 GetMouseMovementY() const { return mData.Mouse.movement.y; } /// \brief Returns the horizontal mouse position const s32 GetMouseX() const { return mInputs->GetMouseX(); } /// \brief Returns the vertical mouse position const s32 GetMouseY() const { return mInputs->GetMouseY(); } // Keyboard acquisition /// \brief Returns true whenever this key is down bool IsKeyDown(Key pKey); /// \brief Returns true if a a key has just been hit bool IsKeyHit(Key pKey); /// \brief Returns true if the key has just been released bool IsKeyUp(Key pKey); // Mouse Buttons acquisition /// \brief Returns true whenever this mouse button is down bool IsMouseDown(MouseButton button); /// \brief Returns true if the mouse button has just been pressed bool IsMouseUp(MouseButton button); /// \brief Returns true if the mouse button has just been releases bool IsMouseHit(MouseButton button); /// \brief Returns true if the window gets more events. Call it in a while() loop bool GetEvent(); /// \brief Returns current event type sf::Event::EventType GetEventType() { return mEvents.Type; } bool IsWheelUp(); bool IsWheelDown(); /// \brief Get the inputs from a window void SetInputs(Window &pWindow); private: /// Map between an action (string) and a particular key or button std::map<std::string, InputBind> mInputBinds; /// Inputs of the current Window const sf::Input* mInputs; sf::Event mEvents; /// Pointer on window Window* mWindow; /// Inputs initialized or not (true after first test) bool mInputInitialized; /// Mouse Wheel current position s32 mWheelPos; }; } #endif
C++
#ifndef RESOURCE_HPP #define RESOURCE_HPP #include <string> #include "Utils/Shared.hpp" namespace engine { /// \brief Interface for any resource type class OOXAPI IResource{ public: IResource(); /// \brief Can't instantiate class virtual ~IResource() = 0; /// \brief Returns the resource name const std::string &GetName() const; /// \brief Set the resource name void SetName(const std::string &pName); /// \brief Add a reference void AddRef(); /// \brief Release a reference s32 Release(); protected: std::string mName; /// Resource Name s32 mRefCount; /// References number on this resource }; } #endif
C++
#ifndef ENTITY_HPP #define ENTITY_HPP #include "Renderer/VAO.hpp" #include "Math/AABB.hpp" #include "Math/Matrix4.hpp" #include "Utils/Color.hpp" #include "Debug/Exceptions.hpp" namespace engine { /// \brief Different types of entities (look below for desc) enum eEntityType{ ET_NONE, ET_OBJECT, ET_MESH, ET_DEBUGOBJECT }; /// \brief Material d'une entity class OOXAPI Material{ public: Material() : mAmbient(0.1f,0.1f,0.1f), mDiffuse(1.f,1.f,1.f), mSpecular(0.5f,0.5f,0.5f), mShininess(1.f){} Color mAmbient, mDiffuse, mSpecular; f32 mShininess; }; class Shader; class Texture; class OOXAPI Entity{ public: /// \brief Returns Entity ID u32 GetID() const { return mID; } // Custom Shapes (Definition in /// \brief Cube 1x1x1 void MakeCube(const std::string &pMeshname, Shader &pShader); /// \brief Sphere radius 1 /// \param pMeshName : entity name for resourceManager /// \param pShader : Shader used for rendering /// \param pSlices : number of subdivisions of the sphere void MakeSphere(const std::string &pMeshName, Shader &pShader, s32 pSlices); /// \brief Create a new mesh from vertices/indices /// \param pMeshName : entity name for resourceManager /// \param pShader : Shader used for rendering /// \param pVertices : Vertices array /// \param pVSize : Vertices array size /// \param pIndices : Indices array /// \param pISize : Indices array size void CreateVAO(const std::string &pMeshName, Shader &pShader, Vector3F* pVertices, u32 pVSize, Index* pIndices = NULL, u32 pISize = 0); /// \brief Function overloaded in Mesh virtual void Make(Vector3F* pNormals, Vector2F* pTexCoords){ throw Exception("Entity : Tried to use the \"Make(normal, texcoords)\" function on a non-Mesh Entity Type."); } /// \brief Function overloaded in Object virtual void Make(Vector3F* pNormals){ throw Exception("Entity : Tried to use the \"Make(normal)\" function on a non-Object Entity Type."); } /// \brief Function overloaded in DebugObject virtual void Make(Vector2F* pTexCoords){ throw Exception("Entity : Tried to use the \"Make(normal, texcoords)\" function on a non-DebugObject Entity Type."); } /// \brief Copy a VAO from another Entity void CopyVAO(Entity &pCopy); /// \brief Returns the VAO VAOPtr& GetVAO() { return mVao; } /// \brief Texture Functions void SetTexture(Texture &pTexture) { mTexture = &pTexture; mUseTexture = true; } const Texture& GetTexture() const { return *mTexture; } /// \brief Return true if entity use texture bool UseTexture() const { return mUseTexture; } /// \brief Set the used shader void SetShader(Shader &pShader) { mShader = &pShader; } /// \brief Returns the Shader Shader* GetShader() const { return mShader; } /// Matrix operations /// \brief Set the modelMatrix void SetModelMatrix(const Matrix4 &pMat) { mModelMatrix = pMat; } /// \brief Returns the ModelMatrix const Matrix4& GetModelMatrix() const { return mModelMatrix; } /// \brief Returns the entity AABB const AABB& GetAABB() const { return mAABB; } /// \brief Returns the entity used material Material& GetMaterial() { return mMaterial; } /// Movement and Orientation /// \brief Change the entity position void SetPosition(const Vector3F &pVec); /// \brief Change the entity orientation void SetOrientation(const Quaternion &pQuat); /// \brief Scale the entity void Scale(f32 x, f32 y, f32 z); /// \brief Move the entity void Translate(const Vector3F& pVector); void Translate(f32 x, f32 y, f32 z); /// \brief Rotate the entity void Rotate(const Vector3F &pAxis, f32 angle); /// \brief Add the entity to the renderer drawlist virtual void Draw() = 0; /// \brief Returns the entity type eEntityType GetType() const { return mType; } protected: Entity(); Entity(const Entity &pCopy); ~Entity(){} static u32 EntityIDs; /// Auto incremented Entities IDs u32 mID; /// This Entity ID std::string mName; /// Entity Name VAOPtr mVao; /// Position/Indice VAO Shader* mShader; /// Shader used during rendering Texture* mTexture; /// Used texture (if any) bool mUseTexture; /// True if a texture is used Matrix4 mModelMatrix; /// Model Matrix AABB mAABB; /// Axis Aligned Bounding Box eEntityType mType; /// Entity Type Material mMaterial; /// Entity Material }; /// \brief MESH : Entity with Texture Coordinates and Normals class OOXAPI Mesh : public Entity{ public: Mesh() : Entity() { mType = ET_MESH; } /// \brief Generate the Normals and TexCoords VBO /// \param pNormals : normals array /// \param pTexCoords : texcoords array void Make(Vector3F* pNormals, Vector2F* pTexCoords); /// \brief Copy an existing Mesh (Pos/Indices/Normals/TexCoords) void CopyMesh(Mesh &pMesh); /// \brief Add the Mesh to the renderer DrawList void Draw(); /// \brief Returns the VAO TexMeshPtr& GetMesh() { return mMesh; } private: TexMeshPtr mMesh; /// VAO used in spite of the mVAO }; /// \brief OBJECT : Entite avec couleurs et normales class OOXAPI Object : public Entity{ public: Object() : Entity() { mType = ET_OBJECT; } /// \brief Generate the Normals VBO /// \param pNormals : normals array void Make(Vector3F* pNormals); /// \brief Copy an existing Object (Pos/Indices/Normals) void CopyObject(Object &pObject); /// \brief Add the Object to the renderer DrawList void Draw(); /// \brief Returns the VAO ColorMeshPtr& GetMesh() { return mMesh; } private: ColorMeshPtr mMesh; /// VAO used in spite of the mVAO }; /// \brief DEBUGOBJECT : objet avec couleur et texture class OOXAPI DebugObject : public Entity{ public: DebugObject() : Entity() { mType = ET_DEBUGOBJECT; } /// \brief Generate the TexCoords VBO /// \param pTexCoords : texcoords array void Make(Vector2F* pTexCoords); /// \brief Copy an existing DebugObject (Pos/Indices/TexCoords) void CopyDebugObject(DebugObject &pObject); /// \brief Add the DebugObject to the renderer DrawList void Draw(); /// \brief Returns the VAO ColorVAOPtr& GetMesh() { return mMesh; } private: ColorVAOPtr mMesh; /// VAO used in spite of the mVAO }; } #endif
C++
#include "Resource.hpp" #include "ResourceManager.hpp" #include "Debug/New.hpp" namespace engine { IResource::IResource() : mName(""), mRefCount(1){ } IResource::~IResource(){ ResourceManager::Call().Remove(mName); } const std::string &IResource::GetName() const{ return mName; } void IResource::SetName(const std::string &pName){ mName = pName; } void IResource::AddRef(){ ++mRefCount; } s32 IResource::Release(){ s32 RefCount = --mRefCount; if(!RefCount) delete this; return RefCount; } }
C++
#include "Window.hpp" #include "Settings.hpp" #include "Utils/String.hpp" #include "Debug/Debug.hpp" namespace engine { Window::Window() : mWidth(0), mHeight(0), mIsOpened(true){ // Récupération des Settings mWidth = Settings::Call().GetSettingInt("WindowWidth"); if(!mWidth){ // Erreur, les settings n'ont pas ete initialisés OmniLog << "Error : Settings have not been initialized. Initializing now." << eol; Settings::Call().Parse(); mWidth = Settings::Call().GetSettingInt("WindowWidth"); } mHeight = Settings::Call().GetSettingInt("WindowHeight"); mHalfWidth = mWidth / 2; mHalfHeight = mHeight / 2; mAntiAliasLevel = Settings::Call().GetSettingInt("MultiSamples"); sf::VideoMode vMode; vMode.BitsPerPixel = 32; vMode.Height = mHeight; vMode.Width = mWidth; sf::ContextSettings settings; settings.AntialiasingLevel = mAntiAliasLevel; settings.DepthBits = 24; settings.MajorVersion = 3; settings.MinorVersion = 3; settings.StencilBits = 8; mWindow.Create(vMode, (String("00xEngine ")+ENGINE_MAJOR+"."+ENGINE_MINOR+"."+ENGINE_PATCH).str().c_str(), sf::Style::Close/* | sf::Style::Resize*/, settings); mWindow.EnableKeyRepeat(false); } Window::~Window(){ mWindow.Close(); } void Window::Close(){ mIsOpened = false; } void Window::Resize(){ mWidth = mWindow.GetWidth(); mHeight = mWindow.GetHeight(); mHalfWidth = mWidth / 2; mHalfHeight = mHeight / 2; } }
C++
#include "Entity.hpp" #include "ResourceManager.hpp" #include "Math/Quaternion.hpp" #include "Utils/String.hpp" #include "Renderer/Renderer.hpp" #include "Renderer/Shader.hpp" #include "Debug/Debug.hpp" namespace engine { u32 Entity::EntityIDs = 0; Entity::Entity() : mID(EntityIDs++), mType(ET_NONE), mUseTexture(false), mShader(0){ } Entity::Entity(const Entity &pCopy){ mType = pCopy.mType; mUseTexture = pCopy.mUseTexture; mTexture = pCopy.mTexture; mModelMatrix = pCopy.mModelMatrix; mAABB = pCopy.mAABB; if(!pCopy.mVao) OmniLog << "Entity \"" << mID << "\" has been created from copy but with no VAO." << eol; else mVao = pCopy.mVao; } void Entity::CreateVAO(const std::string &pMeshName, Shader &pShader, Vector3F* pVertices, u32 pVSize, Index* pIndices, u32 pISize){ if(ResourceManager::Call().Get<VAO>(pMeshName)) throw Exception(String("Entity \"")+mID+"\" was told to create mesh \"" + pMeshName + "\" but this is an already existing mesh"); else{ mShader = &pShader; mVao = new VAO(); mVao->Generate(mShader, pVertices, pVSize, pIndices, pISize); mAABB.Init(pVertices, pVSize / sizeof(Vertex)); mName = pMeshName; } } void Entity::CopyVAO(Entity &pCopy){ if(pCopy.mVao){ mVao = pCopy.mVao.Copy(); mUseTexture = pCopy.mUseTexture; mTexture = pCopy.mTexture; mAABB = pCopy.mAABB; mShader = pCopy.mShader; }else{ throw Exception(String("Entity \"")+mID+"\" was told to get its mesh from an empty mesh of entity \""+pCopy.mID+"\"."); } } void Entity::SetPosition(const Vector3F &pVec){ mAABB.Translate(pVec - mModelMatrix.GetTranslation()); mModelMatrix.SetTranslation(pVec); } void Entity::Translate(const Vector3F &pVector){ mAABB.Translate(pVector); mModelMatrix.Translate(pVector); } void Entity::Translate(f32 x, f32 y, f32 z){ Translate(Vector3F(x,y,z)); } void Entity::SetOrientation(const Quaternion &pQuat){ mModelMatrix.SetOrientation(pQuat); } void Entity::Rotate(const Vector3F &pAxis, f32 angle){ Matrix4 rotation; Quaternion quat; quat.FromAxisAngle(pAxis, angle); rotation.SetOrientation(quat); mModelMatrix = rotation * mModelMatrix; } void Entity::Scale(f32 x, f32 y, f32 z){ mAABB.Scale(Vector3F(x,y,z)); mModelMatrix.SetScale(x,y,z); } // ######################################################## // // MESH void Mesh::Make(Vector3F* pNormals, Vector2F* pTexCoords){ if(!mVao) throw Exception("Entity : Generate the Entity vertices before making a Mesh."); if(!mShader) throw Exception("Entity : Entity needs a Shader before making a Mesh."); mMesh = new TextureMesh(); mMesh->CopyVAO(mVao); mType = ET_MESH; mUseTexture = true; mMesh->GenerateNormals(pNormals, mVao->GetVertexCount() * sizeof(Vector3F), mShader); mMesh->GenerateTexCoords(pTexCoords, mVao->GetVertexCount() * sizeof(Vector2F), mShader); ResourceManager::Call().Add(mName, mMesh); } void Mesh::CopyMesh(Mesh &pMesh){ if(pMesh.mVao){ mVao = pMesh.mVao.Copy(); mUseTexture = pMesh.mUseTexture; mTexture = pMesh.mTexture; mAABB = pMesh.mAABB; mShader = pMesh.mShader; if(pMesh.mMesh) mMesh = pMesh.mMesh.Copy(); }else{ throw Exception(String("Entity \"")+mID+"\" was told to get its mesh from an empty mesh of entity \""+pMesh.mID+"\"."); } } void Mesh::Draw(){ Renderer::Call().DrawMesh(this); } // ######################################################## // // OBJECT void Object::Make(Vector3F* pNormals){ if(!mVao) throw Exception("Entity : Generate the Entity vertices before making an Object."); if(!mShader) throw Exception("Entity : Entity needs a Shader before making an Object."); mMesh = new ColorMesh(); mMesh->CopyVAO(mVao); mType = ET_OBJECT; mUseTexture = false; mMesh->GenerateNormals(pNormals, mVao->GetVertexCount() * sizeof(Vector3F), mShader); ResourceManager::Call().Add(mName, mMesh); } void Object::CopyObject(Object &pObject){ if(pObject.mVao){ mVao = pObject.mVao.Copy(); mUseTexture = pObject.mUseTexture; mTexture = pObject.mTexture; mAABB = pObject.mAABB; mShader = pObject.mShader; if(pObject.mMesh) mMesh = pObject.mMesh.Copy(); }else{ throw Exception(String("Entity \"")+mID+"\" was told to get its mesh from an empty mesh of entity \""+pObject.mID+"\"."); } } void Object::Draw(){ Renderer::Call().DrawObject(this); } // ######################################################## // // DEBUGOBJECT void DebugObject::Make(Vector2F* pTexCoords){ if(!mVao) throw Exception("Entity : Generate the Entity vertices before making a DebugObject."); if(!mShader) throw Exception("Entity : Entity needs a Shader before making a DebugObject."); mMesh = new ColorVAO(); mMesh->CopyVAO(mVao); mType = ET_DEBUGOBJECT; mUseTexture = true; mMesh->GenerateTexCoords(pTexCoords, mVao->GetVertexCount() * sizeof(Vector2F), mShader); ResourceManager::Call().Add(mName, mMesh); } void DebugObject::CopyDebugObject(DebugObject &pObject){ if(pObject.mVao){ mVao = pObject.mVao.Copy(); mUseTexture = pObject.mUseTexture; mTexture = pObject.mTexture; mAABB = pObject.mAABB; mShader = pObject.mShader; if(pObject.mMesh) mMesh = pObject.mMesh.Copy(); }else{ throw Exception(String("Entity \"")+mID+"\" was told to get its mesh from an empty mesh of entity \""+pObject.mID+"\"."); } } void DebugObject::Draw(){ Renderer::Call().DrawDebugObject(this); } }
C++
//////////////////////////////////////////////////////////// /// \mainpage /// /// \section welcome 00xEngine Index Page /// Welcome to the official 00xEngine documentation. /// Some links : /// - Description of all 00xEngine <a href="./annotated.htm">classes</a>. /// - Description of all 00xEngine <a href="./files.htm">files</a>. <br> /// /// \section example Short example /// This is a minimum-code/simple example of how to use the engine : /// /// \code /// /// #include "Engine.hpp" /// /// using namespace engine; /// /// int main(){ /// // Initialize Loggers (used for debug) /// ILogger::Init(); /// /// // Parse the config file (default is Options.cfg) /// Settings::Call().Parse(); /// /// // Add Paths for the ResourceManager to find resources /// ResourceManager::Call().AddPath("Data/shaders", "Shader"); /// ResourceManager::Call().AddPath("Data/textures", "Image"); /// /// { /// // Create our window /// Window myWindow; /// /// // Retrieve the engine Renderer and initialize it with our window /// Renderer& myRenderer = Renderer::Call(); /// myRenderer.Init(myWindow); /// /// // Create our inputs and initialize it with our window /// Input myInput; /// myInput.Init(myWindow); /// /// // Make some text /// Text myText; /// myText.SetText("00xEngine"); /// myText.SetPosition(320, 260); /// /// /// // Begin Main Loop /// while(myWindow.IsOpened()){ /// // Retrieve frame events /// while(myInput.GetEvent()){ /// // Look if the window Close Event happens, if so, close the window /// if(myInput.GetEventType() == sf::Event::Closed) /// myWindow.Close(); /// } /// /// // Draw our text /// myText.Draw(); /// /// // Begin the rendering with some background color /// myRenderer.BeginScene(Color::Black); /// // Render the scene /// myRenderer.Render(); /// // End the rendering /// myRenderer.EndScene(); /// } /// } /// /// // Destroy some instances /// Renderer::Kill(); /// ResourceManager::Kill(); /// Settings::Kill(); /// ILogger::Kill(); /// MemoryManager::Kill(); /// } /// /// \endcode ////////////////////////////////////////////////////////////
C++
#include "Scene.hpp" #include "Debug/New.hpp" using namespace engine; /* GameScene::GameScene(const std::string &pName) : Scene(pName){ } GameInput::GameInput(const std::string &pName) : Input(pName){ } bool GameScene::Start(){ // Recuperation de la fenetre mWindow = &(mKernel->GetWindow().GetWindow()); currRenderer = CRenderer::Get(); cam.SetProjectionMatrix(currRenderer->Get3DProjectionMatrix()); cam.LookAt(Vector3F(0.5f,0,1), Vector3F(-2.5f,2,4)); currRenderer->SetCamera(&cam); TextureShader.Compile("shaderTexture.vs", "shaderTexture.fs"); ColorShader.Compile("shaderColor.vs", "shaderColor.fs"); Image img; img.LoadFromFile("crate.jpg"); tex1.LoadFromImage(img); obj1.MakeCube("carre", ColorShader); obj1.GetMaterial().mAmbient = Color(0.f, 0.08f, 0.08f); obj1.GetMaterial().mDiffuse = Color(0.f, 0.8f, 0.8f); obj2.GetMaterial().mSpecular = Color(0.0f, 0.5f, 0.5f); obj1.GetMaterial().mShininess = 50.f; obj1.Translate(Vector3F(-0.5f,0,0)); //obj2.CopyObject(obj1); obj2.MakeSphere("sphere", ColorShader, 6); obj2.GetMaterial().mAmbient = Color(0.8f, 0.32f, 0.f); obj2.GetMaterial().mDiffuse = Color(2.f, 0.8f, 0.f); obj2.GetMaterial().mSpecular = Color(0.8f, 0.32f, 0.f); obj2.GetMaterial().mShininess = 50.f; //obj2.Scale(12,0.2f,12); //obj2.Translate(Vector3F(2,-1.1f,0)); obj2.Translate(Vector3F(2,0,0)); mesh1.MakeCube("carretex", TextureShader); mesh1.SetTexture(tex1); mesh1.SetPosition(Vector3F(5,0,1.5)); obj2.GetMaterial().mAmbient = Color(0,0,0); // fps.SetFont("DejaVuSans.ttf", 12); // fps.SetPosition(Vector2F(10,25)); // fps.SetColor(Color::White); // fps.SetText("dur"); // mousePos.SetFont("DejaVuSans.ttf", 12); // mousePos.SetPosition(Vector2F(10,10)); // mousePos.SetColor(Color::White); // mousePos.SetText("hur"); l.SetPosition(Vector3F(1,3,1.5)); l.SetDiffuse(Color(1.f,1.f,1.f)); l.SetRange(8); ColorShader.Bind(); ColorShader.SendColor("ambientColor", currRenderer->GetSpecifications().mAmbientColor); ColorShader.SendFloat("constantAtt", l.GetAttenuationConstant()); ColorShader.SendFloat("linearAtt", l.GetAttenuationLinear()); ColorShader.SendFloat("quadraticAtt", l.GetAttenuationQuadratic()); ColorShader.SendFloat("range", l.GetRange()); ColorShader.SendVector3("lightPosition", l.GetPosition()); ColorShader.SendColor("lightColor", l.GetDiffuse()); ColorShader.UnBind(); TextureShader.Bind(); TextureShader.SendColor("ambientLight", currRenderer->GetSpecifications().mAmbientColor); ColorShader.SendFloat("constantAtt", l.GetAttenuationConstant()); ColorShader.SendFloat("linearAtt", l.GetAttenuationLinear()); ColorShader.SendFloat("quadraticAtt", l.GetAttenuationQuadratic()); ColorShader.SendFloat("range", l.GetRange()); TextureShader.SendVector3("lightPosition", l.GetPosition()); TextureShader.SendColor("lightColor", l.GetDiffuse()); TextureShader.UnBind(); return true; } void GameScene::Stop(){ } void GameInput::SingleEvents(){ while(mKernel->GetWindow().GetWindow().GetEvent(mInput.GetEvent())){ // fermeture si escape ou croix if(mInput.GetEventType() == sf::Event::Closed || mInput.IsKeyDown(sf::Key::Escape)) mKernel->KillAllTasks(); if(mInput.IsKeyHit(sf::Key::B)) mScene->obj1.Rotate(Vector3F::UNIT_X, Math::Pi/4.f); if(mInput.IsMouseHit(sf::Mouse::Right)){ // sauvegarde de l'endroit du clic xClick = mInput.GetMouseX(); yClick = mInput.GetMouseY(); // on cache le curseur mKernel->GetWindow().ShowCursor(false); // deplacement de la souris au milieu de la fenetre mKernel->GetWindow().SetCursorPosition(mKernel->GetWindow().GetHalfWidth(), mKernel->GetWindow().GetHalfHeight()); } if(mInput.IsMouseUp(sf::Mouse::Right)){ // On replace la souris a l'emplacement du click mKernel->GetWindow().SetCursorPosition(xClick,yClick); // on remontre le curseur mKernel->GetWindow().ShowCursor(true); } if(mInput.IsKeyHit(sf::Key::W)) mScene->currRenderer->SetWireframe(!mScene->currRenderer->GetWireframe()); } } void GameInput::RepetedEvents(){ // Mouvement de la camera if(mInput.IsKeyDown(sf::Key::Z)) {mScene->cam.MoveForward(1.f * mScene->elapsedTime); } if(mInput.IsKeyDown(sf::Key::S)) {mScene->cam.MoveForward(-1.f * mScene->elapsedTime); } if(mInput.IsKeyDown(sf::Key::D)) {mScene->cam.MoveRight(1.f * mScene->elapsedTime); } if(mInput.IsKeyDown(sf::Key::Q)) {mScene->cam.MoveRight(-1.f * mScene->elapsedTime); } if(mInput.IsKeyDown(sf::Key::A)) {mScene->cam.MoveUp(1.f * mScene->elapsedTime); } if(mInput.IsKeyDown(sf::Key::E)) {mScene->cam.MoveUp(-1.f * mScene->elapsedTime); } if(mInput.IsKeyDown(sf::Key::Up)) mScene->obj1.Translate(Vector3F(0,0,-0.1f)); if(mInput.IsKeyDown(sf::Key::Down)) mScene->obj1.Translate(Vector3F(0,0,0.1f)); if(mInput.IsKeyDown(sf::Key::Left)) mScene->obj1.Translate(Vector3F(-0.1f,0,0)); if(mInput.IsKeyDown(sf::Key::Right)) mScene->obj1.Translate(Vector3F(0.1f,0,0)); // Vitesse de la camera if(mInput.IsKeyDown(sf::Key::LShift)) mScene->cam.SetSpeed(20); else mScene->cam.SetSpeed(5); // Orientation de la camera if(mKernel->GetInput().IsMouseDown(sf::Mouse::Right)){ // on recupere les coordonnees du deplacement x = mInput.GetMouseX(); y = mInput.GetMouseY(); // on bouge la camera en fonction de ce mouvement mScene->cam.Yaw((x - mKernel->GetWindow().GetHalfWidth()) * mScene->elapsedTime); mScene->cam.Pitch((y - mKernel->GetWindow().GetHalfHeight()) * mScene->elapsedTime); // On replace le curseur au point mKernel->GetWindow().SetCursorPosition(mKernel->GetWindow().GetHalfWidth(),mKernel->GetWindow().GetHalfHeight()); } } void GameScene::Update(){ // Mise a jour de la clock elapsedTime = clk.GetElapsedTime(); clk.Reset(); // Affichage des fps if(fpsTimer.GetElapsedTime() > 1){ // fps.SetText(String(1.f/elapsedTime)); fpsTimer.Reset(); } // Affichage des coordonnees souris //mousePos.SetText(String("X: ") + mKernel->GetInput().GetMouseX() + " Y: " + mKernel->GetInput().GetMouseY()); // Envoi des entites a dessiner au Renderer //mousePos.Draw(); //fps.Draw(); if(cam.GetFrustum().CubeInFrustum(mesh1.GetAABB())) mesh1.Draw(); if(cam.GetFrustum().CubeInFrustum(obj1.GetAABB())) obj1.Draw(); if(cam.GetFrustum().CubeInFrustum(obj2.GetAABB())) obj2.Draw(); // Rendu currRenderer->BeginScene(Color(0.f,0.f,0.f,1.f)); currRenderer->Render(); currRenderer->EndScene(); } */
C++
#include "Scene.hpp" #include "Debug/New.hpp" #include <iostream> using namespace engine; f32 ElapsedTime; bool paused = false; int main(){ try{ ILogger::Init(); Settings::Call().Parse(); ResourceManager::Call().AddPath("Data/shaders", "Shader"); ResourceManager::Call().AddPath("Data/textures", "Image"); { Window myWindow; Image Crate; Texture CrateTexture; Text FPSText, MousePosText; Clock FrameClock, FpsClock; Input myInput; myInput.Init(myWindow); Renderer& myRenderer = Renderer::Call(); myRenderer.Init(myWindow); Crate.LoadFromFile("crate.jpg"); CrateTexture.LoadFromImage(Crate); Light l; l.SetPosition(Vector3F(1,3,1.5)); l.SetDiffuse(Color(1.f,1.f,1.f)); l.SetRange(8); Shader ColorShader; ColorShader.Compile("shaderColor.vs", "shaderColor.fs"); ColorShader.Bind(); ColorShader.SendColor("ambientColor", myRenderer.GetSpecifications().mAmbientColor); ColorShader.SendFloat("constantAtt", l.GetAttenuationConstant()); ColorShader.SendFloat("linearAtt", l.GetAttenuationLinear()); ColorShader.SendFloat("quadraticAtt", l.GetAttenuationQuadratic()); ColorShader.SendFloat("range", l.GetRange()); ColorShader.SendVector3("lightPosition", l.GetPosition()); ColorShader.SendColor("lightColor", l.GetDiffuse()); ColorShader.UnBind(); Object obj1; obj1.MakeCube("cube", ColorShader); obj1.GetMaterial().mAmbient = Color(0.f, 0.08f, 0.08f); obj1.GetMaterial().mDiffuse = Color(0.f, 0.8f, 0.8f); obj1.GetMaterial().mSpecular = Color(0.0f, 0.5f, 0.5f); obj1.GetMaterial().mShininess = 50.f; Camera cam; cam.LookAt(Vector3F(0.5f,0,1), Vector3F(-2.5f,2,4)); FPSText.SetSize(12); FPSText.SetPosition(10,10); MousePosText.SetSize(12); MousePosText.SetPosition(10,22); while(myWindow.IsOpened()){ ElapsedTime = FrameClock.GetElapsedTime(); FrameClock.Reset(); if(FpsClock.GetElapsedTime() > 1.f){ FPSText.SetText(String(1.f/ElapsedTime)); FpsClock.Reset(); } while(myInput.GetEvent()){ if(myInput.GetEventType() == sf::Event::Closed) myWindow.Close(); if(myInput.IsKeyHit(Space)) if(!paused){ paused = true; FrameClock.Pause(); }else{ paused = false; FrameClock.Resume(); } } MousePosText.SetText(String("X : ")+myInput.GetMouseX()+" Y : "+myInput.GetMouseY()); MousePosText.Draw(); FPSText.Draw(); obj1.Draw(); myRenderer.BeginScene(myRenderer.GetSpecifications().mAmbientColor); myRenderer.Render(); myRenderer.EndScene(); } } }catch(Exception e){ std::cout << e.what() << std::endl; system("PAUSE"); } Renderer::Kill(); ResourceManager::Kill(); Settings::Kill(); ILogger::Kill(); #ifdef _DEBUG MemoryManager::Kill(); #endif return 0; }
C++
#ifndef SCENE_HPP #define SCENE_HPP #include "Engine.hpp" /* class GameScene : public engine::task::Scene{ public: GameScene(const std::string &pName); bool Start(); void Stop(); void Update(); engine::Clock clk, fpsTimer; f32 elapsedTime; engine::Camera cam; engine::Text mousePos, fps; engine::Texture tex1; engine::Shader TextureShader, ColorShader, TextShader; engine::Light l; engine::Object obj1, obj2; engine::Mesh mesh1; bool movement; sf::RenderWindow* mWindow; engine::CRenderer* currRenderer; }; class GameInput : public engine::task::Input{ public: GameInput(const std::string &pName); void SingleEvents(); void RepetedEvents(); int x, y; // variables contenant la position de la souris int xClick, yClick; // variables contenant l'endroit du clic droit GameScene* mScene; }; */ #endif
C++
#include <iostream> using namespace std; void whoIsYavor(); int main() { whoIsYavor(); system("pause"); return 0; } void whoIsYavor() { cout<<"He is the best!\n"; }
C++
#include "WindowHelper.h" #include "D3D11.h" LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){ HWND hWnd; WNDCLASSEX wc; ZeroMemory(&wc, sizeof(WNDCLASSEX)); wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WindowProc; wc.hInstance = hInstance; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)COLOR_WINDOW; wc.lpszClassName = L"DX11"; RegisterClassEx(&wc); hWnd = CreateWindowEx(NULL, L"DX11", // name of the window class L"DirectX 11", // title of the window #ifdef BORDERLESS_WINDOW WS_POPUP, #endif #ifndef BORDERLESS_WINDOW WS_OVERLAPPEDWINDOW, // window style #endif WH::gdwWindowXPos, // x-position of the window WH::gdwWindowYPos, // y-position of the window #ifdef BORDERLESS_WINDOW WH::gdwWindowWidth, WH::gdwWindowHeight, #endif #ifndef BORDERLESS_WINDOW WINDOW_WIDTH, // width of the window WINDOW_HEIGHT, // height of the window #endif NULL, // we have no parent window, NULL NULL, // we aren't using menus, NULL hInstance, // application handle NULL); // used with multiple windows, NULL #ifdef BORDERLESS_WINDOW HRGN hrgn = CreateRectRgn( 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT ); SetWindowRgn( hWnd, hrgn, TRUE ); #endif ShowWindow(hWnd, nCmdShow); D3D11* pD3D11 = D3D11::Get(); pD3D11->Init(hWnd); MSG msg = {0}; while(TRUE){ if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){ TranslateMessage(&msg); DispatchMessage(&msg); if(msg.message == WM_QUIT) break; }else{ // Game code } } pD3D11->Clean(); return msg.wParam; } LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam){ switch(message){ case WM_DESTROY: { PostQuitMessage(0); return 0; } break; } return DefWindowProc (hWnd, message, wParam, lParam); }
C++
////////////////////////////////////////////////// // Helper file for Windows (WinMain) ////////////////////////////////////////////////// #include <windows.h> #include <windowsx.h> #define WINDOW_WIDTH 800 #define WINDOW_HEIGHT 600 #define BORDERLESS_WINDOW namespace WH{ // Calculate the proper size for the window given a client DWORD dwFrameWidth = GetSystemMetrics( SM_CXSIZEFRAME ); DWORD dwFrameHeight = GetSystemMetrics( SM_CYSIZEFRAME ); DWORD dwMenuHeight = GetSystemMetrics( SM_CYMENU ); DWORD gdwWindowXPos = ( GetSystemMetrics( SM_CXSCREEN ) - WINDOW_WIDTH ) / 2; DWORD gdwWindowYPos = ( GetSystemMetrics( SM_CYSCREEN ) - WINDOW_HEIGHT ) / 2; DWORD gdwWindowWidth = WINDOW_WIDTH + dwFrameWidth * 2; DWORD gdwWindowHeight = WINDOW_HEIGHT + dwFrameHeight * 2 + dwMenuHeight; }
C++
#pragma once #include <d3d11.h> #include <d3dx11.h> #include <d3dx10.h> #pragma comment (lib, "d3d11.lib") #pragma comment (lib, "d3dx11.lib") #pragma comment (lib, "d3dx10.lib") #include <stdio.h> namespace D3D{ // Test for result error inline void CheckResult(HRESULT hr){ if(hr != S_OK) printf("Failed [%x]\n", hr); } }
C++
#include "D3D11.h" D3D11::~D3D11(void){ } D3D11* D3D11::Get(){ static D3D11 instance; return &instance; } void D3D11::Init(HWND hWnd){ DXGI_SWAP_CHAIN_DESC scd; ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC)); scd.BufferCount = 1; scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; scd.OutputWindow = hWnd; scd.SampleDesc.Count = 4; scd.Windowed = TRUE; D3D11CreateDeviceAndSwapChain( NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, NULL, NULL, NULL, D3D11_SDK_VERSION, &scd, &m_swapchain, &m_device, NULL, &m_devcon); ID3D11Texture2D *pBackBuffer; m_swapchain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer); m_device->CreateRenderTargetView(pBackBuffer, NULL, &m_backbuffer); pBackBuffer->Release(); m_devcon->OMSetRenderTargets(1, &m_backbuffer, NULL); } void D3D11::Clean(){ m_swapchain->Release(); m_device->Release(); m_devcon->Release(); }
C++
#pragma once #include "D3DHelper.h" class D3D11{ public: ~D3D11(void); static D3D11* Get(); void Init(HWND hWnd); void Clean(); private: D3D11(void){} IDXGISwapChain *m_swapchain; ID3D11Device *m_device; ID3D11DeviceContext *m_devcon; ID3D11RenderTargetView *m_backbuffer; };
C++
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "DiagnosticsBase.h" #include <cassert> namespace pp { Diagnostics::~Diagnostics() { } void Diagnostics::report(ID id, const SourceLocation& loc, const std::string& text) { // TODO(alokp): Keep a count of errors and warnings. print(id, loc, text); } Diagnostics::Severity Diagnostics::severity(ID id) { if ((id > ERROR_BEGIN) && (id < ERROR_END)) return ERROR; if ((id > WARNING_BEGIN) && (id < WARNING_END)) return WARNING; assert(false); return ERROR; } std::string Diagnostics::message(ID id) { switch (id) { // Errors begin. case INTERNAL_ERROR: return "internal error"; case OUT_OF_MEMORY: return "out of memory"; case INVALID_CHARACTER: return "invalid character"; case INVALID_NUMBER: return "invalid number"; case INTEGER_OVERFLOW: return "integer overflow"; case FLOAT_OVERFLOW: return "float overflow"; case TOKEN_TOO_LONG: return "token too long"; case INVALID_EXPRESSION: return "invalid expression"; case DIVISION_BY_ZERO: return "division by zero"; case EOF_IN_COMMENT: return "unexpected end of file found in comment"; case UNEXPECTED_TOKEN: return "unexpected token"; case DIRECTIVE_INVALID_NAME: return "invalid directive name"; case MACRO_NAME_RESERVED: return "macro name is reserved"; case MACRO_REDEFINED: return "macro redefined"; case MACRO_PREDEFINED_REDEFINED: return "predefined macro redefined"; case MACRO_PREDEFINED_UNDEFINED: return "predefined macro undefined"; case MACRO_UNTERMINATED_INVOCATION: return "unterminated macro invocation"; case MACRO_TOO_FEW_ARGS: return "Not enough arguments for macro"; case MACRO_TOO_MANY_ARGS: return "Too many arguments for macro"; case CONDITIONAL_ENDIF_WITHOUT_IF: return "unexpected #endif found without a matching #if"; case CONDITIONAL_ELSE_WITHOUT_IF: return "unexpected #else found without a matching #if"; case CONDITIONAL_ELSE_AFTER_ELSE: return "unexpected #else found after another #else"; case CONDITIONAL_ELIF_WITHOUT_IF: return "unexpected #elif found without a matching #if"; case CONDITIONAL_ELIF_AFTER_ELSE: return "unexpected #elif found after #else"; case CONDITIONAL_UNTERMINATED: return "unexpected end of file found in conditional block"; case INVALID_EXTENSION_NAME: return "invalid extension name"; case INVALID_EXTENSION_BEHAVIOR: return "invalid extension behavior"; case INVALID_EXTENSION_DIRECTIVE: return "invalid extension directive"; case INVALID_VERSION_NUMBER: return "invalid version number"; case INVALID_VERSION_DIRECTIVE: return "invalid version directive"; case VERSION_NOT_FIRST_STATEMENT: return "#version directive must occur before anything else, " "except for comments and white space"; case INVALID_LINE_NUMBER: return "invalid line number"; case INVALID_FILE_NUMBER: return "invalid file number"; case INVALID_LINE_DIRECTIVE: return "invalid line directive"; // Errors end. // Warnings begin. case EOF_IN_DIRECTIVE: return "unexpected end of file found in directive"; case CONDITIONAL_UNEXPECTED_TOKEN: return "unexpected token after conditional expression"; case UNRECOGNIZED_PRAGMA: return "unrecognized pragma"; // Warnings end. default: assert(false); return ""; } } } // namespace pp
C++
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "Lexer.h" namespace pp { Lexer::~Lexer() { } } // namespace pp
C++
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_PREPROCESSOR_MACRO_EXPANDER_H_ #define COMPILER_PREPROCESSOR_MACRO_EXPANDER_H_ #include <cassert> #include <memory> #include <vector> #include "Lexer.h" #include "Macro.h" #include "pp_utils.h" namespace pp { class Diagnostics; class MacroExpander : public Lexer { public: MacroExpander(Lexer* lexer, MacroSet* macroSet, Diagnostics* diagnostics); virtual ~MacroExpander(); virtual void lex(Token* token); private: PP_DISALLOW_COPY_AND_ASSIGN(MacroExpander); void getToken(Token* token); void ungetToken(const Token& token); bool isNextTokenLeftParen(); bool pushMacro(const Macro& macro, const Token& identifier); void popMacro(); bool expandMacro(const Macro& macro, const Token& identifier, std::vector<Token>* replacements); typedef std::vector<Token> MacroArg; bool collectMacroArgs(const Macro& macro, const Token& identifier, std::vector<MacroArg>* args); void replaceMacroParams(const Macro& macro, const std::vector<MacroArg>& args, std::vector<Token>* replacements); struct MacroContext { const Macro* macro; std::size_t index; std::vector<Token> replacements; MacroContext() : macro(0), index(0) { } bool empty() const { return index == replacements.size(); } const Token& get() { return replacements[index++]; } void unget() { assert(index > 0); --index; } }; Lexer* mLexer; MacroSet* mMacroSet; Diagnostics* mDiagnostics; std::auto_ptr<Token> mReserveToken; std::vector<MacroContext*> mContextStack; }; } // namespace pp #endif // COMPILER_PREPROCESSOR_MACRO_EXPANDER_H_
C++
// // Copyright (c) 2011 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_PREPROCESSOR_INPUT_H_ #define COMPILER_PREPROCESSOR_INPUT_H_ #include <stddef.h> #include <vector> namespace pp { // Holds and reads input for Lexer. class Input { public: Input(); Input(size_t count, const char* const string[], const int length[]); size_t count() const { return mCount; } const char* string(size_t index) const { return mString[index]; } size_t length(size_t index) const { return mLength[index]; } size_t read(char* buf, size_t maxSize); struct Location { size_t sIndex; // String index; size_t cIndex; // Char index. Location() : sIndex(0), cIndex(0) { } }; const Location& readLoc() const { return mReadLoc; } private: // Input. size_t mCount; const char* const* mString; std::vector<size_t> mLength; Location mReadLoc; }; } // namespace pp #endif // COMPILER_PREPROCESSOR_INPUT_H_
C++
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_PREPROCESSOR_DIRECTIVE_PARSER_H_ #define COMPILER_PREPROCESSOR_DIRECTIVE_PARSER_H_ #include "Lexer.h" #include "Macro.h" #include "pp_utils.h" #include "SourceLocation.h" namespace pp { class Diagnostics; class DirectiveHandler; class Tokenizer; class DirectiveParser : public Lexer { public: DirectiveParser(Tokenizer* tokenizer, MacroSet* macroSet, Diagnostics* diagnostics, DirectiveHandler* directiveHandler); virtual void lex(Token* token); private: PP_DISALLOW_COPY_AND_ASSIGN(DirectiveParser); void parseDirective(Token* token); void parseDefine(Token* token); void parseUndef(Token* token); void parseIf(Token* token); void parseIfdef(Token* token); void parseIfndef(Token* token); void parseElse(Token* token); void parseElif(Token* token); void parseEndif(Token* token); void parseError(Token* token); void parsePragma(Token* token); void parseExtension(Token* token); void parseVersion(Token* token); void parseLine(Token* token); bool skipping() const; void parseConditionalIf(Token* token); int parseExpressionIf(Token* token); int parseExpressionIfdef(Token* token); struct ConditionalBlock { std::string type; SourceLocation location; bool skipBlock; bool skipGroup; bool foundValidGroup; bool foundElseGroup; ConditionalBlock() : skipBlock(false), skipGroup(false), foundValidGroup(false), foundElseGroup(false) { } }; bool mPastFirstStatement; std::vector<ConditionalBlock> mConditionalStack; Tokenizer* mTokenizer; MacroSet* mMacroSet; Diagnostics* mDiagnostics; DirectiveHandler* mDirectiveHandler; }; } // namespace pp #endif // COMPILER_PREPROCESSOR_DIRECTIVE_PARSER_H_
C++
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_PREPROCESSOR_MACRO_H_ #define COMPILER_PREPROCESSOR_MACRO_H_ #include <map> #include <string> #include <vector> namespace pp { struct Token; struct Macro { enum Type { kTypeObj, kTypeFunc }; typedef std::vector<std::string> Parameters; typedef std::vector<Token> Replacements; Macro() : predefined(false), disabled(false), type(kTypeObj) { } bool equals(const Macro& other) const; bool predefined; mutable bool disabled; Type type; std::string name; Parameters parameters; Replacements replacements; }; typedef std::map<std::string, Macro> MacroSet; } // namespace pp #endif // COMPILER_PREPROCESSOR_MACRO_H_
C++
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_PREPROCESSOR_SOURCE_LOCATION_H_ #define COMPILER_PREPROCESSOR_SOURCE_LOCATION_H_ namespace pp { struct SourceLocation { SourceLocation() : file(0), line(0) { } SourceLocation(int f, int l) : file(f), line(l) { } bool equals(const SourceLocation& other) const { return (file == other.file) && (line == other.line); } int file; int line; }; inline bool operator==(const SourceLocation& lhs, const SourceLocation& rhs) { return lhs.equals(rhs); } inline bool operator!=(const SourceLocation& lhs, const SourceLocation& rhs) { return !lhs.equals(rhs); } } // namespace pp #endif // COMPILER_PREPROCESSOR_SOURCE_LOCATION_H_
C++
// // Copyright (c) 2011 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_PREPROCESSOR_TOKEN_H_ #define COMPILER_PREPROCESSOR_TOKEN_H_ #include <ostream> #include <string> #include "SourceLocation.h" namespace pp { struct Token { enum Type { LAST = 0, // EOF. IDENTIFIER = 258, CONST_INT, CONST_FLOAT, OP_INC, OP_DEC, OP_LEFT, OP_RIGHT, OP_LE, OP_GE, OP_EQ, OP_NE, OP_AND, OP_XOR, OP_OR, OP_ADD_ASSIGN, OP_SUB_ASSIGN, OP_MUL_ASSIGN, OP_DIV_ASSIGN, OP_MOD_ASSIGN, OP_LEFT_ASSIGN, OP_RIGHT_ASSIGN, OP_AND_ASSIGN, OP_XOR_ASSIGN, OP_OR_ASSIGN, // Preprocessing token types. // These types are used by the preprocessor internally. // Preprocessor clients must not depend or check for them. PP_HASH, PP_NUMBER, PP_OTHER }; enum Flags { AT_START_OF_LINE = 1 << 0, HAS_LEADING_SPACE = 1 << 1, EXPANSION_DISABLED = 1 << 2 }; Token() : type(0), flags(0) { } void reset(); bool equals(const Token& other) const; // Returns true if this is the first token on line. // It disregards any leading whitespace. bool atStartOfLine() const { return (flags & AT_START_OF_LINE) != 0; } void setAtStartOfLine(bool start); bool hasLeadingSpace() const { return (flags & HAS_LEADING_SPACE) != 0; } void setHasLeadingSpace(bool space); bool expansionDisabled() const { return (flags & EXPANSION_DISABLED) != 0; } void setExpansionDisabled(bool disable); // Converts text into numeric value for CONST_INT and CONST_FLOAT token. // Returns false if the parsed value cannot fit into an int or float. bool iValue(int* value) const; bool uValue(unsigned int* value) const; bool fValue(float* value) const; int type; unsigned int flags; SourceLocation location; std::string text; }; inline bool operator==(const Token& lhs, const Token& rhs) { return lhs.equals(rhs); } inline bool operator!=(const Token& lhs, const Token& rhs) { return !lhs.equals(rhs); } extern std::ostream& operator<<(std::ostream& out, const Token& token); } // namepsace pp #endif // COMPILER_PREPROCESSOR_TOKEN_H_
C++
// // Copyright (c) 2011 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "Input.h" #include <algorithm> #include <cassert> #include <cstring> namespace pp { Input::Input() : mCount(0), mString(0) { } Input::Input(size_t count, const char* const string[], const int length[]) : mCount(count), mString(string) { mLength.reserve(mCount); for (size_t i = 0; i < mCount; ++i) { int len = length ? length[i] : -1; mLength.push_back(len < 0 ? std::strlen(mString[i]) : len); } } size_t Input::read(char* buf, size_t maxSize) { size_t nRead = 0; while ((nRead < maxSize) && (mReadLoc.sIndex < mCount)) { size_t size = mLength[mReadLoc.sIndex] - mReadLoc.cIndex; size = std::min(size, maxSize); std::memcpy(buf + nRead, mString[mReadLoc.sIndex] + mReadLoc.cIndex, size); nRead += size; mReadLoc.cIndex += size; // Advance string if we reached the end of current string. if (mReadLoc.cIndex == mLength[mReadLoc.sIndex]) { ++mReadLoc.sIndex; mReadLoc.cIndex = 0; } } return nRead; } } // namespace pp
C++
// // Copyright (c) 2011 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "Preprocessor.h" #include <cassert> #include <sstream> #include "DiagnosticsBase.h" #include "DirectiveParser.h" #include "Macro.h" #include "MacroExpander.h" #include "Token.h" #include "Tokenizer.h" namespace pp { struct PreprocessorImpl { Diagnostics* diagnostics; MacroSet macroSet; Tokenizer tokenizer; DirectiveParser directiveParser; MacroExpander macroExpander; PreprocessorImpl(Diagnostics* diag, DirectiveHandler* directiveHandler) : diagnostics(diag), tokenizer(diag), directiveParser(&tokenizer, &macroSet, diag, directiveHandler), macroExpander(&directiveParser, &macroSet, diag) { } }; Preprocessor::Preprocessor(Diagnostics* diagnostics, DirectiveHandler* directiveHandler) { mImpl = new PreprocessorImpl(diagnostics, directiveHandler); } Preprocessor::~Preprocessor() { delete mImpl; } bool Preprocessor::init(size_t count, const char* const string[], const int length[]) { static const int kGLSLVersion = 100; // Add standard pre-defined macros. predefineMacro("__LINE__", 0); predefineMacro("__FILE__", 0); predefineMacro("__VERSION__", kGLSLVersion); predefineMacro("GL_ES", 1); return mImpl->tokenizer.init(count, string, length); } void Preprocessor::predefineMacro(const char* name, int value) { std::ostringstream stream; stream << value; Token token; token.type = Token::CONST_INT; token.text = stream.str(); Macro macro; macro.predefined = true; macro.type = Macro::kTypeObj; macro.name = name; macro.replacements.push_back(token); mImpl->macroSet[name] = macro; } void Preprocessor::lex(Token* token) { bool validToken = false; while (!validToken) { mImpl->macroExpander.lex(token); switch (token->type) { // We should not be returning internal preprocessing tokens. // Convert preprocessing tokens to compiler tokens or report // diagnostics. case Token::PP_HASH: assert(false); break; case Token::CONST_INT: { int val = 0; if (!token->iValue(&val)) { // Do not mark the token as invalid. // Just emit the diagnostic and reset value to 0. mImpl->diagnostics->report(Diagnostics::INTEGER_OVERFLOW, token->location, token->text); token->text.assign("0"); } validToken = true; break; } case Token::CONST_FLOAT: { float val = 0; if (!token->fValue(&val)) { // Do not mark the token as invalid. // Just emit the diagnostic and reset value to 0.0. mImpl->diagnostics->report(Diagnostics::FLOAT_OVERFLOW, token->location, token->text); token->text.assign("0.0"); } validToken = true; break; } case Token::PP_NUMBER: mImpl->diagnostics->report(Diagnostics::INVALID_NUMBER, token->location, token->text); break; case Token::PP_OTHER: mImpl->diagnostics->report(Diagnostics::INVALID_CHARACTER, token->location, token->text); break; default: validToken = true; break; } } } } // namespace pp
C++
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // numeric_lex.h: Functions to extract numeric values from string. #ifndef COMPILER_PREPROCESSOR_NUMERIC_LEX_H_ #define COMPILER_PREPROCESSOR_NUMERIC_LEX_H_ #include <sstream> namespace pp { inline std::ios::fmtflags numeric_base_int(const std::string& str) { if ((str.size() >= 2) && (str[0] == '0') && (str[1] == 'x' || str[1] == 'X')) { return std::ios::hex; } else if ((str.size() >= 1) && (str[0] == '0')) { return std::ios::oct; } return std::ios::dec; } // The following functions parse the given string to extract a numerical // value of the given type. These functions assume that the string is // of the correct form. They can only fail if the parsed value is too big, // in which case false is returned. template<typename IntType> bool numeric_lex_int(const std::string& str, IntType* value) { std::istringstream stream(str); // This should not be necessary, but MSVS has a buggy implementation. // It returns incorrect results if the base is not specified. stream.setf(numeric_base_int(str), std::ios::basefield); stream >> (*value); return !stream.fail(); } template<typename FloatType> bool numeric_lex_float(const std::string& str, FloatType* value) { std::istringstream stream(str); // Force "C" locale so that decimal character is always '.', and // not dependent on the current locale. stream.imbue(std::locale::classic()); stream >> (*value); return !stream.fail(); } } // namespace pp. #endif // COMPILER_PREPROCESSOR_NUMERIC_LEX_H_
C++
// // Copyright (c) 2011 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "Macro.h" #include "Token.h" namespace pp { bool Macro::equals(const Macro& other) const { return (type == other.type) && (name == other.name) && (parameters == other.parameters) && (replacements == other.replacements); } } // namespace pp
C++
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_PREPROCESSOR_LEXER_H_ #define COMPILER_PREPROCESSOR_LEXER_H_ namespace pp { struct Token; class Lexer { public: virtual ~Lexer(); virtual void lex(Token* token) = 0; }; } // namespace pp #endif // COMPILER_PREPROCESSOR_LEXER_H_
C++
// // Copyright (c) 2011 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "Token.h" #include <cassert> #include "numeric_lex.h" namespace pp { void Token::reset() { type = 0; flags = 0; location = SourceLocation(); text.clear(); } bool Token::equals(const Token& other) const { return (type == other.type) && (flags == other.flags) && (location == other.location) && (text == other.text); } void Token::setAtStartOfLine(bool start) { if (start) flags |= AT_START_OF_LINE; else flags &= ~AT_START_OF_LINE; } void Token::setHasLeadingSpace(bool space) { if (space) flags |= HAS_LEADING_SPACE; else flags &= ~HAS_LEADING_SPACE; } void Token::setExpansionDisabled(bool disable) { if (disable) flags |= EXPANSION_DISABLED; else flags &= ~EXPANSION_DISABLED; } bool Token::iValue(int* value) const { assert(type == CONST_INT); return numeric_lex_int(text, value); } bool Token::uValue(unsigned int* value) const { assert(type == CONST_INT); return numeric_lex_int(text, value); } bool Token::fValue(float* value) const { assert(type == CONST_FLOAT); return numeric_lex_float(text, value); } std::ostream& operator<<(std::ostream& out, const Token& token) { if (token.hasLeadingSpace()) out << " "; out << token.text; return out; } } // namespace pp
C++
// // Copyright (c) 2011 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_PREPROCESSOR_PREPROCESSOR_H_ #define COMPILER_PREPROCESSOR_PREPROCESSOR_H_ #include <stddef.h> #include "pp_utils.h" namespace pp { class Diagnostics; class DirectiveHandler; struct PreprocessorImpl; struct Token; class Preprocessor { public: Preprocessor(Diagnostics* diagnostics, DirectiveHandler* directiveHandler); ~Preprocessor(); // count: specifies the number of elements in the string and length arrays. // string: specifies an array of pointers to strings. // length: specifies an array of string lengths. // If length is NULL, each string is assumed to be null terminated. // If length is a value other than NULL, it points to an array containing // a string length for each of the corresponding elements of string. // Each element in the length array may contain the length of the // corresponding string or a value less than 0 to indicate that the string // is null terminated. bool init(size_t count, const char* const string[], const int length[]); // Adds a pre-defined macro. void predefineMacro(const char* name, int value); void lex(Token* token); private: PP_DISALLOW_COPY_AND_ASSIGN(Preprocessor); PreprocessorImpl* mImpl; }; } // namespace pp #endif // COMPILER_PREPROCESSOR_PREPROCESSOR_H_
C++
// // Copyright (c) 2011 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "DirectiveParser.h" #include <cassert> #include <cstdlib> #include <sstream> #include "DiagnosticsBase.h" #include "DirectiveHandlerBase.h" #include "ExpressionParser.h" #include "MacroExpander.h" #include "Token.h" #include "Tokenizer.h" namespace { enum DirectiveType { DIRECTIVE_NONE, DIRECTIVE_DEFINE, DIRECTIVE_UNDEF, DIRECTIVE_IF, DIRECTIVE_IFDEF, DIRECTIVE_IFNDEF, DIRECTIVE_ELSE, DIRECTIVE_ELIF, DIRECTIVE_ENDIF, DIRECTIVE_ERROR, DIRECTIVE_PRAGMA, DIRECTIVE_EXTENSION, DIRECTIVE_VERSION, DIRECTIVE_LINE }; } // namespace static DirectiveType getDirective(const pp::Token* token) { static const std::string kDirectiveDefine("define"); static const std::string kDirectiveUndef("undef"); static const std::string kDirectiveIf("if"); static const std::string kDirectiveIfdef("ifdef"); static const std::string kDirectiveIfndef("ifndef"); static const std::string kDirectiveElse("else"); static const std::string kDirectiveElif("elif"); static const std::string kDirectiveEndif("endif"); static const std::string kDirectiveError("error"); static const std::string kDirectivePragma("pragma"); static const std::string kDirectiveExtension("extension"); static const std::string kDirectiveVersion("version"); static const std::string kDirectiveLine("line"); if (token->type != pp::Token::IDENTIFIER) return DIRECTIVE_NONE; if (token->text == kDirectiveDefine) return DIRECTIVE_DEFINE; else if (token->text == kDirectiveUndef) return DIRECTIVE_UNDEF; else if (token->text == kDirectiveIf) return DIRECTIVE_IF; else if (token->text == kDirectiveIfdef) return DIRECTIVE_IFDEF; else if (token->text == kDirectiveIfndef) return DIRECTIVE_IFNDEF; else if (token->text == kDirectiveElse) return DIRECTIVE_ELSE; else if (token->text == kDirectiveElif) return DIRECTIVE_ELIF; else if (token->text == kDirectiveEndif) return DIRECTIVE_ENDIF; else if (token->text == kDirectiveError) return DIRECTIVE_ERROR; else if (token->text == kDirectivePragma) return DIRECTIVE_PRAGMA; else if (token->text == kDirectiveExtension) return DIRECTIVE_EXTENSION; else if (token->text == kDirectiveVersion) return DIRECTIVE_VERSION; else if (token->text == kDirectiveLine) return DIRECTIVE_LINE; return DIRECTIVE_NONE; } static bool isConditionalDirective(DirectiveType directive) { switch (directive) { case DIRECTIVE_IF: case DIRECTIVE_IFDEF: case DIRECTIVE_IFNDEF: case DIRECTIVE_ELSE: case DIRECTIVE_ELIF: case DIRECTIVE_ENDIF: return true; default: return false; } } // Returns true if the token represents End Of Directive. static bool isEOD(const pp::Token* token) { return (token->type == '\n') || (token->type == pp::Token::LAST); } static void skipUntilEOD(pp::Lexer* lexer, pp::Token* token) { while(!isEOD(token)) { lexer->lex(token); } } static bool isMacroNameReserved(const std::string& name) { // Names prefixed with "GL_" are reserved. if (name.substr(0, 3) == "GL_") return true; // Names containing two consecutive underscores are reserved. if (name.find("__") != std::string::npos) return true; return false; } static bool isMacroPredefined(const std::string& name, const pp::MacroSet& macroSet) { pp::MacroSet::const_iterator iter = macroSet.find(name); return iter != macroSet.end() ? iter->second.predefined : false; } namespace pp { class DefinedParser : public Lexer { public: DefinedParser(Lexer* lexer, const MacroSet* macroSet, Diagnostics* diagnostics) : mLexer(lexer), mMacroSet(macroSet), mDiagnostics(diagnostics) { } protected: virtual void lex(Token* token) { static const std::string kDefined("defined"); mLexer->lex(token); if (token->type != Token::IDENTIFIER) return; if (token->text != kDefined) return; bool paren = false; mLexer->lex(token); if (token->type == '(') { paren = true; mLexer->lex(token); } if (token->type != Token::IDENTIFIER) { mDiagnostics->report(Diagnostics::UNEXPECTED_TOKEN, token->location, token->text); skipUntilEOD(mLexer, token); return; } MacroSet::const_iterator iter = mMacroSet->find(token->text); std::string expression = iter != mMacroSet->end() ? "1" : "0"; if (paren) { mLexer->lex(token); if (token->type != ')') { mDiagnostics->report(Diagnostics::UNEXPECTED_TOKEN, token->location, token->text); skipUntilEOD(mLexer, token); return; } } // We have a valid defined operator. // Convert the current token into a CONST_INT token. token->type = Token::CONST_INT; token->text = expression; } private: Lexer* mLexer; const MacroSet* mMacroSet; Diagnostics* mDiagnostics; }; DirectiveParser::DirectiveParser(Tokenizer* tokenizer, MacroSet* macroSet, Diagnostics* diagnostics, DirectiveHandler* directiveHandler) : mPastFirstStatement(false), mTokenizer(tokenizer), mMacroSet(macroSet), mDiagnostics(diagnostics), mDirectiveHandler(directiveHandler) { } void DirectiveParser::lex(Token* token) { do { mTokenizer->lex(token); if (token->type == Token::PP_HASH) { parseDirective(token); mPastFirstStatement = true; } if (token->type == Token::LAST) { if (!mConditionalStack.empty()) { const ConditionalBlock& block = mConditionalStack.back(); mDiagnostics->report(Diagnostics::CONDITIONAL_UNTERMINATED, block.location, block.type); } break; } } while (skipping() || (token->type == '\n')); mPastFirstStatement = true; } void DirectiveParser::parseDirective(Token* token) { assert(token->type == Token::PP_HASH); mTokenizer->lex(token); if (isEOD(token)) { // Empty Directive. return; } DirectiveType directive = getDirective(token); // While in an excluded conditional block/group, // we only parse conditional directives. if (skipping() && !isConditionalDirective(directive)) { skipUntilEOD(mTokenizer, token); return; } switch(directive) { case DIRECTIVE_NONE: mDiagnostics->report(Diagnostics::DIRECTIVE_INVALID_NAME, token->location, token->text); skipUntilEOD(mTokenizer, token); break; case DIRECTIVE_DEFINE: parseDefine(token); break; case DIRECTIVE_UNDEF: parseUndef(token); break; case DIRECTIVE_IF: parseIf(token); break; case DIRECTIVE_IFDEF: parseIfdef(token); break; case DIRECTIVE_IFNDEF: parseIfndef(token); break; case DIRECTIVE_ELSE: parseElse(token); break; case DIRECTIVE_ELIF: parseElif(token); break; case DIRECTIVE_ENDIF: parseEndif(token); break; case DIRECTIVE_ERROR: parseError(token); break; case DIRECTIVE_PRAGMA: parsePragma(token); break; case DIRECTIVE_EXTENSION: parseExtension(token); break; case DIRECTIVE_VERSION: parseVersion(token); break; case DIRECTIVE_LINE: parseLine(token); break; default: assert(false); break; } skipUntilEOD(mTokenizer, token); if (token->type == Token::LAST) { mDiagnostics->report(Diagnostics::EOF_IN_DIRECTIVE, token->location, token->text); } } void DirectiveParser::parseDefine(Token* token) { assert(getDirective(token) == DIRECTIVE_DEFINE); mTokenizer->lex(token); if (token->type != Token::IDENTIFIER) { mDiagnostics->report(Diagnostics::UNEXPECTED_TOKEN, token->location, token->text); return; } if (isMacroPredefined(token->text, *mMacroSet)) { mDiagnostics->report(Diagnostics::MACRO_PREDEFINED_REDEFINED, token->location, token->text); return; } if (isMacroNameReserved(token->text)) { mDiagnostics->report(Diagnostics::MACRO_NAME_RESERVED, token->location, token->text); return; } Macro macro; macro.type = Macro::kTypeObj; macro.name = token->text; mTokenizer->lex(token); if (token->type == '(' && !token->hasLeadingSpace()) { // Function-like macro. Collect arguments. macro.type = Macro::kTypeFunc; do { mTokenizer->lex(token); if (token->type != Token::IDENTIFIER) break; macro.parameters.push_back(token->text); mTokenizer->lex(token); // Get ','. } while (token->type == ','); if (token->type != ')') { mDiagnostics->report(Diagnostics::UNEXPECTED_TOKEN, token->location, token->text); return; } mTokenizer->lex(token); // Get ')'. } while ((token->type != '\n') && (token->type != Token::LAST)) { // Reset the token location because it is unnecessary in replacement // list. Resetting it also allows us to reuse Token::equals() to // compare macros. token->location = SourceLocation(); macro.replacements.push_back(*token); mTokenizer->lex(token); } if (!macro.replacements.empty()) { // Whitespace preceding the replacement list is not considered part of // the replacement list for either form of macro. macro.replacements.front().setHasLeadingSpace(false); } // Check for macro redefinition. MacroSet::const_iterator iter = mMacroSet->find(macro.name); if (iter != mMacroSet->end() && !macro.equals(iter->second)) { mDiagnostics->report(Diagnostics::MACRO_REDEFINED, token->location, macro.name); return; } mMacroSet->insert(std::make_pair(macro.name, macro)); } void DirectiveParser::parseUndef(Token* token) { assert(getDirective(token) == DIRECTIVE_UNDEF); mTokenizer->lex(token); if (token->type != Token::IDENTIFIER) { mDiagnostics->report(Diagnostics::UNEXPECTED_TOKEN, token->location, token->text); return; } MacroSet::iterator iter = mMacroSet->find(token->text); if (iter != mMacroSet->end()) { if (iter->second.predefined) { mDiagnostics->report(Diagnostics::MACRO_PREDEFINED_UNDEFINED, token->location, token->text); } else { mMacroSet->erase(iter); } } mTokenizer->lex(token); } void DirectiveParser::parseIf(Token* token) { assert(getDirective(token) == DIRECTIVE_IF); parseConditionalIf(token); } void DirectiveParser::parseIfdef(Token* token) { assert(getDirective(token) == DIRECTIVE_IFDEF); parseConditionalIf(token); } void DirectiveParser::parseIfndef(Token* token) { assert(getDirective(token) == DIRECTIVE_IFNDEF); parseConditionalIf(token); } void DirectiveParser::parseElse(Token* token) { assert(getDirective(token) == DIRECTIVE_ELSE); if (mConditionalStack.empty()) { mDiagnostics->report(Diagnostics::CONDITIONAL_ELSE_WITHOUT_IF, token->location, token->text); skipUntilEOD(mTokenizer, token); return; } ConditionalBlock& block = mConditionalStack.back(); if (block.skipBlock) { // No diagnostics. Just skip the whole line. skipUntilEOD(mTokenizer, token); return; } if (block.foundElseGroup) { mDiagnostics->report(Diagnostics::CONDITIONAL_ELSE_AFTER_ELSE, token->location, token->text); skipUntilEOD(mTokenizer, token); return; } block.foundElseGroup = true; block.skipGroup = block.foundValidGroup; block.foundValidGroup = true; // Warn if there are extra tokens after #else. mTokenizer->lex(token); if (!isEOD(token)) { mDiagnostics->report(Diagnostics::CONDITIONAL_UNEXPECTED_TOKEN, token->location, token->text); skipUntilEOD(mTokenizer, token); } } void DirectiveParser::parseElif(Token* token) { assert(getDirective(token) == DIRECTIVE_ELIF); if (mConditionalStack.empty()) { mDiagnostics->report(Diagnostics::CONDITIONAL_ELIF_WITHOUT_IF, token->location, token->text); skipUntilEOD(mTokenizer, token); return; } ConditionalBlock& block = mConditionalStack.back(); if (block.skipBlock) { // No diagnostics. Just skip the whole line. skipUntilEOD(mTokenizer, token); return; } if (block.foundElseGroup) { mDiagnostics->report(Diagnostics::CONDITIONAL_ELIF_AFTER_ELSE, token->location, token->text); skipUntilEOD(mTokenizer, token); return; } if (block.foundValidGroup) { // Do not parse the expression. // Also be careful not to emit a diagnostic. block.skipGroup = true; skipUntilEOD(mTokenizer, token); return; } int expression = parseExpressionIf(token); block.skipGroup = expression == 0; block.foundValidGroup = expression != 0; } void DirectiveParser::parseEndif(Token* token) { assert(getDirective(token) == DIRECTIVE_ENDIF); if (mConditionalStack.empty()) { mDiagnostics->report(Diagnostics::CONDITIONAL_ENDIF_WITHOUT_IF, token->location, token->text); skipUntilEOD(mTokenizer, token); return; } mConditionalStack.pop_back(); // Warn if there are tokens after #endif. mTokenizer->lex(token); if (!isEOD(token)) { mDiagnostics->report(Diagnostics::CONDITIONAL_UNEXPECTED_TOKEN, token->location, token->text); skipUntilEOD(mTokenizer, token); } } void DirectiveParser::parseError(Token* token) { assert(getDirective(token) == DIRECTIVE_ERROR); std::ostringstream stream; mTokenizer->lex(token); while ((token->type != '\n') && (token->type != Token::LAST)) { stream << *token; mTokenizer->lex(token); } mDirectiveHandler->handleError(token->location, stream.str()); } // Parses pragma of form: #pragma name[(value)]. void DirectiveParser::parsePragma(Token* token) { assert(getDirective(token) == DIRECTIVE_PRAGMA); enum State { PRAGMA_NAME, LEFT_PAREN, PRAGMA_VALUE, RIGHT_PAREN }; bool valid = true; std::string name, value; int state = PRAGMA_NAME; mTokenizer->lex(token); while ((token->type != '\n') && (token->type != Token::LAST)) { switch(state++) { case PRAGMA_NAME: name = token->text; valid = valid && (token->type == Token::IDENTIFIER); break; case LEFT_PAREN: valid = valid && (token->type == '('); break; case PRAGMA_VALUE: value = token->text; valid = valid && (token->type == Token::IDENTIFIER); break; case RIGHT_PAREN: valid = valid && (token->type == ')'); break; default: valid = false; break; } mTokenizer->lex(token); } valid = valid && ((state == PRAGMA_NAME) || // Empty pragma. (state == LEFT_PAREN) || // Without value. (state == RIGHT_PAREN + 1)); // With value. if (!valid) { mDiagnostics->report(Diagnostics::UNRECOGNIZED_PRAGMA, token->location, name); } else if (state > PRAGMA_NAME) // Do not notify for empty pragma. { mDirectiveHandler->handlePragma(token->location, name, value); } } void DirectiveParser::parseExtension(Token* token) { assert(getDirective(token) == DIRECTIVE_EXTENSION); enum State { EXT_NAME, COLON, EXT_BEHAVIOR }; bool valid = true; std::string name, behavior; int state = EXT_NAME; mTokenizer->lex(token); while ((token->type != '\n') && (token->type != Token::LAST)) { switch (state++) { case EXT_NAME: if (valid && (token->type != Token::IDENTIFIER)) { mDiagnostics->report(Diagnostics::INVALID_EXTENSION_NAME, token->location, token->text); valid = false; } if (valid) name = token->text; break; case COLON: if (valid && (token->type != ':')) { mDiagnostics->report(Diagnostics::UNEXPECTED_TOKEN, token->location, token->text); valid = false; } break; case EXT_BEHAVIOR: if (valid && (token->type != Token::IDENTIFIER)) { mDiagnostics->report(Diagnostics::INVALID_EXTENSION_BEHAVIOR, token->location, token->text); valid = false; } if (valid) behavior = token->text; break; default: if (valid) { mDiagnostics->report(Diagnostics::UNEXPECTED_TOKEN, token->location, token->text); valid = false; } break; } mTokenizer->lex(token); } if (valid && (state != EXT_BEHAVIOR + 1)) { mDiagnostics->report(Diagnostics::INVALID_EXTENSION_DIRECTIVE, token->location, token->text); valid = false; } if (valid) mDirectiveHandler->handleExtension(token->location, name, behavior); } void DirectiveParser::parseVersion(Token* token) { assert(getDirective(token) == DIRECTIVE_VERSION); if (mPastFirstStatement) { mDiagnostics->report(Diagnostics::VERSION_NOT_FIRST_STATEMENT, token->location, token->text); skipUntilEOD(mTokenizer, token); return; } enum State { VERSION_NUMBER }; bool valid = true; int version = 0; int state = VERSION_NUMBER; mTokenizer->lex(token); while ((token->type != '\n') && (token->type != Token::LAST)) { switch (state++) { case VERSION_NUMBER: if (valid && (token->type != Token::CONST_INT)) { mDiagnostics->report(Diagnostics::INVALID_VERSION_NUMBER, token->location, token->text); valid = false; } if (valid && !token->iValue(&version)) { mDiagnostics->report(Diagnostics::INTEGER_OVERFLOW, token->location, token->text); valid = false; } break; default: if (valid) { mDiagnostics->report(Diagnostics::UNEXPECTED_TOKEN, token->location, token->text); valid = false; } break; } mTokenizer->lex(token); } if (valid && (state != VERSION_NUMBER + 1)) { mDiagnostics->report(Diagnostics::INVALID_VERSION_DIRECTIVE, token->location, token->text); valid = false; } if (valid) mDirectiveHandler->handleVersion(token->location, version); } void DirectiveParser::parseLine(Token* token) { assert(getDirective(token) == DIRECTIVE_LINE); enum State { LINE_NUMBER, FILE_NUMBER }; bool valid = true; int line = 0, file = 0; int state = LINE_NUMBER; MacroExpander macroExpander(mTokenizer, mMacroSet, mDiagnostics); macroExpander.lex(token); while ((token->type != '\n') && (token->type != Token::LAST)) { switch (state++) { case LINE_NUMBER: if (valid && (token->type != Token::CONST_INT)) { mDiagnostics->report(Diagnostics::INVALID_LINE_NUMBER, token->location, token->text); valid = false; } if (valid && !token->iValue(&line)) { mDiagnostics->report(Diagnostics::INTEGER_OVERFLOW, token->location, token->text); valid = false; } break; case FILE_NUMBER: if (valid && (token->type != Token::CONST_INT)) { mDiagnostics->report(Diagnostics::INVALID_FILE_NUMBER, token->location, token->text); valid = false; } if (valid && !token->iValue(&file)) { mDiagnostics->report(Diagnostics::INTEGER_OVERFLOW, token->location, token->text); valid = false; } break; default: if (valid) { mDiagnostics->report(Diagnostics::UNEXPECTED_TOKEN, token->location, token->text); valid = false; } break; } macroExpander.lex(token); } if (valid && (state != FILE_NUMBER) && (state != FILE_NUMBER + 1)) { mDiagnostics->report(Diagnostics::INVALID_LINE_DIRECTIVE, token->location, token->text); valid = false; } if (valid) { mTokenizer->setLineNumber(line); if (state == FILE_NUMBER + 1) mTokenizer->setFileNumber(file); } } bool DirectiveParser::skipping() const { if (mConditionalStack.empty()) return false; const ConditionalBlock& block = mConditionalStack.back(); return block.skipBlock || block.skipGroup; } void DirectiveParser::parseConditionalIf(Token* token) { ConditionalBlock block; block.type = token->text; block.location = token->location; if (skipping()) { // This conditional block is inside another conditional group // which is skipped. As a consequence this whole block is skipped. // Be careful not to parse the conditional expression that might // emit a diagnostic. skipUntilEOD(mTokenizer, token); block.skipBlock = true; } else { DirectiveType directive = getDirective(token); int expression = 0; switch (directive) { case DIRECTIVE_IF: expression = parseExpressionIf(token); break; case DIRECTIVE_IFDEF: expression = parseExpressionIfdef(token); break; case DIRECTIVE_IFNDEF: expression = parseExpressionIfdef(token) == 0 ? 1 : 0; break; default: assert(false); break; } block.skipGroup = expression == 0; block.foundValidGroup = expression != 0; } mConditionalStack.push_back(block); } int DirectiveParser::parseExpressionIf(Token* token) { assert((getDirective(token) == DIRECTIVE_IF) || (getDirective(token) == DIRECTIVE_ELIF)); DefinedParser definedParser(mTokenizer, mMacroSet, mDiagnostics); MacroExpander macroExpander(&definedParser, mMacroSet, mDiagnostics); ExpressionParser expressionParser(&macroExpander, mDiagnostics); int expression = 0; macroExpander.lex(token); expressionParser.parse(token, &expression); // Warn if there are tokens after #if expression. if (!isEOD(token)) { mDiagnostics->report(Diagnostics::CONDITIONAL_UNEXPECTED_TOKEN, token->location, token->text); skipUntilEOD(mTokenizer, token); } return expression; } int DirectiveParser::parseExpressionIfdef(Token* token) { assert((getDirective(token) == DIRECTIVE_IFDEF) || (getDirective(token) == DIRECTIVE_IFNDEF)); mTokenizer->lex(token); if (token->type != Token::IDENTIFIER) { mDiagnostics->report(Diagnostics::UNEXPECTED_TOKEN, token->location, token->text); skipUntilEOD(mTokenizer, token); return 0; } MacroSet::const_iterator iter = mMacroSet->find(token->text); int expression = iter != mMacroSet->end() ? 1 : 0; // Warn if there are tokens after #ifdef expression. mTokenizer->lex(token); if (!isEOD(token)) { mDiagnostics->report(Diagnostics::CONDITIONAL_UNEXPECTED_TOKEN, token->location, token->text); skipUntilEOD(mTokenizer, token); } return expression; } } // namespace pp
C++
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "DirectiveHandlerBase.h" namespace pp { DirectiveHandler::~DirectiveHandler() { } } // namespace pp
C++
// // Copyright (c) 2011 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "MacroExpander.h" #include <algorithm> #include <sstream> #include "DiagnosticsBase.h" #include "Token.h" namespace pp { class TokenLexer : public Lexer { public: typedef std::vector<Token> TokenVector; TokenLexer(TokenVector* tokens) { tokens->swap(mTokens); mIter = mTokens.begin(); } virtual void lex(Token* token) { if (mIter == mTokens.end()) { token->reset(); token->type = Token::LAST; } else { *token = *mIter++; } } private: PP_DISALLOW_COPY_AND_ASSIGN(TokenLexer); TokenVector mTokens; TokenVector::const_iterator mIter; }; MacroExpander::MacroExpander(Lexer* lexer, MacroSet* macroSet, Diagnostics* diagnostics) : mLexer(lexer), mMacroSet(macroSet), mDiagnostics(diagnostics) { } MacroExpander::~MacroExpander() { for (std::size_t i = 0; i < mContextStack.size(); ++i) { delete mContextStack[i]; } } void MacroExpander::lex(Token* token) { while (true) { getToken(token); if (token->type != Token::IDENTIFIER) break; if (token->expansionDisabled()) break; MacroSet::const_iterator iter = mMacroSet->find(token->text); if (iter == mMacroSet->end()) break; const Macro& macro = iter->second; if (macro.disabled) { // If a particular token is not expanded, it is never expanded. token->setExpansionDisabled(true); break; } if ((macro.type == Macro::kTypeFunc) && !isNextTokenLeftParen()) { // If the token immediately after the macro name is not a '(', // this macro should not be expanded. break; } pushMacro(macro, *token); } } void MacroExpander::getToken(Token* token) { if (mReserveToken.get()) { *token = *mReserveToken; mReserveToken.reset(); return; } // First pop all empty macro contexts. while (!mContextStack.empty() && mContextStack.back()->empty()) { popMacro(); } if (!mContextStack.empty()) { *token = mContextStack.back()->get(); } else { mLexer->lex(token); } } void MacroExpander::ungetToken(const Token& token) { if (!mContextStack.empty()) { MacroContext* context = mContextStack.back(); context->unget(); assert(context->replacements[context->index] == token); } else { assert(!mReserveToken.get()); mReserveToken.reset(new Token(token)); } } bool MacroExpander::isNextTokenLeftParen() { Token token; getToken(&token); bool lparen = token.type == '('; ungetToken(token); return lparen; } bool MacroExpander::pushMacro(const Macro& macro, const Token& identifier) { assert(!macro.disabled); assert(!identifier.expansionDisabled()); assert(identifier.type == Token::IDENTIFIER); assert(identifier.text == macro.name); std::vector<Token> replacements; if (!expandMacro(macro, identifier, &replacements)) return false; // Macro is disabled for expansion until it is popped off the stack. macro.disabled = true; MacroContext* context = new MacroContext; context->macro = &macro; context->replacements.swap(replacements); mContextStack.push_back(context); return true; } void MacroExpander::popMacro() { assert(!mContextStack.empty()); MacroContext* context = mContextStack.back(); mContextStack.pop_back(); assert(context->empty()); assert(context->macro->disabled); context->macro->disabled = false; delete context; } bool MacroExpander::expandMacro(const Macro& macro, const Token& identifier, std::vector<Token>* replacements) { replacements->clear(); if (macro.type == Macro::kTypeObj) { replacements->assign(macro.replacements.begin(), macro.replacements.end()); if (macro.predefined) { static const std::string kLine = "__LINE__"; static const std::string kFile = "__FILE__"; assert(replacements->size() == 1); Token& repl = replacements->front(); if (macro.name == kLine) { std::ostringstream stream; stream << identifier.location.line; repl.text = stream.str(); } else if (macro.name == kFile) { std::ostringstream stream; stream << identifier.location.file; repl.text = stream.str(); } } } else { assert(macro.type == Macro::kTypeFunc); std::vector<MacroArg> args; args.reserve(macro.parameters.size()); if (!collectMacroArgs(macro, identifier, &args)) return false; replaceMacroParams(macro, args, replacements); } for (std::size_t i = 0; i < replacements->size(); ++i) { Token& repl = replacements->at(i); if (i == 0) { // The first token in the replacement list inherits the padding // properties of the identifier token. repl.setAtStartOfLine(identifier.atStartOfLine()); repl.setHasLeadingSpace(identifier.hasLeadingSpace()); } repl.location = identifier.location; } return true; } bool MacroExpander::collectMacroArgs(const Macro& macro, const Token& identifier, std::vector<MacroArg>* args) { Token token; getToken(&token); assert(token.type == '('); args->push_back(MacroArg()); for (int openParens = 1; openParens != 0; ) { getToken(&token); if (token.type == Token::LAST) { mDiagnostics->report(Diagnostics::MACRO_UNTERMINATED_INVOCATION, identifier.location, identifier.text); // Do not lose EOF token. ungetToken(token); return false; } bool isArg = false; // True if token is part of the current argument. switch (token.type) { case '(': ++openParens; isArg = true; break; case ')': --openParens; isArg = openParens != 0; break; case ',': // The individual arguments are separated by comma tokens, but // the comma tokens between matching inner parentheses do not // seperate arguments. if (openParens == 1) args->push_back(MacroArg()); isArg = openParens != 1; break; default: isArg = true; break; } if (isArg) { MacroArg& arg = args->back(); // Initial whitespace is not part of the argument. if (arg.empty()) token.setHasLeadingSpace(false); arg.push_back(token); } } const Macro::Parameters& params = macro.parameters; // If there is only one empty argument, it is equivalent to no argument. if (params.empty() && (args->size() == 1) && args->front().empty()) { args->clear(); } // Validate the number of arguments. if (args->size() != params.size()) { Diagnostics::ID id = args->size() < macro.parameters.size() ? Diagnostics::MACRO_TOO_FEW_ARGS : Diagnostics::MACRO_TOO_MANY_ARGS; mDiagnostics->report(id, identifier.location, identifier.text); return false; } // Pre-expand each argument before substitution. // This step expands each argument individually before they are // inserted into the macro body. for (std::size_t i = 0; i < args->size(); ++i) { MacroArg& arg = args->at(i); TokenLexer lexer(&arg); MacroExpander expander(&lexer, mMacroSet, mDiagnostics); arg.clear(); expander.lex(&token); while (token.type != Token::LAST) { arg.push_back(token); expander.lex(&token); } } return true; } void MacroExpander::replaceMacroParams(const Macro& macro, const std::vector<MacroArg>& args, std::vector<Token>* replacements) { for (std::size_t i = 0; i < macro.replacements.size(); ++i) { const Token& repl = macro.replacements[i]; if (repl.type != Token::IDENTIFIER) { replacements->push_back(repl); continue; } // TODO(alokp): Optimize this. // There is no need to search for macro params every time. // The param index can be cached with the replacement token. Macro::Parameters::const_iterator iter = std::find( macro.parameters.begin(), macro.parameters.end(), repl.text); if (iter == macro.parameters.end()) { replacements->push_back(repl); continue; } std::size_t iArg = std::distance(macro.parameters.begin(), iter); const MacroArg& arg = args[iArg]; if (arg.empty()) { continue; } std::size_t iRepl = replacements->size(); replacements->insert(replacements->end(), arg.begin(), arg.end()); // The replacement token inherits padding properties from // macro replacement token. replacements->at(iRepl).setHasLeadingSpace(repl.hasLeadingSpace()); } } } // namespace pp
C++
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_PREPROCESSOR_TOKENIZER_H_ #define COMPILER_PREPROCESSOR_TOKENIZER_H_ #include "Input.h" #include "Lexer.h" #include "pp_utils.h" namespace pp { class Diagnostics; class Tokenizer : public Lexer { public: struct Context { Diagnostics* diagnostics; Input input; // The location where yytext points to. Token location should track // scanLoc instead of Input::mReadLoc because they may not be the same // if text is buffered up in the scanner input buffer. Input::Location scanLoc; bool leadingSpace; bool lineStart; }; static const std::size_t kMaxTokenLength; Tokenizer(Diagnostics* diagnostics); ~Tokenizer(); bool init(size_t count, const char* const string[], const int length[]); void setFileNumber(int file); void setLineNumber(int line); virtual void lex(Token* token); private: PP_DISALLOW_COPY_AND_ASSIGN(Tokenizer); bool initScanner(); void destroyScanner(); void* mHandle; // Scanner handle. Context mContext; // Scanner extra. }; } // namespace pp #endif // COMPILER_PREPROCESSOR_TOKENIZER_H_
C++
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_PREPROCESSOR_EXPRESSION_PARSER_H_ #define COMPILER_PREPROCESSOR_EXPRESSION_PARSER_H_ #include "pp_utils.h" namespace pp { class Diagnostics; class Lexer; struct Token; class ExpressionParser { public: ExpressionParser(Lexer* lexer, Diagnostics* diagnostics); bool parse(Token* token, int* result); private: PP_DISALLOW_COPY_AND_ASSIGN(ExpressionParser); Lexer* mLexer; Diagnostics* mDiagnostics; }; } // namespace pp #endif // COMPILER_PREPROCESSOR_EXPRESSION_PARSER_H_
C++
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_PREPROCESSOR_DIRECTIVE_HANDLER_H_ #define COMPILER_PREPROCESSOR_DIRECTIVE_HANDLER_H_ #include <string> namespace pp { struct SourceLocation; // Base class for handling directives. // Preprocessor uses this class to notify the clients about certain // preprocessor directives. Derived classes are responsible for // handling them in an appropriate manner. class DirectiveHandler { public: virtual ~DirectiveHandler(); virtual void handleError(const SourceLocation& loc, const std::string& msg) = 0; // Handle pragma of form: #pragma name[(value)] virtual void handlePragma(const SourceLocation& loc, const std::string& name, const std::string& value) = 0; virtual void handleExtension(const SourceLocation& loc, const std::string& name, const std::string& behavior) = 0; virtual void handleVersion(const SourceLocation& loc, int version) = 0; }; } // namespace pp #endif // COMPILER_PREPROCESSOR_DIRECTIVE_HANDLER_H_
C++
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_PREPROCESSOR_DIAGNOSTICS_H_ #define COMPILER_PREPROCESSOR_DIAGNOSTICS_H_ #include <string> namespace pp { struct SourceLocation; // Base class for reporting diagnostic messages. // Derived classes are responsible for formatting and printing the messages. class Diagnostics { public: enum Severity { ERROR, WARNING }; enum ID { ERROR_BEGIN, INTERNAL_ERROR, OUT_OF_MEMORY, INVALID_CHARACTER, INVALID_NUMBER, INTEGER_OVERFLOW, FLOAT_OVERFLOW, TOKEN_TOO_LONG, INVALID_EXPRESSION, DIVISION_BY_ZERO, EOF_IN_COMMENT, UNEXPECTED_TOKEN, DIRECTIVE_INVALID_NAME, MACRO_NAME_RESERVED, MACRO_REDEFINED, MACRO_PREDEFINED_REDEFINED, MACRO_PREDEFINED_UNDEFINED, MACRO_UNTERMINATED_INVOCATION, MACRO_TOO_FEW_ARGS, MACRO_TOO_MANY_ARGS, CONDITIONAL_ENDIF_WITHOUT_IF, CONDITIONAL_ELSE_WITHOUT_IF, CONDITIONAL_ELSE_AFTER_ELSE, CONDITIONAL_ELIF_WITHOUT_IF, CONDITIONAL_ELIF_AFTER_ELSE, CONDITIONAL_UNTERMINATED, INVALID_EXTENSION_NAME, INVALID_EXTENSION_BEHAVIOR, INVALID_EXTENSION_DIRECTIVE, INVALID_VERSION_NUMBER, INVALID_VERSION_DIRECTIVE, VERSION_NOT_FIRST_STATEMENT, INVALID_LINE_NUMBER, INVALID_FILE_NUMBER, INVALID_LINE_DIRECTIVE, ERROR_END, WARNING_BEGIN, EOF_IN_DIRECTIVE, CONDITIONAL_UNEXPECTED_TOKEN, UNRECOGNIZED_PRAGMA, WARNING_END }; virtual ~Diagnostics(); void report(ID id, const SourceLocation& loc, const std::string& text); protected: Severity severity(ID id); std::string message(ID id); virtual void print(ID id, const SourceLocation& loc, const std::string& text) = 0; }; } // namespace pp #endif // COMPILER_PREPROCESSOR_DIAGNOSTICS_H_
C++
/* A Bison parser, made by GNU Bison 2.7. */ /* Bison implementation for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2012 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "2.7" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 1 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* Substitute the variable and function names. */ #define yyparse ppparse #define yylex pplex #define yyerror pperror #define yylval pplval #define yychar ppchar #define yydebug ppdebug #define yynerrs ppnerrs /* Copy the first part of user declarations. */ // // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // This file is auto-generated by generate_parser.sh. DO NOT EDIT! #if defined(__GNUC__) // Triggered by the auto-generated pplval variable. #if !defined(__clang__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)) #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #else #pragma GCC diagnostic ignored "-Wuninitialized" #endif #elif defined(_MSC_VER) #pragma warning(disable: 4065 4701) #endif #include "ExpressionParser.h" #include <cassert> #include <sstream> #include "DiagnosticsBase.h" #include "Lexer.h" #include "Token.h" #if defined(_MSC_VER) typedef __int64 YYSTYPE; #else #include <stdint.h> typedef intmax_t YYSTYPE; #endif // _MSC_VER #define YYENABLE_NLS 0 #define YYLTYPE_IS_TRIVIAL 1 #define YYSTYPE_IS_TRIVIAL 1 #define YYSTYPE_IS_DECLARED 1 namespace { struct Context { pp::Diagnostics* diagnostics; pp::Lexer* lexer; pp::Token* token; int* result; }; } // namespace static int yylex(YYSTYPE* lvalp, Context* context); static void yyerror(Context* context, const char* reason); # ifndef YY_NULL # if defined __cplusplus && 201103L <= __cplusplus # define YY_NULL nullptr # else # define YY_NULL 0 # endif # endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int ppdebug; #endif /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { TOK_CONST_INT = 258, TOK_OP_OR = 259, TOK_OP_AND = 260, TOK_OP_NE = 261, TOK_OP_EQ = 262, TOK_OP_GE = 263, TOK_OP_LE = 264, TOK_OP_RIGHT = 265, TOK_OP_LEFT = 266, TOK_UNARY = 267 }; #endif #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef int YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 #endif #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int ppparse (void *YYPARSE_PARAM); #else int ppparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int ppparse (Context *context); #else int ppparse (); #endif #endif /* ! YYPARSE_PARAM */ /* Copy the second part of user declarations. */ #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #elif (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) typedef signed char yytype_int8; #else typedef short int yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(Msgid) dgettext ("bison-runtime", Msgid) # endif # endif # ifndef YY_ # define YY_(Msgid) Msgid # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(E) ((void) (E)) #else # define YYUSE(E) /* empty */ #endif /* Identity function, used to suppress warnings about constant conditions. */ #ifndef lint # define YYID(N) (N) #else #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static int YYID (int yyi) #else static int YYID (yyi) int yyi; #endif { return yyi; } #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ /* Use EXIT_SUCCESS as a witness for stdlib.h. */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's `empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss_alloc; YYSTYPE yyvs_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ + YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (YYID (0)) #endif #if defined YYCOPY_NEEDED && YYCOPY_NEEDED /* Copy COUNT objects from SRC to DST. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(Dst, Src, Count) \ __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src))) # else # define YYCOPY(Dst, Src, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (Dst)[yyi] = (Src)[yyi]; \ } \ while (YYID (0)) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL 14 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 175 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 27 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 3 /* YYNRULES -- Number of rules. */ #define YYNRULES 26 /* YYNRULES -- Number of states. */ #define YYNSTATES 52 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 267 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 23, 2, 2, 2, 21, 8, 2, 25, 26, 19, 17, 2, 18, 2, 20, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 11, 2, 12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 7, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 2, 24, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 9, 10, 13, 14, 15, 16, 22 }; #if YYDEBUG /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ static const yytype_uint8 yyprhs[] = { 0, 0, 3, 5, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47, 51, 55, 59, 63, 67, 71, 75, 79, 82, 85, 88, 91 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const yytype_int8 yyrhs[] = { 28, 0, -1, 29, -1, 3, -1, 29, 4, 29, -1, 29, 5, 29, -1, 29, 6, 29, -1, 29, 7, 29, -1, 29, 8, 29, -1, 29, 9, 29, -1, 29, 10, 29, -1, 29, 13, 29, -1, 29, 14, 29, -1, 29, 12, 29, -1, 29, 11, 29, -1, 29, 15, 29, -1, 29, 16, 29, -1, 29, 18, 29, -1, 29, 17, 29, -1, 29, 21, 29, -1, 29, 20, 29, -1, 29, 19, 29, -1, 23, 29, -1, 24, 29, -1, 18, 29, -1, 17, 29, -1, 25, 29, 26, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const yytype_uint8 yyrline[] = { 0, 91, 91, 98, 99, 102, 105, 108, 111, 114, 117, 120, 123, 126, 129, 132, 135, 138, 141, 144, 157, 170, 173, 176, 179, 182, 185 }; #endif #if YYDEBUG || YYERROR_VERBOSE || 0 /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "TOK_CONST_INT", "TOK_OP_OR", "TOK_OP_AND", "'|'", "'^'", "'&'", "TOK_OP_NE", "TOK_OP_EQ", "'<'", "'>'", "TOK_OP_GE", "TOK_OP_LE", "TOK_OP_RIGHT", "TOK_OP_LEFT", "'+'", "'-'", "'*'", "'/'", "'%'", "TOK_UNARY", "'!'", "'~'", "'('", "')'", "$accept", "input", "expression", YY_NULL }; #endif # ifdef YYPRINT /* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to token YYLEX-NUM. */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 124, 94, 38, 261, 262, 60, 62, 263, 264, 265, 266, 43, 45, 42, 47, 37, 267, 33, 126, 40, 41 }; # endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 27, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 3 }; /* YYDEFACT[STATE-NAME] -- Default reduction number in state STATE-NUM. Performed when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const yytype_uint8 yydefact[] = { 0, 3, 0, 0, 0, 0, 0, 0, 2, 25, 24, 22, 23, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 26, 4, 5, 6, 7, 8, 9, 10, 14, 13, 11, 12, 15, 16, 18, 17, 21, 20, 19 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int8 yydefgoto[] = { -1, 7, 8 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ #define YYPACT_NINF -11 static const yytype_int16 yypact[] = { 46, -11, 46, 46, 46, 46, 46, 12, 68, -11, -11, -11, -11, 27, -11, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, -11, 85, 101, 116, 130, 143, 154, 154, -10, -10, -10, -10, 37, 37, 31, 31, -11, -11, -11 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int8 yypgoto[] = { -11, -11, -2 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If YYTABLE_NINF, syntax error. */ #define YYTABLE_NINF -1 static const yytype_uint8 yytable[] = { 9, 10, 11, 12, 13, 26, 27, 28, 29, 30, 31, 32, 14, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 1, 30, 31, 32, 33, 28, 29, 30, 31, 32, 0, 0, 0, 0, 2, 3, 0, 0, 0, 0, 4, 5, 6, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 }; #define yypact_value_is_default(Yystate) \ (!!((Yystate) == (-11))) #define yytable_value_is_error(Yytable_value) \ YYID (0) static const yytype_int8 yycheck[] = { 2, 3, 4, 5, 6, 15, 16, 17, 18, 19, 20, 21, 0, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 3, 19, 20, 21, 26, 17, 18, 19, 20, 21, -1, -1, -1, -1, 17, 18, -1, -1, -1, -1, 23, 24, 25, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 3, 17, 18, 23, 24, 25, 28, 29, 29, 29, 29, 29, 29, 0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 26, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. However, YYFAIL appears to be in use. Nevertheless, it is formally deprecated in Bison 2.4.2's NEWS entry, where a plan to phase it out is discussed. */ #define YYFAIL goto yyerrlab #if defined YYFAIL /* This is here to suppress warnings from the GCC cpp's -Wunused-macros. Normally we don't worry about that warning, but some users do, and we want to make it easy for users to remove YYFAIL uses, which will produce warnings from Bison 2.5. */ #endif #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY) \ { \ yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (yylen); \ yystate = *yyssp; \ goto yybackup; \ } \ else \ { \ yyerror (context, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (YYID (0)) /* Error token number */ #define YYTERROR 1 #define YYERRCODE 256 /* This macro is provided for backward compatibility. */ #ifndef YY_LOCATION_PRINT # define YY_LOCATION_PRINT(File, Loc) ((void) 0) #endif /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM # define YYLEX yylex (&yylval, YYLEX_PARAM) #else # define YYLEX yylex (&yylval, context) #endif /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (YYID (0)) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, context); \ YYFPRINTF (stderr, "\n"); \ } \ } while (YYID (0)) /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, Context *context) #else static void yy_symbol_value_print (yyoutput, yytype, yyvaluep, context) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; Context *context; #endif { FILE *yyo = yyoutput; YYUSE (yyo); if (!yyvaluep) return; YYUSE (context); # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # else YYUSE (yyoutput); # endif switch (yytype) { default: break; } } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, Context *context) #else static void yy_symbol_print (yyoutput, yytype, yyvaluep, context) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; Context *context; #endif { if (yytype < YYNTOKENS) YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); else YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); yy_symbol_value_print (yyoutput, yytype, yyvaluep, context); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) #else static void yy_stack_print (yybottom, yytop) yytype_int16 *yybottom; yytype_int16 *yytop; #endif { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_reduce_print (YYSTYPE *yyvsp, int yyrule, Context *context) #else static void yy_reduce_print (yyvsp, yyrule, context) YYSTYPE *yyvsp; int yyrule; Context *context; #endif { int yynrhs = yyr2[yyrule]; int yyi; unsigned long int yylno = yyrline[yyrule]; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], &(yyvsp[(yyi + 1) - (yynrhs)]) , context); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyvsp, Rule, context); \ } while (YYID (0)) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static YYSIZE_T yystrlen (const char *yystr) #else static YYSIZE_T yystrlen (yystr) const char *yystr; #endif { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static char * yystpcpy (char *yydest, const char *yysrc) #else static char * yystpcpy (yydest, yysrc) char *yydest; const char *yysrc; #endif { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message about the unexpected token YYTOKEN for the state stack whose top is YYSSP. Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is not large enough to hold the message. In that case, also set *YYMSG_ALLOC to the required number of bytes. Return 2 if the required number of bytes is too large to store. */ static int yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, yytype_int16 *yyssp, int yytoken) { YYSIZE_T yysize0 = yytnamerr (YY_NULL, yytname[yytoken]); YYSIZE_T yysize = yysize0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; /* Internationalized format string. */ const char *yyformat = YY_NULL; /* Arguments of yyformat. */ char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; /* Number of reported tokens (one for the "unexpected", one per "expected"). */ int yycount = 0; /* There are many possibilities here to consider: - Assume YYFAIL is not used. It's too flawed to consider. See <http://lists.gnu.org/archive/html/bison-patches/2009-12/msg00024.html> for details. YYERROR is fine as it does not invoke this function. - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yychar) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (yytoken != YYEMPTY) { int yyn = yypact[*yyssp]; yyarg[yycount++] = yytname[yytoken]; if (!yypact_value_is_default (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yyx; for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR && !yytable_value_is_error (yytable[yyx + yyn])) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; break; } yyarg[yycount++] = yytname[yyx]; { YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULL, yytname[yyx]); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } } } } switch (yycount) { # define YYCASE_(N, S) \ case N: \ yyformat = S; \ break YYCASE_(0, YY_("syntax error")); YYCASE_(1, YY_("syntax error, unexpected %s")); YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); # undef YYCASE_ } { YYSIZE_T yysize1 = yysize + yystrlen (yyformat); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } if (*yymsg_alloc < yysize) { *yymsg_alloc = 2 * yysize; if (! (yysize <= *yymsg_alloc && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; return 1; } /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ { char *yyp = *yymsg; int yyi = 0; while ((*yyp = *yyformat) != '\0') if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyformat += 2; } else { yyp++; yyformat++; } } return 0; } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, Context *context) #else static void yydestruct (yymsg, yytype, yyvaluep, context) const char *yymsg; int yytype; YYSTYPE *yyvaluep; Context *context; #endif { YYUSE (yyvaluep); YYUSE (context); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { default: break; } } /*----------. | yyparse. | `----------*/ #ifdef YYPARSE_PARAM #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else /* ! YYPARSE_PARAM */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (Context *context) #else int yyparse (context) Context *context; #endif #endif { /* The lookahead symbol. */ int yychar; #if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ /* Suppress an incorrect diagnostic about yylval being uninitialized. */ # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") # define YY_IGNORE_MAYBE_UNINITIALIZED_END \ _Pragma ("GCC diagnostic pop") #else /* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. */ static YYSTYPE yyval_default; # define YY_INITIAL_VALUE(Value) = Value #endif #ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_END #endif #ifndef YY_INITIAL_VALUE # define YY_INITIAL_VALUE(Value) /* Nothing. */ #endif /* The semantic value of the lookahead symbol. */ YYSTYPE yylval YY_INITIAL_VALUE(yyval_default); /* Number of syntax errors so far. */ int yynerrs; int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: `yyss': related to states. `yyvs': related to semantic values. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: { *(context->result) = static_cast<int>((yyvsp[(1) - (1)])); YYACCEPT; } break; case 4: { (yyval) = (yyvsp[(1) - (3)]) || (yyvsp[(3) - (3)]); } break; case 5: { (yyval) = (yyvsp[(1) - (3)]) && (yyvsp[(3) - (3)]); } break; case 6: { (yyval) = (yyvsp[(1) - (3)]) | (yyvsp[(3) - (3)]); } break; case 7: { (yyval) = (yyvsp[(1) - (3)]) ^ (yyvsp[(3) - (3)]); } break; case 8: { (yyval) = (yyvsp[(1) - (3)]) & (yyvsp[(3) - (3)]); } break; case 9: { (yyval) = (yyvsp[(1) - (3)]) != (yyvsp[(3) - (3)]); } break; case 10: { (yyval) = (yyvsp[(1) - (3)]) == (yyvsp[(3) - (3)]); } break; case 11: { (yyval) = (yyvsp[(1) - (3)]) >= (yyvsp[(3) - (3)]); } break; case 12: { (yyval) = (yyvsp[(1) - (3)]) <= (yyvsp[(3) - (3)]); } break; case 13: { (yyval) = (yyvsp[(1) - (3)]) > (yyvsp[(3) - (3)]); } break; case 14: { (yyval) = (yyvsp[(1) - (3)]) < (yyvsp[(3) - (3)]); } break; case 15: { (yyval) = (yyvsp[(1) - (3)]) >> (yyvsp[(3) - (3)]); } break; case 16: { (yyval) = (yyvsp[(1) - (3)]) << (yyvsp[(3) - (3)]); } break; case 17: { (yyval) = (yyvsp[(1) - (3)]) - (yyvsp[(3) - (3)]); } break; case 18: { (yyval) = (yyvsp[(1) - (3)]) + (yyvsp[(3) - (3)]); } break; case 19: { if ((yyvsp[(3) - (3)]) == 0) { std::ostringstream stream; stream << (yyvsp[(1) - (3)]) << " % " << (yyvsp[(3) - (3)]); std::string text = stream.str(); context->diagnostics->report(pp::Diagnostics::DIVISION_BY_ZERO, context->token->location, text.c_str()); YYABORT; } else { (yyval) = (yyvsp[(1) - (3)]) % (yyvsp[(3) - (3)]); } } break; case 20: { if ((yyvsp[(3) - (3)]) == 0) { std::ostringstream stream; stream << (yyvsp[(1) - (3)]) << " / " << (yyvsp[(3) - (3)]); std::string text = stream.str(); context->diagnostics->report(pp::Diagnostics::DIVISION_BY_ZERO, context->token->location, text.c_str()); YYABORT; } else { (yyval) = (yyvsp[(1) - (3)]) / (yyvsp[(3) - (3)]); } } break; case 21: { (yyval) = (yyvsp[(1) - (3)]) * (yyvsp[(3) - (3)]); } break; case 22: { (yyval) = ! (yyvsp[(2) - (2)]); } break; case 23: { (yyval) = ~ (yyvsp[(2) - (2)]); } break; case 24: { (yyval) = - (yyvsp[(2) - (2)]); } break; case 25: { (yyval) = + (yyvsp[(2) - (2)]); } break; case 26: { (yyval) = (yyvsp[(2) - (3)]); } break; default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (context, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (context, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, context); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp, context); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (context, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, context); } /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, context); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); } int yylex(YYSTYPE* lvalp, Context* context) { int type = 0; pp::Token* token = context->token; switch (token->type) { case pp::Token::CONST_INT: { unsigned int val = 0; if (!token->uValue(&val)) { context->diagnostics->report(pp::Diagnostics::INTEGER_OVERFLOW, token->location, token->text); } *lvalp = static_cast<YYSTYPE>(val); type = TOK_CONST_INT; break; } case pp::Token::OP_OR: type = TOK_OP_OR; break; case pp::Token::OP_AND: type = TOK_OP_AND; break; case pp::Token::OP_NE: type = TOK_OP_NE; break; case pp::Token::OP_EQ: type = TOK_OP_EQ; break; case pp::Token::OP_GE: type = TOK_OP_GE; break; case pp::Token::OP_LE: type = TOK_OP_LE; break; case pp::Token::OP_RIGHT: type = TOK_OP_RIGHT; break; case pp::Token::OP_LEFT: type = TOK_OP_LEFT; break; case '|': type = '|'; break; case '^': type = '^'; break; case '&': type = '&'; break; case '>': type = '>'; break; case '<': type = '<'; break; case '-': type = '-'; break; case '+': type = '+'; break; case '%': type = '%'; break; case '/': type = '/'; break; case '*': type = '*'; break; case '!': type = '!'; break; case '~': type = '~'; break; case '(': type = '('; break; case ')': type = ')'; break; default: break; } // Advance to the next token if the current one is valid. if (type != 0) context->lexer->lex(token); return type; } void yyerror(Context* context, const char* reason) { context->diagnostics->report(pp::Diagnostics::INVALID_EXPRESSION, context->token->location, reason); } namespace pp { ExpressionParser::ExpressionParser(Lexer* lexer, Diagnostics* diagnostics) : mLexer(lexer), mDiagnostics(diagnostics) { } bool ExpressionParser::parse(Token* token, int* result) { Context context; context.diagnostics = mDiagnostics; context.lexer = mLexer; context.token = token; context.result = result; int ret = yyparse(&context); switch (ret) { case 0: case 1: break; case 2: mDiagnostics->report(Diagnostics::OUT_OF_MEMORY, token->location, ""); break; default: assert(false); mDiagnostics->report(Diagnostics::INTERNAL_ERROR, token->location, ""); break; } return ret == 0; } } // namespace pp
C++
// // Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/ParseHelper.h" #include <stdarg.h> #include <stdio.h> #include "compiler/glslang.h" #include "compiler/preprocessor/SourceLocation.h" /////////////////////////////////////////////////////////////////////// // // Sub- vector and matrix fields // //////////////////////////////////////////////////////////////////////// // // Look at a '.' field selector string and change it into offsets // for a vector. // bool TParseContext::parseVectorFields(const TString& compString, int vecSize, TVectorFields& fields, const TSourceLoc& line) { fields.num = (int) compString.size(); if (fields.num > 4) { error(line, "illegal vector field selection", compString.c_str()); return false; } enum { exyzw, ergba, estpq } fieldSet[4]; for (int i = 0; i < fields.num; ++i) { switch (compString[i]) { case 'x': fields.offsets[i] = 0; fieldSet[i] = exyzw; break; case 'r': fields.offsets[i] = 0; fieldSet[i] = ergba; break; case 's': fields.offsets[i] = 0; fieldSet[i] = estpq; break; case 'y': fields.offsets[i] = 1; fieldSet[i] = exyzw; break; case 'g': fields.offsets[i] = 1; fieldSet[i] = ergba; break; case 't': fields.offsets[i] = 1; fieldSet[i] = estpq; break; case 'z': fields.offsets[i] = 2; fieldSet[i] = exyzw; break; case 'b': fields.offsets[i] = 2; fieldSet[i] = ergba; break; case 'p': fields.offsets[i] = 2; fieldSet[i] = estpq; break; case 'w': fields.offsets[i] = 3; fieldSet[i] = exyzw; break; case 'a': fields.offsets[i] = 3; fieldSet[i] = ergba; break; case 'q': fields.offsets[i] = 3; fieldSet[i] = estpq; break; default: error(line, "illegal vector field selection", compString.c_str()); return false; } } for (int i = 0; i < fields.num; ++i) { if (fields.offsets[i] >= vecSize) { error(line, "vector field selection out of range", compString.c_str()); return false; } if (i > 0) { if (fieldSet[i] != fieldSet[i-1]) { error(line, "illegal - vector component fields not from the same set", compString.c_str()); return false; } } } return true; } // // Look at a '.' field selector string and change it into offsets // for a matrix. // bool TParseContext::parseMatrixFields(const TString& compString, int matSize, TMatrixFields& fields, const TSourceLoc& line) { fields.wholeRow = false; fields.wholeCol = false; fields.row = -1; fields.col = -1; if (compString.size() != 2) { error(line, "illegal length of matrix field selection", compString.c_str()); return false; } if (compString[0] == '_') { if (compString[1] < '0' || compString[1] > '3') { error(line, "illegal matrix field selection", compString.c_str()); return false; } fields.wholeCol = true; fields.col = compString[1] - '0'; } else if (compString[1] == '_') { if (compString[0] < '0' || compString[0] > '3') { error(line, "illegal matrix field selection", compString.c_str()); return false; } fields.wholeRow = true; fields.row = compString[0] - '0'; } else { if (compString[0] < '0' || compString[0] > '3' || compString[1] < '0' || compString[1] > '3') { error(line, "illegal matrix field selection", compString.c_str()); return false; } fields.row = compString[0] - '0'; fields.col = compString[1] - '0'; } if (fields.row >= matSize || fields.col >= matSize) { error(line, "matrix field selection out of range", compString.c_str()); return false; } return true; } /////////////////////////////////////////////////////////////////////// // // Errors // //////////////////////////////////////////////////////////////////////// // // Track whether errors have occurred. // void TParseContext::recover() { } // // Used by flex/bison to output all syntax and parsing errors. // void TParseContext::error(const TSourceLoc& loc, const char* reason, const char* token, const char* extraInfo) { pp::SourceLocation srcLoc; srcLoc.file = loc.first_file; srcLoc.line = loc.first_line; diagnostics.writeInfo(pp::Diagnostics::ERROR, srcLoc, reason, token, extraInfo); } void TParseContext::warning(const TSourceLoc& loc, const char* reason, const char* token, const char* extraInfo) { pp::SourceLocation srcLoc; srcLoc.file = loc.first_file; srcLoc.line = loc.first_line; diagnostics.writeInfo(pp::Diagnostics::WARNING, srcLoc, reason, token, extraInfo); } void TParseContext::trace(const char* str) { diagnostics.writeDebug(str); } // // Same error message for all places assignments don't work. // void TParseContext::assignError(const TSourceLoc& line, const char* op, TString left, TString right) { std::stringstream extraInfoStream; extraInfoStream << "cannot convert from '" << right << "' to '" << left << "'"; std::string extraInfo = extraInfoStream.str(); error(line, "", op, extraInfo.c_str()); } // // Same error message for all places unary operations don't work. // void TParseContext::unaryOpError(const TSourceLoc& line, const char* op, TString operand) { std::stringstream extraInfoStream; extraInfoStream << "no operation '" << op << "' exists that takes an operand of type " << operand << " (or there is no acceptable conversion)"; std::string extraInfo = extraInfoStream.str(); error(line, " wrong operand type", op, extraInfo.c_str()); } // // Same error message for all binary operations don't work. // void TParseContext::binaryOpError(const TSourceLoc& line, const char* op, TString left, TString right) { std::stringstream extraInfoStream; extraInfoStream << "no operation '" << op << "' exists that takes a left-hand operand of type '" << left << "' and a right operand of type '" << right << "' (or there is no acceptable conversion)"; std::string extraInfo = extraInfoStream.str(); error(line, " wrong operand types ", op, extraInfo.c_str()); } bool TParseContext::precisionErrorCheck(const TSourceLoc& line, TPrecision precision, TBasicType type){ if (!checksPrecisionErrors) return false; switch( type ){ case EbtFloat: if( precision == EbpUndefined ){ error( line, "No precision specified for (float)", "" ); return true; } break; case EbtInt: if( precision == EbpUndefined ){ error( line, "No precision specified (int)", "" ); return true; } break; default: return false; } return false; } // // Both test and if necessary, spit out an error, to see if the node is really // an l-value that can be operated on this way. // // Returns true if the was an error. // bool TParseContext::lValueErrorCheck(const TSourceLoc& line, const char* op, TIntermTyped* node) { TIntermSymbol* symNode = node->getAsSymbolNode(); TIntermBinary* binaryNode = node->getAsBinaryNode(); if (binaryNode) { bool errorReturn; switch(binaryNode->getOp()) { case EOpIndexDirect: case EOpIndexIndirect: case EOpIndexDirectStruct: return lValueErrorCheck(line, op, binaryNode->getLeft()); case EOpVectorSwizzle: errorReturn = lValueErrorCheck(line, op, binaryNode->getLeft()); if (!errorReturn) { int offset[4] = {0,0,0,0}; TIntermTyped* rightNode = binaryNode->getRight(); TIntermAggregate *aggrNode = rightNode->getAsAggregate(); for (TIntermSequence::iterator p = aggrNode->getSequence().begin(); p != aggrNode->getSequence().end(); p++) { int value = (*p)->getAsTyped()->getAsConstantUnion()->getIConst(0); offset[value]++; if (offset[value] > 1) { error(line, " l-value of swizzle cannot have duplicate components", op); return true; } } } return errorReturn; default: break; } error(line, " l-value required", op); return true; } const char* symbol = 0; if (symNode != 0) symbol = symNode->getSymbol().c_str(); const char* message = 0; switch (node->getQualifier()) { case EvqConst: message = "can't modify a const"; break; case EvqConstReadOnly: message = "can't modify a const"; break; case EvqAttribute: message = "can't modify an attribute"; break; case EvqUniform: message = "can't modify a uniform"; break; case EvqVaryingIn: message = "can't modify a varying"; break; case EvqFragCoord: message = "can't modify gl_FragCoord"; break; case EvqFrontFacing: message = "can't modify gl_FrontFacing"; break; case EvqPointCoord: message = "can't modify gl_PointCoord"; break; default: // // Type that can't be written to? // switch (node->getBasicType()) { case EbtSampler2D: case EbtSamplerCube: message = "can't modify a sampler"; break; case EbtVoid: message = "can't modify void"; break; default: break; } } if (message == 0 && binaryNode == 0 && symNode == 0) { error(line, " l-value required", op); return true; } // // Everything else is okay, no error. // if (message == 0) return false; // // If we get here, we have an error and a message. // if (symNode) { std::stringstream extraInfoStream; extraInfoStream << "\"" << symbol << "\" (" << message << ")"; std::string extraInfo = extraInfoStream.str(); error(line, " l-value required", op, extraInfo.c_str()); } else { std::stringstream extraInfoStream; extraInfoStream << "(" << message << ")"; std::string extraInfo = extraInfoStream.str(); error(line, " l-value required", op, extraInfo.c_str()); } return true; } // // Both test, and if necessary spit out an error, to see if the node is really // a constant. // // Returns true if the was an error. // bool TParseContext::constErrorCheck(TIntermTyped* node) { if (node->getQualifier() == EvqConst) return false; error(node->getLine(), "constant expression required", ""); return true; } // // Both test, and if necessary spit out an error, to see if the node is really // an integer. // // Returns true if the was an error. // bool TParseContext::integerErrorCheck(TIntermTyped* node, const char* token) { if (node->getBasicType() == EbtInt && node->getNominalSize() == 1) return false; error(node->getLine(), "integer expression required", token); return true; } // // Both test, and if necessary spit out an error, to see if we are currently // globally scoped. // // Returns true if the was an error. // bool TParseContext::globalErrorCheck(const TSourceLoc& line, bool global, const char* token) { if (global) return false; error(line, "only allowed at global scope", token); return true; } // // For now, keep it simple: if it starts "gl_", it's reserved, independent // of scope. Except, if the symbol table is at the built-in push-level, // which is when we are parsing built-ins. // Also checks for "webgl_" and "_webgl_" reserved identifiers if parsing a // webgl shader. // // Returns true if there was an error. // bool TParseContext::reservedErrorCheck(const TSourceLoc& line, const TString& identifier) { static const char* reservedErrMsg = "reserved built-in name"; if (!symbolTable.atBuiltInLevel()) { if (identifier.compare(0, 3, "gl_") == 0) { error(line, reservedErrMsg, "gl_"); return true; } if (isWebGLBasedSpec(shaderSpec)) { if (identifier.compare(0, 6, "webgl_") == 0) { error(line, reservedErrMsg, "webgl_"); return true; } if (identifier.compare(0, 7, "_webgl_") == 0) { error(line, reservedErrMsg, "_webgl_"); return true; } if (shaderSpec == SH_CSS_SHADERS_SPEC && identifier.compare(0, 4, "css_") == 0) { error(line, reservedErrMsg, "css_"); return true; } } if (identifier.find("__") != TString::npos) { error(line, "identifiers containing two consecutive underscores (__) are reserved as possible future keywords", identifier.c_str()); return true; } } return false; } // // Make sure there is enough data provided to the constructor to build // something of the type of the constructor. Also returns the type of // the constructor. // // Returns true if there was an error in construction. // bool TParseContext::constructorErrorCheck(const TSourceLoc& line, TIntermNode* node, TFunction& function, TOperator op, TType* type) { *type = function.getReturnType(); bool constructingMatrix = false; switch(op) { case EOpConstructMat2: case EOpConstructMat3: case EOpConstructMat4: constructingMatrix = true; break; default: break; } // // Note: It's okay to have too many components available, but not okay to have unused // arguments. 'full' will go to true when enough args have been seen. If we loop // again, there is an extra argument, so 'overfull' will become true. // size_t size = 0; bool constType = true; bool full = false; bool overFull = false; bool matrixInMatrix = false; bool arrayArg = false; for (size_t i = 0; i < function.getParamCount(); ++i) { const TParameter& param = function.getParam(i); size += param.type->getObjectSize(); if (constructingMatrix && param.type->isMatrix()) matrixInMatrix = true; if (full) overFull = true; if (op != EOpConstructStruct && !type->isArray() && size >= type->getObjectSize()) full = true; if (param.type->getQualifier() != EvqConst) constType = false; if (param.type->isArray()) arrayArg = true; } if (constType) type->setQualifier(EvqConst); if (type->isArray() && static_cast<size_t>(type->getArraySize()) != function.getParamCount()) { error(line, "array constructor needs one argument per array element", "constructor"); return true; } if (arrayArg && op != EOpConstructStruct) { error(line, "constructing from a non-dereferenced array", "constructor"); return true; } if (matrixInMatrix && !type->isArray()) { if (function.getParamCount() != 1) { error(line, "constructing matrix from matrix can only take one argument", "constructor"); return true; } } if (overFull) { error(line, "too many arguments", "constructor"); return true; } if (op == EOpConstructStruct && !type->isArray() && int(type->getStruct()->size()) != function.getParamCount()) { error(line, "Number of constructor parameters does not match the number of structure fields", "constructor"); return true; } if (!type->isMatrix() || !matrixInMatrix) { if ((op != EOpConstructStruct && size != 1 && size < type->getObjectSize()) || (op == EOpConstructStruct && size < type->getObjectSize())) { error(line, "not enough data provided for construction", "constructor"); return true; } } TIntermTyped *typed = node ? node->getAsTyped() : 0; if (typed == 0) { error(line, "constructor argument does not have a type", "constructor"); return true; } if (op != EOpConstructStruct && IsSampler(typed->getBasicType())) { error(line, "cannot convert a sampler", "constructor"); return true; } if (typed->getBasicType() == EbtVoid) { error(line, "cannot convert a void", "constructor"); return true; } return false; } // This function checks to see if a void variable has been declared and raise an error message for such a case // // returns true in case of an error // bool TParseContext::voidErrorCheck(const TSourceLoc& line, const TString& identifier, const TPublicType& pubType) { if (pubType.type == EbtVoid) { error(line, "illegal use of type 'void'", identifier.c_str()); return true; } return false; } // This function checks to see if the node (for the expression) contains a scalar boolean expression or not // // returns true in case of an error // bool TParseContext::boolErrorCheck(const TSourceLoc& line, const TIntermTyped* type) { if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector()) { error(line, "boolean expression expected", ""); return true; } return false; } // This function checks to see if the node (for the expression) contains a scalar boolean expression or not // // returns true in case of an error // bool TParseContext::boolErrorCheck(const TSourceLoc& line, const TPublicType& pType) { if (pType.type != EbtBool || pType.array || pType.matrix || (pType.size > 1)) { error(line, "boolean expression expected", ""); return true; } return false; } bool TParseContext::samplerErrorCheck(const TSourceLoc& line, const TPublicType& pType, const char* reason) { if (pType.type == EbtStruct) { if (containsSampler(*pType.userDef)) { error(line, reason, getBasicString(pType.type), "(structure contains a sampler)"); return true; } return false; } else if (IsSampler(pType.type)) { error(line, reason, getBasicString(pType.type)); return true; } return false; } bool TParseContext::structQualifierErrorCheck(const TSourceLoc& line, const TPublicType& pType) { if ((pType.qualifier == EvqVaryingIn || pType.qualifier == EvqVaryingOut || pType.qualifier == EvqAttribute) && pType.type == EbtStruct) { error(line, "cannot be used with a structure", getQualifierString(pType.qualifier)); return true; } if (pType.qualifier != EvqUniform && samplerErrorCheck(line, pType, "samplers must be uniform")) return true; return false; } bool TParseContext::parameterSamplerErrorCheck(const TSourceLoc& line, TQualifier qualifier, const TType& type) { if ((qualifier == EvqOut || qualifier == EvqInOut) && type.getBasicType() != EbtStruct && IsSampler(type.getBasicType())) { error(line, "samplers cannot be output parameters", type.getBasicString()); return true; } return false; } bool TParseContext::containsSampler(TType& type) { if (IsSampler(type.getBasicType())) return true; if (type.getBasicType() == EbtStruct) { TTypeList& structure = *type.getStruct(); for (unsigned int i = 0; i < structure.size(); ++i) { if (containsSampler(*structure[i])) return true; } } return false; } // // Do size checking for an array type's size. // // Returns true if there was an error. // bool TParseContext::arraySizeErrorCheck(const TSourceLoc& line, TIntermTyped* expr, int& size) { TIntermConstantUnion* constant = expr->getAsConstantUnion(); if (constant == 0 || constant->getBasicType() != EbtInt) { error(line, "array size must be a constant integer expression", ""); return true; } size = constant->getIConst(0); if (size <= 0) { error(line, "array size must be a positive integer", ""); size = 1; return true; } return false; } // // See if this qualifier can be an array. // // Returns true if there is an error. // bool TParseContext::arrayQualifierErrorCheck(const TSourceLoc& line, TPublicType type) { if ((type.qualifier == EvqAttribute) || (type.qualifier == EvqConst)) { error(line, "cannot declare arrays of this qualifier", TType(type).getCompleteString().c_str()); return true; } return false; } // // See if this type can be an array. // // Returns true if there is an error. // bool TParseContext::arrayTypeErrorCheck(const TSourceLoc& line, TPublicType type) { // // Can the type be an array? // if (type.array) { error(line, "cannot declare arrays of arrays", TType(type).getCompleteString().c_str()); return true; } return false; } // // Do all the semantic checking for declaring an array, with and // without a size, and make the right changes to the symbol table. // // size == 0 means no specified size. // // Returns true if there was an error. // bool TParseContext::arrayErrorCheck(const TSourceLoc& line, TString& identifier, TPublicType type, TVariable*& variable) { // // Don't check for reserved word use until after we know it's not in the symbol table, // because reserved arrays can be redeclared. // bool builtIn = false; bool sameScope = false; TSymbol* symbol = symbolTable.find(identifier, &builtIn, &sameScope); if (symbol == 0 || !sameScope) { if (reservedErrorCheck(line, identifier)) return true; variable = new TVariable(&identifier, TType(type)); if (type.arraySize) variable->getType().setArraySize(type.arraySize); if (! symbolTable.insert(*variable)) { delete variable; error(line, "INTERNAL ERROR inserting new symbol", identifier.c_str()); return true; } } else { if (! symbol->isVariable()) { error(line, "variable expected", identifier.c_str()); return true; } variable = static_cast<TVariable*>(symbol); if (! variable->getType().isArray()) { error(line, "redeclaring non-array as array", identifier.c_str()); return true; } if (variable->getType().getArraySize() > 0) { error(line, "redeclaration of array with size", identifier.c_str()); return true; } if (! variable->getType().sameElementType(TType(type))) { error(line, "redeclaration of array with a different type", identifier.c_str()); return true; } if (type.arraySize) variable->getType().setArraySize(type.arraySize); } if (voidErrorCheck(line, identifier, type)) return true; return false; } // // Enforce non-initializer type/qualifier rules. // // Returns true if there was an error. // bool TParseContext::nonInitConstErrorCheck(const TSourceLoc& line, TString& identifier, TPublicType& type, bool array) { if (type.qualifier == EvqConst) { // Make the qualifier make sense. type.qualifier = EvqTemporary; if (array) { error(line, "arrays may not be declared constant since they cannot be initialized", identifier.c_str()); } else if (type.isStructureContainingArrays()) { error(line, "structures containing arrays may not be declared constant since they cannot be initialized", identifier.c_str()); } else { error(line, "variables with qualifier 'const' must be initialized", identifier.c_str()); } return true; } return false; } // // Do semantic checking for a variable declaration that has no initializer, // and update the symbol table. // // Returns true if there was an error. // bool TParseContext::nonInitErrorCheck(const TSourceLoc& line, TString& identifier, TPublicType& type, TVariable*& variable) { if (reservedErrorCheck(line, identifier)) recover(); variable = new TVariable(&identifier, TType(type)); if (! symbolTable.insert(*variable)) { error(line, "redefinition", variable->getName().c_str()); delete variable; variable = 0; return true; } if (voidErrorCheck(line, identifier, type)) return true; return false; } bool TParseContext::paramErrorCheck(const TSourceLoc& line, TQualifier qualifier, TQualifier paramQualifier, TType* type) { if (qualifier != EvqConst && qualifier != EvqTemporary) { error(line, "qualifier not allowed on function parameter", getQualifierString(qualifier)); return true; } if (qualifier == EvqConst && paramQualifier != EvqIn) { error(line, "qualifier not allowed with ", getQualifierString(qualifier), getQualifierString(paramQualifier)); return true; } if (qualifier == EvqConst) type->setQualifier(EvqConstReadOnly); else type->setQualifier(paramQualifier); return false; } bool TParseContext::extensionErrorCheck(const TSourceLoc& line, const TString& extension) { const TExtensionBehavior& extBehavior = extensionBehavior(); TExtensionBehavior::const_iterator iter = extBehavior.find(extension.c_str()); if (iter == extBehavior.end()) { error(line, "extension", extension.c_str(), "is not supported"); return true; } // In GLSL ES, an extension's default behavior is "disable". if (iter->second == EBhDisable || iter->second == EBhUndefined) { error(line, "extension", extension.c_str(), "is disabled"); return true; } if (iter->second == EBhWarn) { warning(line, "extension", extension.c_str(), "is being used"); return false; } return false; } bool TParseContext::supportsExtension(const char* extension) { const TExtensionBehavior& extbehavior = extensionBehavior(); TExtensionBehavior::const_iterator iter = extbehavior.find(extension); return (iter != extbehavior.end()); } ///////////////////////////////////////////////////////////////////////////////// // // Non-Errors. // ///////////////////////////////////////////////////////////////////////////////// // // Look up a function name in the symbol table, and make sure it is a function. // // Return the function symbol if found, otherwise 0. // const TFunction* TParseContext::findFunction(const TSourceLoc& line, TFunction* call, bool *builtIn) { // First find by unmangled name to check whether the function name has been // hidden by a variable name or struct typename. const TSymbol* symbol = symbolTable.find(call->getName(), builtIn); if (symbol == 0) { symbol = symbolTable.find(call->getMangledName(), builtIn); } if (symbol == 0) { error(line, "no matching overloaded function found", call->getName().c_str()); return 0; } if (!symbol->isFunction()) { error(line, "function name expected", call->getName().c_str()); return 0; } return static_cast<const TFunction*>(symbol); } bool TParseContext::isVariableBuiltIn(const TVariable* var) { bool builtIn = false; // First find by unmangled name to check whether the function name has been // hidden by a variable name or struct typename. const TSymbol* symbol = symbolTable.find(var->getName(), &builtIn); if (symbol == 0) { symbol = symbolTable.find(var->getMangledName(), &builtIn); } if (symbol == 0) { return false; } if (!symbol->isVariable()) { return false; } return builtIn; } // // Initializers show up in several places in the grammar. Have one set of // code to handle them here. // bool TParseContext::executeInitializer(const TSourceLoc& line, TString& identifier, TPublicType& pType, TIntermTyped* initializer, TIntermNode*& intermNode, TVariable* variable) { TType type = TType(pType); if (variable == 0) { if (reservedErrorCheck(line, identifier)) return true; if (voidErrorCheck(line, identifier, pType)) return true; // // add variable to symbol table // variable = new TVariable(&identifier, type); if (! symbolTable.insert(*variable)) { error(line, "redefinition", variable->getName().c_str()); return true; // don't delete variable, it's used by error recovery, and the pool // pop will take care of the memory } } // // identifier must be of type constant, a global, or a temporary // TQualifier qualifier = variable->getType().getQualifier(); if ((qualifier != EvqTemporary) && (qualifier != EvqGlobal) && (qualifier != EvqConst)) { error(line, " cannot initialize this type of qualifier ", variable->getType().getQualifierString()); return true; } // // test for and propagate constant // if (qualifier == EvqConst) { if (qualifier != initializer->getType().getQualifier()) { std::stringstream extraInfoStream; extraInfoStream << "'" << variable->getType().getCompleteString() << "'"; std::string extraInfo = extraInfoStream.str(); error(line, " assigning non-constant to", "=", extraInfo.c_str()); variable->getType().setQualifier(EvqTemporary); return true; } if (type != initializer->getType()) { error(line, " non-matching types for const initializer ", variable->getType().getQualifierString()); variable->getType().setQualifier(EvqTemporary); return true; } if (initializer->getAsConstantUnion()) { variable->shareConstPointer(initializer->getAsConstantUnion()->getUnionArrayPointer()); } else if (initializer->getAsSymbolNode()) { const TSymbol* symbol = symbolTable.find(initializer->getAsSymbolNode()->getSymbol()); const TVariable* tVar = static_cast<const TVariable*>(symbol); ConstantUnion* constArray = tVar->getConstPointer(); variable->shareConstPointer(constArray); } else { std::stringstream extraInfoStream; extraInfoStream << "'" << variable->getType().getCompleteString() << "'"; std::string extraInfo = extraInfoStream.str(); error(line, " cannot assign to", "=", extraInfo.c_str()); variable->getType().setQualifier(EvqTemporary); return true; } } if (qualifier != EvqConst) { TIntermSymbol* intermSymbol = intermediate.addSymbol(variable->getUniqueId(), variable->getName(), variable->getType(), line); intermNode = intermediate.addAssign(EOpInitialize, intermSymbol, initializer, line); if (intermNode == 0) { assignError(line, "=", intermSymbol->getCompleteString(), initializer->getCompleteString()); return true; } } else intermNode = 0; return false; } bool TParseContext::areAllChildConst(TIntermAggregate* aggrNode) { ASSERT(aggrNode != NULL); if (!aggrNode->isConstructor()) return false; bool allConstant = true; // check if all the child nodes are constants so that they can be inserted into // the parent node TIntermSequence &sequence = aggrNode->getSequence() ; for (TIntermSequence::iterator p = sequence.begin(); p != sequence.end(); ++p) { if (!(*p)->getAsTyped()->getAsConstantUnion()) return false; } return allConstant; } // This function is used to test for the correctness of the parameters passed to various constructor functions // and also convert them to the right datatype if it is allowed and required. // // Returns 0 for an error or the constructed node (aggregate or typed) for no error. // TIntermTyped* TParseContext::addConstructor(TIntermNode* node, const TType* type, TOperator op, TFunction* fnCall, const TSourceLoc& line) { if (node == 0) return 0; TIntermAggregate* aggrNode = node->getAsAggregate(); TTypeList::const_iterator memberTypes; if (op == EOpConstructStruct) memberTypes = type->getStruct()->begin(); TType elementType = *type; if (type->isArray()) elementType.clearArrayness(); bool singleArg; if (aggrNode) { if (aggrNode->getOp() != EOpNull || aggrNode->getSequence().size() == 1) singleArg = true; else singleArg = false; } else singleArg = true; TIntermTyped *newNode; if (singleArg) { // If structure constructor or array constructor is being called // for only one parameter inside the structure, we need to call constructStruct function once. if (type->isArray()) newNode = constructStruct(node, &elementType, 1, node->getLine(), false); else if (op == EOpConstructStruct) newNode = constructStruct(node, *memberTypes, 1, node->getLine(), false); else newNode = constructBuiltIn(type, op, node, node->getLine(), false); if (newNode && newNode->getAsAggregate()) { TIntermTyped* constConstructor = foldConstConstructor(newNode->getAsAggregate(), *type); if (constConstructor) return constConstructor; } return newNode; } // // Handle list of arguments. // TIntermSequence &sequenceVector = aggrNode->getSequence() ; // Stores the information about the parameter to the constructor // if the structure constructor contains more than one parameter, then construct // each parameter int paramCount = 0; // keeps a track of the constructor parameter number being checked // for each parameter to the constructor call, check to see if the right type is passed or convert them // to the right type if possible (and allowed). // for structure constructors, just check if the right type is passed, no conversion is allowed. for (TIntermSequence::iterator p = sequenceVector.begin(); p != sequenceVector.end(); p++, paramCount++) { if (type->isArray()) newNode = constructStruct(*p, &elementType, paramCount+1, node->getLine(), true); else if (op == EOpConstructStruct) newNode = constructStruct(*p, memberTypes[paramCount], paramCount+1, node->getLine(), true); else newNode = constructBuiltIn(type, op, *p, node->getLine(), true); if (newNode) { *p = newNode; } } TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, line); TIntermTyped* constConstructor = foldConstConstructor(constructor->getAsAggregate(), *type); if (constConstructor) return constConstructor; return constructor; } TIntermTyped* TParseContext::foldConstConstructor(TIntermAggregate* aggrNode, const TType& type) { bool canBeFolded = areAllChildConst(aggrNode); aggrNode->setType(type); if (canBeFolded) { bool returnVal = false; ConstantUnion* unionArray = new ConstantUnion[type.getObjectSize()]; if (aggrNode->getSequence().size() == 1) { returnVal = intermediate.parseConstTree(aggrNode->getLine(), aggrNode, unionArray, aggrNode->getOp(), symbolTable, type, true); } else { returnVal = intermediate.parseConstTree(aggrNode->getLine(), aggrNode, unionArray, aggrNode->getOp(), symbolTable, type); } if (returnVal) return 0; return intermediate.addConstantUnion(unionArray, type, aggrNode->getLine()); } return 0; } // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value // for the parameter to the constructor (passed to this function). Essentially, it converts // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a // float, then float is converted to int. // // Returns 0 for an error or the constructed node. // TIntermTyped* TParseContext::constructBuiltIn(const TType* type, TOperator op, TIntermNode* node, const TSourceLoc& line, bool subset) { TIntermTyped* newNode; TOperator basicOp; // // First, convert types as needed. // switch (op) { case EOpConstructVec2: case EOpConstructVec3: case EOpConstructVec4: case EOpConstructMat2: case EOpConstructMat3: case EOpConstructMat4: case EOpConstructFloat: basicOp = EOpConstructFloat; break; case EOpConstructIVec2: case EOpConstructIVec3: case EOpConstructIVec4: case EOpConstructInt: basicOp = EOpConstructInt; break; case EOpConstructBVec2: case EOpConstructBVec3: case EOpConstructBVec4: case EOpConstructBool: basicOp = EOpConstructBool; break; default: error(line, "unsupported construction", ""); recover(); return 0; } newNode = intermediate.addUnaryMath(basicOp, node, node->getLine(), symbolTable); if (newNode == 0) { error(line, "can't convert", "constructor"); return 0; } // // Now, if there still isn't an operation to do the construction, and we need one, add one. // // Otherwise, skip out early. if (subset || (newNode != node && newNode->getType() == *type)) return newNode; // setAggregateOperator will insert a new node for the constructor, as needed. return intermediate.setAggregateOperator(newNode, op, line); } // This function tests for the type of the parameters to the structures constructors. Raises // an error message if the expected type does not match the parameter passed to the constructor. // // Returns 0 for an error or the input node itself if the expected and the given parameter types match. // TIntermTyped* TParseContext::constructStruct(TIntermNode* node, TType* type, int paramCount, const TSourceLoc& line, bool subset) { if (*type == node->getAsTyped()->getType()) { if (subset) return node->getAsTyped(); else return intermediate.setAggregateOperator(node->getAsTyped(), EOpConstructStruct, line); } else { std::stringstream extraInfoStream; extraInfoStream << "cannot convert parameter " << paramCount << " from '" << node->getAsTyped()->getType().getBasicString() << "' to '" << type->getBasicString() << "'"; std::string extraInfo = extraInfoStream.str(); error(line, "", "constructor", extraInfo.c_str()); recover(); } return 0; } // // This function returns the tree representation for the vector field(s) being accessed from contant vector. // If only one component of vector is accessed (v.x or v[0] where v is a contant vector), then a contant node is // returned, else an aggregate node is returned (for v.xy). The input to this function could either be the symbol // node or it could be the intermediate tree representation of accessing fields in a constant structure or column of // a constant matrix. // TIntermTyped* TParseContext::addConstVectorNode(TVectorFields& fields, TIntermTyped* node, const TSourceLoc& line) { TIntermTyped* typedNode; TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion(); ConstantUnion *unionArray; if (tempConstantNode) { unionArray = tempConstantNode->getUnionArrayPointer(); if (!unionArray) { return node; } } else { // The node has to be either a symbol node or an aggregate node or a tempConstant node, else, its an error error(line, "Cannot offset into the vector", "Error"); recover(); return 0; } ConstantUnion* constArray = new ConstantUnion[fields.num]; for (int i = 0; i < fields.num; i++) { if (fields.offsets[i] >= node->getType().getNominalSize()) { std::stringstream extraInfoStream; extraInfoStream << "vector field selection out of range '" << fields.offsets[i] << "'"; std::string extraInfo = extraInfoStream.str(); error(line, "", "[", extraInfo.c_str()); recover(); fields.offsets[i] = 0; } constArray[i] = unionArray[fields.offsets[i]]; } typedNode = intermediate.addConstantUnion(constArray, node->getType(), line); return typedNode; } // // This function returns the column being accessed from a constant matrix. The values are retrieved from // the symbol table and parse-tree is built for a vector (each column of a matrix is a vector). The input // to the function could either be a symbol node (m[0] where m is a constant matrix)that represents a // constant matrix or it could be the tree representation of the constant matrix (s.m1[0] where s is a constant structure) // TIntermTyped* TParseContext::addConstMatrixNode(int index, TIntermTyped* node, const TSourceLoc& line) { TIntermTyped* typedNode; TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion(); if (index >= node->getType().getNominalSize()) { std::stringstream extraInfoStream; extraInfoStream << "matrix field selection out of range '" << index << "'"; std::string extraInfo = extraInfoStream.str(); error(line, "", "[", extraInfo.c_str()); recover(); index = 0; } if (tempConstantNode) { ConstantUnion* unionArray = tempConstantNode->getUnionArrayPointer(); int size = tempConstantNode->getType().getNominalSize(); typedNode = intermediate.addConstantUnion(&unionArray[size*index], tempConstantNode->getType(), line); } else { error(line, "Cannot offset into the matrix", "Error"); recover(); return 0; } return typedNode; } // // This function returns an element of an array accessed from a constant array. The values are retrieved from // the symbol table and parse-tree is built for the type of the element. The input // to the function could either be a symbol node (a[0] where a is a constant array)that represents a // constant array or it could be the tree representation of the constant array (s.a1[0] where s is a constant structure) // TIntermTyped* TParseContext::addConstArrayNode(int index, TIntermTyped* node, const TSourceLoc& line) { TIntermTyped* typedNode; TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion(); TType arrayElementType = node->getType(); arrayElementType.clearArrayness(); if (index >= node->getType().getArraySize()) { std::stringstream extraInfoStream; extraInfoStream << "array field selection out of range '" << index << "'"; std::string extraInfo = extraInfoStream.str(); error(line, "", "[", extraInfo.c_str()); recover(); index = 0; } if (tempConstantNode) { size_t arrayElementSize = arrayElementType.getObjectSize(); ConstantUnion* unionArray = tempConstantNode->getUnionArrayPointer(); typedNode = intermediate.addConstantUnion(&unionArray[arrayElementSize * index], tempConstantNode->getType(), line); } else { error(line, "Cannot offset into the array", "Error"); recover(); return 0; } return typedNode; } // // This function returns the value of a particular field inside a constant structure from the symbol table. // If there is an embedded/nested struct, it appropriately calls addConstStructNested or addConstStructFromAggr // function and returns the parse-tree with the values of the embedded/nested struct. // TIntermTyped* TParseContext::addConstStruct(TString& identifier, TIntermTyped* node, const TSourceLoc& line) { const TTypeList* fields = node->getType().getStruct(); size_t instanceSize = 0; for (size_t index = 0; index < fields->size(); ++index) { if ((*fields)[index]->getFieldName() == identifier) { break; } else { instanceSize += (*fields)[index]->getObjectSize(); } } TIntermTyped* typedNode = 0; TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion(); if (tempConstantNode) { ConstantUnion* constArray = tempConstantNode->getUnionArrayPointer(); typedNode = intermediate.addConstantUnion(constArray+instanceSize, tempConstantNode->getType(), line); // type will be changed in the calling function } else { error(line, "Cannot offset into the structure", "Error"); recover(); return 0; } return typedNode; } bool TParseContext::enterStructDeclaration(const TSourceLoc& line, const TString& identifier) { ++structNestingLevel; // Embedded structure definitions are not supported per GLSL ES spec. // They aren't allowed in GLSL either, but we need to detect this here // so we don't rely on the GLSL compiler to catch it. if (structNestingLevel > 1) { error(line, "", "Embedded struct definitions are not allowed"); return true; } return false; } void TParseContext::exitStructDeclaration() { --structNestingLevel; } namespace { const int kWebGLMaxStructNesting = 4; } // namespace bool TParseContext::structNestingErrorCheck(const TSourceLoc& line, const TType& fieldType) { if (!isWebGLBasedSpec(shaderSpec)) { return false; } if (fieldType.getBasicType() != EbtStruct) { return false; } // We're already inside a structure definition at this point, so add // one to the field's struct nesting. if (1 + fieldType.getDeepestStructNesting() > kWebGLMaxStructNesting) { std::stringstream extraInfoStream; extraInfoStream << "Reference of struct type " << fieldType.getTypeName() << " exceeds maximum struct nesting of " << kWebGLMaxStructNesting; std::string extraInfo = extraInfoStream.str(); error(line, "", "", extraInfo.c_str()); return true; } return false; } // // Parse an array of strings using yyparse. // // Returns 0 for success. // int PaParseStrings(size_t count, const char* const string[], const int length[], TParseContext* context) { if ((count == 0) || (string == NULL)) return 1; if (glslang_initialize(context)) return 1; int error = glslang_scan(count, string, length, context); if (!error) error = glslang_parse(context); glslang_finalize(context); return (error == 0) && (context->numErrors() == 0) ? 0 : 1; }
C++
// // Copyright (c) 2002-2011 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/OutputGLSLBase.h" #include "compiler/debug.h" #include <cfloat> namespace { TString arrayBrackets(const TType& type) { ASSERT(type.isArray()); TInfoSinkBase out; out << "[" << type.getArraySize() << "]"; return TString(out.c_str()); } bool isSingleStatement(TIntermNode* node) { if (const TIntermAggregate* aggregate = node->getAsAggregate()) { return (aggregate->getOp() != EOpFunction) && (aggregate->getOp() != EOpSequence); } else if (const TIntermSelection* selection = node->getAsSelectionNode()) { // Ternary operators are usually part of an assignment operator. // This handles those rare cases in which they are all by themselves. return selection->usesTernaryOperator(); } else if (node->getAsLoopNode()) { return false; } return true; } } // namespace TOutputGLSLBase::TOutputGLSLBase(TInfoSinkBase& objSink, ShArrayIndexClampingStrategy clampingStrategy, ShHashFunction64 hashFunction, NameMap& nameMap, TSymbolTable& symbolTable) : TIntermTraverser(true, true, true), mObjSink(objSink), mDeclaringVariables(false), mClampingStrategy(clampingStrategy), mHashFunction(hashFunction), mNameMap(nameMap), mSymbolTable(symbolTable) { } void TOutputGLSLBase::writeTriplet(Visit visit, const char* preStr, const char* inStr, const char* postStr) { TInfoSinkBase& out = objSink(); if (visit == PreVisit && preStr) { out << preStr; } else if (visit == InVisit && inStr) { out << inStr; } else if (visit == PostVisit && postStr) { out << postStr; } } void TOutputGLSLBase::writeVariableType(const TType& type) { TInfoSinkBase& out = objSink(); TQualifier qualifier = type.getQualifier(); // TODO(alokp): Validate qualifier for variable declarations. if ((qualifier != EvqTemporary) && (qualifier != EvqGlobal)) out << type.getQualifierString() << " "; // Declare the struct if we have not done so already. if ((type.getBasicType() == EbtStruct) && (mDeclaredStructs.find(type.getTypeName()) == mDeclaredStructs.end())) { out << "struct " << hashName(type.getTypeName()) << "{\n"; const TTypeList* structure = type.getStruct(); ASSERT(structure != NULL); for (size_t i = 0; i < structure->size(); ++i) { const TType* fieldType = (*structure)[i]; ASSERT(fieldType != NULL); if (writeVariablePrecision(fieldType->getPrecision())) out << " "; out << getTypeName(*fieldType) << " " << hashName(fieldType->getFieldName()); if (fieldType->isArray()) out << arrayBrackets(*fieldType); out << ";\n"; } out << "}"; mDeclaredStructs.insert(type.getTypeName()); } else { if (writeVariablePrecision(type.getPrecision())) out << " "; out << getTypeName(type); } } void TOutputGLSLBase::writeFunctionParameters(const TIntermSequence& args) { TInfoSinkBase& out = objSink(); for (TIntermSequence::const_iterator iter = args.begin(); iter != args.end(); ++iter) { const TIntermSymbol* arg = (*iter)->getAsSymbolNode(); ASSERT(arg != NULL); const TType& type = arg->getType(); writeVariableType(type); const TString& name = arg->getSymbol(); if (!name.empty()) out << " " << hashName(name); if (type.isArray()) out << arrayBrackets(type); // Put a comma if this is not the last argument. if (iter != args.end() - 1) out << ", "; } } const ConstantUnion* TOutputGLSLBase::writeConstantUnion(const TType& type, const ConstantUnion* pConstUnion) { TInfoSinkBase& out = objSink(); if (type.getBasicType() == EbtStruct) { out << hashName(type.getTypeName()) << "("; const TTypeList* structure = type.getStruct(); ASSERT(structure != NULL); for (size_t i = 0; i < structure->size(); ++i) { const TType* fieldType = (*structure)[i]; ASSERT(fieldType != NULL); pConstUnion = writeConstantUnion(*fieldType, pConstUnion); if (i != structure->size() - 1) out << ", "; } out << ")"; } else { size_t size = type.getObjectSize(); bool writeType = size > 1; if (writeType) out << getTypeName(type) << "("; for (size_t i = 0; i < size; ++i, ++pConstUnion) { switch (pConstUnion->getType()) { case EbtFloat: out << std::min(FLT_MAX, std::max(-FLT_MAX, pConstUnion->getFConst())); break; case EbtInt: out << pConstUnion->getIConst(); break; case EbtBool: out << pConstUnion->getBConst(); break; default: UNREACHABLE(); } if (i != size - 1) out << ", "; } if (writeType) out << ")"; } return pConstUnion; } void TOutputGLSLBase::visitSymbol(TIntermSymbol* node) { TInfoSinkBase& out = objSink(); if (mLoopUnroll.NeedsToReplaceSymbolWithValue(node)) out << mLoopUnroll.GetLoopIndexValue(node); else out << hashVariableName(node->getSymbol()); if (mDeclaringVariables && node->getType().isArray()) out << arrayBrackets(node->getType()); } void TOutputGLSLBase::visitConstantUnion(TIntermConstantUnion* node) { writeConstantUnion(node->getType(), node->getUnionArrayPointer()); } bool TOutputGLSLBase::visitBinary(Visit visit, TIntermBinary* node) { bool visitChildren = true; TInfoSinkBase& out = objSink(); switch (node->getOp()) { case EOpInitialize: if (visit == InVisit) { out << " = "; // RHS of initialize is not being declared. mDeclaringVariables = false; } break; case EOpAssign: writeTriplet(visit, "(", " = ", ")"); break; case EOpAddAssign: writeTriplet(visit, "(", " += ", ")"); break; case EOpSubAssign: writeTriplet(visit, "(", " -= ", ")"); break; case EOpDivAssign: writeTriplet(visit, "(", " /= ", ")"); break; // Notice the fall-through. case EOpMulAssign: case EOpVectorTimesMatrixAssign: case EOpVectorTimesScalarAssign: case EOpMatrixTimesScalarAssign: case EOpMatrixTimesMatrixAssign: writeTriplet(visit, "(", " *= ", ")"); break; case EOpIndexDirect: writeTriplet(visit, NULL, "[", "]"); break; case EOpIndexIndirect: if (node->getAddIndexClamp()) { if (visit == InVisit) { if (mClampingStrategy == SH_CLAMP_WITH_CLAMP_INTRINSIC) { out << "[int(clamp(float("; } else { out << "[webgl_int_clamp("; } } else if (visit == PostVisit) { int maxSize; TIntermTyped *left = node->getLeft(); TType leftType = left->getType(); if (left->isArray()) { // The shader will fail validation if the array length is not > 0. maxSize = leftType.getArraySize() - 1; } else { maxSize = leftType.getNominalSize() - 1; } if (mClampingStrategy == SH_CLAMP_WITH_CLAMP_INTRINSIC) { out << "), 0.0, float(" << maxSize << ")))]"; } else { out << ", 0, " << maxSize << ")]"; } } } else { writeTriplet(visit, NULL, "[", "]"); } break; case EOpIndexDirectStruct: if (visit == InVisit) { out << "."; // TODO(alokp): ASSERT TString fieldName = node->getType().getFieldName(); const TType& structType = node->getLeft()->getType(); if (!mSymbolTable.findBuiltIn(structType.getTypeName())) fieldName = hashName(fieldName); out << fieldName; visitChildren = false; } break; case EOpVectorSwizzle: if (visit == InVisit) { out << "."; TIntermAggregate* rightChild = node->getRight()->getAsAggregate(); TIntermSequence& sequence = rightChild->getSequence(); for (TIntermSequence::iterator sit = sequence.begin(); sit != sequence.end(); ++sit) { TIntermConstantUnion* element = (*sit)->getAsConstantUnion(); ASSERT(element->getBasicType() == EbtInt); ASSERT(element->getNominalSize() == 1); const ConstantUnion& data = element->getUnionArrayPointer()[0]; ASSERT(data.getType() == EbtInt); switch (data.getIConst()) { case 0: out << "x"; break; case 1: out << "y"; break; case 2: out << "z"; break; case 3: out << "w"; break; default: UNREACHABLE(); break; } } visitChildren = false; } break; case EOpAdd: writeTriplet(visit, "(", " + ", ")"); break; case EOpSub: writeTriplet(visit, "(", " - ", ")"); break; case EOpMul: writeTriplet(visit, "(", " * ", ")"); break; case EOpDiv: writeTriplet(visit, "(", " / ", ")"); break; case EOpMod: UNIMPLEMENTED(); break; case EOpEqual: writeTriplet(visit, "(", " == ", ")"); break; case EOpNotEqual: writeTriplet(visit, "(", " != ", ")"); break; case EOpLessThan: writeTriplet(visit, "(", " < ", ")"); break; case EOpGreaterThan: writeTriplet(visit, "(", " > ", ")"); break; case EOpLessThanEqual: writeTriplet(visit, "(", " <= ", ")"); break; case EOpGreaterThanEqual: writeTriplet(visit, "(", " >= ", ")"); break; // Notice the fall-through. case EOpVectorTimesScalar: case EOpVectorTimesMatrix: case EOpMatrixTimesVector: case EOpMatrixTimesScalar: case EOpMatrixTimesMatrix: writeTriplet(visit, "(", " * ", ")"); break; case EOpLogicalOr: writeTriplet(visit, "(", " || ", ")"); break; case EOpLogicalXor: writeTriplet(visit, "(", " ^^ ", ")"); break; case EOpLogicalAnd: writeTriplet(visit, "(", " && ", ")"); break; default: UNREACHABLE(); break; } return visitChildren; } bool TOutputGLSLBase::visitUnary(Visit visit, TIntermUnary* node) { TString preString; TString postString = ")"; switch (node->getOp()) { case EOpNegative: preString = "(-"; break; case EOpVectorLogicalNot: preString = "not("; break; case EOpLogicalNot: preString = "(!"; break; case EOpPostIncrement: preString = "("; postString = "++)"; break; case EOpPostDecrement: preString = "("; postString = "--)"; break; case EOpPreIncrement: preString = "(++"; break; case EOpPreDecrement: preString = "(--"; break; case EOpConvIntToBool: case EOpConvFloatToBool: switch (node->getOperand()->getType().getNominalSize()) { case 1: preString = "bool("; break; case 2: preString = "bvec2("; break; case 3: preString = "bvec3("; break; case 4: preString = "bvec4("; break; default: UNREACHABLE(); } break; case EOpConvBoolToFloat: case EOpConvIntToFloat: switch (node->getOperand()->getType().getNominalSize()) { case 1: preString = "float("; break; case 2: preString = "vec2("; break; case 3: preString = "vec3("; break; case 4: preString = "vec4("; break; default: UNREACHABLE(); } break; case EOpConvFloatToInt: case EOpConvBoolToInt: switch (node->getOperand()->getType().getNominalSize()) { case 1: preString = "int("; break; case 2: preString = "ivec2("; break; case 3: preString = "ivec3("; break; case 4: preString = "ivec4("; break; default: UNREACHABLE(); } break; case EOpRadians: preString = "radians("; break; case EOpDegrees: preString = "degrees("; break; case EOpSin: preString = "sin("; break; case EOpCos: preString = "cos("; break; case EOpTan: preString = "tan("; break; case EOpAsin: preString = "asin("; break; case EOpAcos: preString = "acos("; break; case EOpAtan: preString = "atan("; break; case EOpExp: preString = "exp("; break; case EOpLog: preString = "log("; break; case EOpExp2: preString = "exp2("; break; case EOpLog2: preString = "log2("; break; case EOpSqrt: preString = "sqrt("; break; case EOpInverseSqrt: preString = "inversesqrt("; break; case EOpAbs: preString = "abs("; break; case EOpSign: preString = "sign("; break; case EOpFloor: preString = "floor("; break; case EOpCeil: preString = "ceil("; break; case EOpFract: preString = "fract("; break; case EOpLength: preString = "length("; break; case EOpNormalize: preString = "normalize("; break; case EOpDFdx: preString = "dFdx("; break; case EOpDFdy: preString = "dFdy("; break; case EOpFwidth: preString = "fwidth("; break; case EOpAny: preString = "any("; break; case EOpAll: preString = "all("; break; default: UNREACHABLE(); break; } if (visit == PreVisit && node->getUseEmulatedFunction()) preString = BuiltInFunctionEmulator::GetEmulatedFunctionName(preString); writeTriplet(visit, preString.c_str(), NULL, postString.c_str()); return true; } bool TOutputGLSLBase::visitSelection(Visit visit, TIntermSelection* node) { TInfoSinkBase& out = objSink(); if (node->usesTernaryOperator()) { // Notice two brackets at the beginning and end. The outer ones // encapsulate the whole ternary expression. This preserves the // order of precedence when ternary expressions are used in a // compound expression, i.e., c = 2 * (a < b ? 1 : 2). out << "(("; node->getCondition()->traverse(this); out << ") ? ("; node->getTrueBlock()->traverse(this); out << ") : ("; node->getFalseBlock()->traverse(this); out << "))"; } else { out << "if ("; node->getCondition()->traverse(this); out << ")\n"; incrementDepth(); visitCodeBlock(node->getTrueBlock()); if (node->getFalseBlock()) { out << "else\n"; visitCodeBlock(node->getFalseBlock()); } decrementDepth(); } return false; } bool TOutputGLSLBase::visitAggregate(Visit visit, TIntermAggregate* node) { bool visitChildren = true; TInfoSinkBase& out = objSink(); TString preString; bool delayedWrite = false; switch (node->getOp()) { case EOpSequence: { // Scope the sequences except when at the global scope. if (depth > 0) out << "{\n"; incrementDepth(); const TIntermSequence& sequence = node->getSequence(); for (TIntermSequence::const_iterator iter = sequence.begin(); iter != sequence.end(); ++iter) { TIntermNode* node = *iter; ASSERT(node != NULL); node->traverse(this); if (isSingleStatement(node)) out << ";\n"; } decrementDepth(); // Scope the sequences except when at the global scope. if (depth > 0) out << "}\n"; visitChildren = false; break; } case EOpPrototype: { // Function declaration. ASSERT(visit == PreVisit); writeVariableType(node->getType()); out << " " << hashName(node->getName()); out << "("; writeFunctionParameters(node->getSequence()); out << ")"; visitChildren = false; break; } case EOpFunction: { // Function definition. ASSERT(visit == PreVisit); writeVariableType(node->getType()); out << " " << hashFunctionName(node->getName()); incrementDepth(); // Function definition node contains one or two children nodes // representing function parameters and function body. The latter // is not present in case of empty function bodies. const TIntermSequence& sequence = node->getSequence(); ASSERT((sequence.size() == 1) || (sequence.size() == 2)); TIntermSequence::const_iterator seqIter = sequence.begin(); // Traverse function parameters. TIntermAggregate* params = (*seqIter)->getAsAggregate(); ASSERT(params != NULL); ASSERT(params->getOp() == EOpParameters); params->traverse(this); // Traverse function body. TIntermAggregate* body = ++seqIter != sequence.end() ? (*seqIter)->getAsAggregate() : NULL; visitCodeBlock(body); decrementDepth(); // Fully processed; no need to visit children. visitChildren = false; break; } case EOpFunctionCall: // Function call. if (visit == PreVisit) { out << hashFunctionName(node->getName()) << "("; } else if (visit == InVisit) { out << ", "; } else { out << ")"; } break; case EOpParameters: { // Function parameters. ASSERT(visit == PreVisit); out << "("; writeFunctionParameters(node->getSequence()); out << ")"; visitChildren = false; break; } case EOpDeclaration: { // Variable declaration. if (visit == PreVisit) { const TIntermSequence& sequence = node->getSequence(); const TIntermTyped* variable = sequence.front()->getAsTyped(); writeVariableType(variable->getType()); out << " "; mDeclaringVariables = true; } else if (visit == InVisit) { out << ", "; mDeclaringVariables = true; } else { mDeclaringVariables = false; } break; } case EOpConstructFloat: writeTriplet(visit, "float(", NULL, ")"); break; case EOpConstructVec2: writeTriplet(visit, "vec2(", ", ", ")"); break; case EOpConstructVec3: writeTriplet(visit, "vec3(", ", ", ")"); break; case EOpConstructVec4: writeTriplet(visit, "vec4(", ", ", ")"); break; case EOpConstructBool: writeTriplet(visit, "bool(", NULL, ")"); break; case EOpConstructBVec2: writeTriplet(visit, "bvec2(", ", ", ")"); break; case EOpConstructBVec3: writeTriplet(visit, "bvec3(", ", ", ")"); break; case EOpConstructBVec4: writeTriplet(visit, "bvec4(", ", ", ")"); break; case EOpConstructInt: writeTriplet(visit, "int(", NULL, ")"); break; case EOpConstructIVec2: writeTriplet(visit, "ivec2(", ", ", ")"); break; case EOpConstructIVec3: writeTriplet(visit, "ivec3(", ", ", ")"); break; case EOpConstructIVec4: writeTriplet(visit, "ivec4(", ", ", ")"); break; case EOpConstructMat2: writeTriplet(visit, "mat2(", ", ", ")"); break; case EOpConstructMat3: writeTriplet(visit, "mat3(", ", ", ")"); break; case EOpConstructMat4: writeTriplet(visit, "mat4(", ", ", ")"); break; case EOpConstructStruct: if (visit == PreVisit) { const TType& type = node->getType(); ASSERT(type.getBasicType() == EbtStruct); out << hashName(type.getTypeName()) << "("; } else if (visit == InVisit) { out << ", "; } else { out << ")"; } break; case EOpLessThan: preString = "lessThan("; delayedWrite = true; break; case EOpGreaterThan: preString = "greaterThan("; delayedWrite = true; break; case EOpLessThanEqual: preString = "lessThanEqual("; delayedWrite = true; break; case EOpGreaterThanEqual: preString = "greaterThanEqual("; delayedWrite = true; break; case EOpVectorEqual: preString = "equal("; delayedWrite = true; break; case EOpVectorNotEqual: preString = "notEqual("; delayedWrite = true; break; case EOpComma: writeTriplet(visit, NULL, ", ", NULL); break; case EOpMod: preString = "mod("; delayedWrite = true; break; case EOpPow: preString = "pow("; delayedWrite = true; break; case EOpAtan: preString = "atan("; delayedWrite = true; break; case EOpMin: preString = "min("; delayedWrite = true; break; case EOpMax: preString = "max("; delayedWrite = true; break; case EOpClamp: preString = "clamp("; delayedWrite = true; break; case EOpMix: preString = "mix("; delayedWrite = true; break; case EOpStep: preString = "step("; delayedWrite = true; break; case EOpSmoothStep: preString = "smoothstep("; delayedWrite = true; break; case EOpDistance: preString = "distance("; delayedWrite = true; break; case EOpDot: preString = "dot("; delayedWrite = true; break; case EOpCross: preString = "cross("; delayedWrite = true; break; case EOpFaceForward: preString = "faceforward("; delayedWrite = true; break; case EOpReflect: preString = "reflect("; delayedWrite = true; break; case EOpRefract: preString = "refract("; delayedWrite = true; break; case EOpMul: preString = "matrixCompMult("; delayedWrite = true; break; default: UNREACHABLE(); break; } if (delayedWrite && visit == PreVisit && node->getUseEmulatedFunction()) preString = BuiltInFunctionEmulator::GetEmulatedFunctionName(preString); if (delayedWrite) writeTriplet(visit, preString.c_str(), ", ", ")"); return visitChildren; } bool TOutputGLSLBase::visitLoop(Visit visit, TIntermLoop* node) { TInfoSinkBase& out = objSink(); incrementDepth(); // Loop header. TLoopType loopType = node->getType(); if (loopType == ELoopFor) // for loop { if (!node->getUnrollFlag()) { out << "for ("; if (node->getInit()) node->getInit()->traverse(this); out << "; "; if (node->getCondition()) node->getCondition()->traverse(this); out << "; "; if (node->getExpression()) node->getExpression()->traverse(this); out << ")\n"; } } else if (loopType == ELoopWhile) // while loop { out << "while ("; ASSERT(node->getCondition() != NULL); node->getCondition()->traverse(this); out << ")\n"; } else // do-while loop { ASSERT(loopType == ELoopDoWhile); out << "do\n"; } // Loop body. if (node->getUnrollFlag()) { TLoopIndexInfo indexInfo; mLoopUnroll.FillLoopIndexInfo(node, indexInfo); mLoopUnroll.Push(indexInfo); while (mLoopUnroll.SatisfiesLoopCondition()) { visitCodeBlock(node->getBody()); mLoopUnroll.Step(); } mLoopUnroll.Pop(); } else { visitCodeBlock(node->getBody()); } // Loop footer. if (loopType == ELoopDoWhile) // do-while loop { out << "while ("; ASSERT(node->getCondition() != NULL); node->getCondition()->traverse(this); out << ");\n"; } decrementDepth(); // No need to visit children. They have been already processed in // this function. return false; } bool TOutputGLSLBase::visitBranch(Visit visit, TIntermBranch* node) { switch (node->getFlowOp()) { case EOpKill: writeTriplet(visit, "discard", NULL, NULL); break; case EOpBreak: writeTriplet(visit, "break", NULL, NULL); break; case EOpContinue: writeTriplet(visit, "continue", NULL, NULL); break; case EOpReturn: writeTriplet(visit, "return ", NULL, NULL); break; default: UNREACHABLE(); break; } return true; } void TOutputGLSLBase::visitCodeBlock(TIntermNode* node) { TInfoSinkBase &out = objSink(); if (node != NULL) { node->traverse(this); // Single statements not part of a sequence need to be terminated // with semi-colon. if (isSingleStatement(node)) out << ";\n"; } else { out << "{\n}\n"; // Empty code block. } } TString TOutputGLSLBase::getTypeName(const TType& type) { TInfoSinkBase out; if (type.isMatrix()) { out << "mat"; out << type.getNominalSize(); } else if (type.isVector()) { switch (type.getBasicType()) { case EbtFloat: out << "vec"; break; case EbtInt: out << "ivec"; break; case EbtBool: out << "bvec"; break; default: UNREACHABLE(); break; } out << type.getNominalSize(); } else { if (type.getBasicType() == EbtStruct) out << hashName(type.getTypeName()); else out << type.getBasicString(); } return TString(out.c_str()); } TString TOutputGLSLBase::hashName(const TString& name) { if (mHashFunction == NULL || name.empty()) return name; NameMap::const_iterator it = mNameMap.find(name.c_str()); if (it != mNameMap.end()) return it->second.c_str(); TString hashedName = TIntermTraverser::hash(name, mHashFunction); mNameMap[name.c_str()] = hashedName.c_str(); return hashedName; } TString TOutputGLSLBase::hashVariableName(const TString& name) { if (mSymbolTable.findBuiltIn(name) != NULL) return name; return hashName(name); } TString TOutputGLSLBase::hashFunctionName(const TString& mangled_name) { TString name = TFunction::unmangleName(mangled_name); if (mSymbolTable.findBuiltIn(mangled_name) != NULL || name == "main") return name; return hashName(name); }
C++
// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/VariableInfo.h" static TString arrayBrackets(int index) { TStringStream stream; stream << "[" << index << "]"; return stream.str(); } // Returns the data type for an attribute or uniform. static ShDataType getVariableDataType(const TType& type) { switch (type.getBasicType()) { case EbtFloat: if (type.isMatrix()) { switch (type.getNominalSize()) { case 2: return SH_FLOAT_MAT2; case 3: return SH_FLOAT_MAT3; case 4: return SH_FLOAT_MAT4; default: UNREACHABLE(); } } else if (type.isVector()) { switch (type.getNominalSize()) { case 2: return SH_FLOAT_VEC2; case 3: return SH_FLOAT_VEC3; case 4: return SH_FLOAT_VEC4; default: UNREACHABLE(); } } else { return SH_FLOAT; } case EbtInt: if (type.isMatrix()) { UNREACHABLE(); } else if (type.isVector()) { switch (type.getNominalSize()) { case 2: return SH_INT_VEC2; case 3: return SH_INT_VEC3; case 4: return SH_INT_VEC4; default: UNREACHABLE(); } } else { return SH_INT; } case EbtBool: if (type.isMatrix()) { UNREACHABLE(); } else if (type.isVector()) { switch (type.getNominalSize()) { case 2: return SH_BOOL_VEC2; case 3: return SH_BOOL_VEC3; case 4: return SH_BOOL_VEC4; default: UNREACHABLE(); } } else { return SH_BOOL; } case EbtSampler2D: return SH_SAMPLER_2D; case EbtSamplerCube: return SH_SAMPLER_CUBE; case EbtSamplerExternalOES: return SH_SAMPLER_EXTERNAL_OES; case EbtSampler2DRect: return SH_SAMPLER_2D_RECT_ARB; default: UNREACHABLE(); } return SH_NONE; } static void getBuiltInVariableInfo(const TType& type, const TString& name, const TString& mappedName, TVariableInfoList& infoList); static void getUserDefinedVariableInfo(const TType& type, const TString& name, const TString& mappedName, TVariableInfoList& infoList, ShHashFunction64 hashFunction); // Returns info for an attribute or uniform. static void getVariableInfo(const TType& type, const TString& name, const TString& mappedName, TVariableInfoList& infoList, ShHashFunction64 hashFunction) { if (type.getBasicType() == EbtStruct) { if (type.isArray()) { for (int i = 0; i < type.getArraySize(); ++i) { TString lname = name + arrayBrackets(i); TString lmappedName = mappedName + arrayBrackets(i); getUserDefinedVariableInfo(type, lname, lmappedName, infoList, hashFunction); } } else { getUserDefinedVariableInfo(type, name, mappedName, infoList, hashFunction); } } else { getBuiltInVariableInfo(type, name, mappedName, infoList); } } void getBuiltInVariableInfo(const TType& type, const TString& name, const TString& mappedName, TVariableInfoList& infoList) { ASSERT(type.getBasicType() != EbtStruct); TVariableInfo varInfo; if (type.isArray()) { varInfo.name = (name + "[0]").c_str(); varInfo.mappedName = (mappedName + "[0]").c_str(); varInfo.size = type.getArraySize(); } else { varInfo.name = name.c_str(); varInfo.mappedName = mappedName.c_str(); varInfo.size = 1; } varInfo.type = getVariableDataType(type); infoList.push_back(varInfo); } void getUserDefinedVariableInfo(const TType& type, const TString& name, const TString& mappedName, TVariableInfoList& infoList, ShHashFunction64 hashFunction) { ASSERT(type.getBasicType() == EbtStruct); const TTypeList* structure = type.getStruct(); for (size_t i = 0; i < structure->size(); ++i) { const TType* fieldType = (*structure)[i]; getVariableInfo(*fieldType, name + "." + fieldType->getFieldName(), mappedName + "." + TIntermTraverser::hash(fieldType->getFieldName(), hashFunction), infoList, hashFunction); } } TVariableInfo::TVariableInfo() { } TVariableInfo::TVariableInfo(ShDataType type, int size) : type(type), size(size) { } CollectAttribsUniforms::CollectAttribsUniforms(TVariableInfoList& attribs, TVariableInfoList& uniforms, ShHashFunction64 hashFunction) : mAttribs(attribs), mUniforms(uniforms), mHashFunction(hashFunction) { } // We are only interested in attribute and uniform variable declaration. void CollectAttribsUniforms::visitSymbol(TIntermSymbol*) { } void CollectAttribsUniforms::visitConstantUnion(TIntermConstantUnion*) { } bool CollectAttribsUniforms::visitBinary(Visit, TIntermBinary*) { return false; } bool CollectAttribsUniforms::visitUnary(Visit, TIntermUnary*) { return false; } bool CollectAttribsUniforms::visitSelection(Visit, TIntermSelection*) { return false; } bool CollectAttribsUniforms::visitAggregate(Visit, TIntermAggregate* node) { bool visitChildren = false; switch (node->getOp()) { case EOpSequence: // We need to visit sequence children to get to variable declarations. visitChildren = true; break; case EOpDeclaration: { const TIntermSequence& sequence = node->getSequence(); TQualifier qualifier = sequence.front()->getAsTyped()->getQualifier(); if (qualifier == EvqAttribute || qualifier == EvqUniform) { TVariableInfoList& infoList = qualifier == EvqAttribute ? mAttribs : mUniforms; for (TIntermSequence::const_iterator i = sequence.begin(); i != sequence.end(); ++i) { const TIntermSymbol* variable = (*i)->getAsSymbolNode(); // The only case in which the sequence will not contain a // TIntermSymbol node is initialization. It will contain a // TInterBinary node in that case. Since attributes and unifroms // cannot be initialized in a shader, we must have only // TIntermSymbol nodes in the sequence. ASSERT(variable != NULL); TString processedSymbol; if (mHashFunction == NULL) processedSymbol = variable->getSymbol(); else processedSymbol = TIntermTraverser::hash(variable->getOriginalSymbol(), mHashFunction); getVariableInfo(variable->getType(), variable->getOriginalSymbol(), processedSymbol, infoList, mHashFunction); } } break; } default: break; } return visitChildren; } bool CollectAttribsUniforms::visitLoop(Visit, TIntermLoop*) { return false; } bool CollectAttribsUniforms::visitBranch(Visit, TIntermBranch*) { return false; }
C++
// // Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef _CONSTANT_UNION_INCLUDED_ #define _CONSTANT_UNION_INCLUDED_ #include <assert.h> class ConstantUnion { public: ConstantUnion() { iConst = 0; type = EbtVoid; } POOL_ALLOCATOR_NEW_DELETE(GlobalPoolAllocator) void setIConst(int i) {iConst = i; type = EbtInt; } void setFConst(float f) {fConst = f; type = EbtFloat; } void setBConst(bool b) {bConst = b; type = EbtBool; } int getIConst() { return iConst; } float getFConst() { return fConst; } bool getBConst() { return bConst; } int getIConst() const { return iConst; } float getFConst() const { return fConst; } bool getBConst() const { return bConst; } bool operator==(const int i) const { return i == iConst; } bool operator==(const float f) const { return f == fConst; } bool operator==(const bool b) const { return b == bConst; } bool operator==(const ConstantUnion& constant) const { if (constant.type != type) return false; switch (type) { case EbtInt: return constant.iConst == iConst; case EbtFloat: return constant.fConst == fConst; case EbtBool: return constant.bConst == bConst; default: return false; } } bool operator!=(const int i) const { return !operator==(i); } bool operator!=(const float f) const { return !operator==(f); } bool operator!=(const bool b) const { return !operator==(b); } bool operator!=(const ConstantUnion& constant) const { return !operator==(constant); } bool operator>(const ConstantUnion& constant) const { assert(type == constant.type); switch (type) { case EbtInt: return iConst > constant.iConst; case EbtFloat: return fConst > constant.fConst; default: return false; // Invalid operation, handled at semantic analysis } } bool operator<(const ConstantUnion& constant) const { assert(type == constant.type); switch (type) { case EbtInt: return iConst < constant.iConst; case EbtFloat: return fConst < constant.fConst; default: return false; // Invalid operation, handled at semantic analysis } } ConstantUnion operator+(const ConstantUnion& constant) const { ConstantUnion returnValue; assert(type == constant.type); switch (type) { case EbtInt: returnValue.setIConst(iConst + constant.iConst); break; case EbtFloat: returnValue.setFConst(fConst + constant.fConst); break; default: assert(false && "Default missing"); } return returnValue; } ConstantUnion operator-(const ConstantUnion& constant) const { ConstantUnion returnValue; assert(type == constant.type); switch (type) { case EbtInt: returnValue.setIConst(iConst - constant.iConst); break; case EbtFloat: returnValue.setFConst(fConst - constant.fConst); break; default: assert(false && "Default missing"); } return returnValue; } ConstantUnion operator*(const ConstantUnion& constant) const { ConstantUnion returnValue; assert(type == constant.type); switch (type) { case EbtInt: returnValue.setIConst(iConst * constant.iConst); break; case EbtFloat: returnValue.setFConst(fConst * constant.fConst); break; default: assert(false && "Default missing"); } return returnValue; } ConstantUnion operator%(const ConstantUnion& constant) const { ConstantUnion returnValue; assert(type == constant.type); switch (type) { case EbtInt: returnValue.setIConst(iConst % constant.iConst); break; default: assert(false && "Default missing"); } return returnValue; } ConstantUnion operator>>(const ConstantUnion& constant) const { ConstantUnion returnValue; assert(type == constant.type); switch (type) { case EbtInt: returnValue.setIConst(iConst >> constant.iConst); break; default: assert(false && "Default missing"); } return returnValue; } ConstantUnion operator<<(const ConstantUnion& constant) const { ConstantUnion returnValue; assert(type == constant.type); switch (type) { case EbtInt: returnValue.setIConst(iConst << constant.iConst); break; default: assert(false && "Default missing"); } return returnValue; } ConstantUnion operator&(const ConstantUnion& constant) const { ConstantUnion returnValue; assert(type == constant.type); switch (type) { case EbtInt: returnValue.setIConst(iConst & constant.iConst); break; default: assert(false && "Default missing"); } return returnValue; } ConstantUnion operator|(const ConstantUnion& constant) const { ConstantUnion returnValue; assert(type == constant.type); switch (type) { case EbtInt: returnValue.setIConst(iConst | constant.iConst); break; default: assert(false && "Default missing"); } return returnValue; } ConstantUnion operator^(const ConstantUnion& constant) const { ConstantUnion returnValue; assert(type == constant.type); switch (type) { case EbtInt: returnValue.setIConst(iConst ^ constant.iConst); break; default: assert(false && "Default missing"); } return returnValue; } ConstantUnion operator&&(const ConstantUnion& constant) const { ConstantUnion returnValue; assert(type == constant.type); switch (type) { case EbtBool: returnValue.setBConst(bConst && constant.bConst); break; default: assert(false && "Default missing"); } return returnValue; } ConstantUnion operator||(const ConstantUnion& constant) const { ConstantUnion returnValue; assert(type == constant.type); switch (type) { case EbtBool: returnValue.setBConst(bConst || constant.bConst); break; default: assert(false && "Default missing"); } return returnValue; } TBasicType getType() const { return type; } private: union { int iConst; // used for ivec, scalar ints bool bConst; // used for bvec, scalar bools float fConst; // used for vec, mat, scalar floats } ; TBasicType type; }; #endif // _CONSTANT_UNION_INCLUDED_
C++
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/InitializeParseContext.h" #include "compiler/osinclude.h" OS_TLSIndex GlobalParseContextIndex = OS_INVALID_TLS_INDEX; bool InitializeParseContextIndex() { if (GlobalParseContextIndex != OS_INVALID_TLS_INDEX) { assert(0 && "InitializeParseContextIndex(): Parse Context already initalized"); return false; } // // Allocate a TLS index. // GlobalParseContextIndex = OS_AllocTLSIndex(); if (GlobalParseContextIndex == OS_INVALID_TLS_INDEX) { assert(0 && "InitializeParseContextIndex(): Parse Context already initalized"); return false; } return true; } bool FreeParseContextIndex() { OS_TLSIndex tlsiIndex = GlobalParseContextIndex; if (GlobalParseContextIndex == OS_INVALID_TLS_INDEX) { assert(0 && "FreeParseContextIndex(): Parse Context index not initalized"); return false; } GlobalParseContextIndex = OS_INVALID_TLS_INDEX; return OS_FreeTLSIndex(tlsiIndex); } bool InitializeGlobalParseContext() { if (GlobalParseContextIndex == OS_INVALID_TLS_INDEX) { assert(0 && "InitializeGlobalParseContext(): Parse Context index not initalized"); return false; } TThreadParseContext *lpParseContext = static_cast<TThreadParseContext *>(OS_GetTLSValue(GlobalParseContextIndex)); if (lpParseContext != 0) { assert(0 && "InitializeParseContextIndex(): Parse Context already initalized"); return false; } TThreadParseContext *lpThreadData = new TThreadParseContext(); if (lpThreadData == 0) { assert(0 && "InitializeGlobalParseContext(): Unable to create thread parse context"); return false; } lpThreadData->lpGlobalParseContext = 0; OS_SetTLSValue(GlobalParseContextIndex, lpThreadData); return true; } bool FreeParseContext() { if (GlobalParseContextIndex == OS_INVALID_TLS_INDEX) { assert(0 && "FreeParseContext(): Parse Context index not initalized"); return false; } TThreadParseContext *lpParseContext = static_cast<TThreadParseContext *>(OS_GetTLSValue(GlobalParseContextIndex)); if (lpParseContext) delete lpParseContext; return true; } TParseContextPointer& GetGlobalParseContext() { // // Minimal error checking for speed // TThreadParseContext *lpParseContext = static_cast<TThreadParseContext *>(OS_GetTLSValue(GlobalParseContextIndex)); return lpParseContext->lpGlobalParseContext; }
C++
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/Diagnostics.h" #include "compiler/debug.h" #include "compiler/InfoSink.h" #include "compiler/preprocessor/SourceLocation.h" TDiagnostics::TDiagnostics(TInfoSink& infoSink) : mInfoSink(infoSink), mNumErrors(0), mNumWarnings(0) { } TDiagnostics::~TDiagnostics() { } void TDiagnostics::writeInfo(Severity severity, const pp::SourceLocation& loc, const std::string& reason, const std::string& token, const std::string& extra) { TPrefixType prefix = EPrefixNone; switch (severity) { case ERROR: ++mNumErrors; prefix = EPrefixError; break; case WARNING: ++mNumWarnings; prefix = EPrefixWarning; break; default: UNREACHABLE(); break; } TInfoSinkBase& sink = mInfoSink.info; /* VC++ format: file(linenum) : error #: 'token' : extrainfo */ sink.prefix(prefix); sink.location(loc.file, loc.line); sink << "'" << token << "' : " << reason << " " << extra << "\n"; } void TDiagnostics::writeDebug(const std::string& str) { mInfoSink.debug << str; } void TDiagnostics::print(ID id, const pp::SourceLocation& loc, const std::string& text) { writeInfo(severity(id), loc, message(id), text, ""); }
C++
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_DIRECTIVE_HANDLER_H_ #define COMPILER_DIRECTIVE_HANDLER_H_ #include "compiler/ExtensionBehavior.h" #include "compiler/Pragma.h" #include "compiler/preprocessor/DirectiveHandlerBase.h" class TDiagnostics; class TDirectiveHandler : public pp::DirectiveHandler { public: TDirectiveHandler(TExtensionBehavior& extBehavior, TDiagnostics& diagnostics); virtual ~TDirectiveHandler(); const TPragma& pragma() const { return mPragma; } const TExtensionBehavior& extensionBehavior() const { return mExtensionBehavior; } virtual void handleError(const pp::SourceLocation& loc, const std::string& msg); virtual void handlePragma(const pp::SourceLocation& loc, const std::string& name, const std::string& value); virtual void handleExtension(const pp::SourceLocation& loc, const std::string& name, const std::string& behavior); virtual void handleVersion(const pp::SourceLocation& loc, int version); private: TPragma mPragma; TExtensionBehavior& mExtensionBehavior; TDiagnostics& mDiagnostics; }; #endif // COMPILER_DIRECTIVE_HANDLER_H_
C++
// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/osinclude.h" // // This file contains contains the window's specific functions // #if !defined(ANGLE_OS_WIN) #error Trying to build a windows specific file in a non windows build. #endif // // Thread Local Storage Operations // OS_TLSIndex OS_AllocTLSIndex() { DWORD dwIndex = TlsAlloc(); if (dwIndex == TLS_OUT_OF_INDEXES) { assert(0 && "OS_AllocTLSIndex(): Unable to allocate Thread Local Storage"); return OS_INVALID_TLS_INDEX; } return dwIndex; } bool OS_SetTLSValue(OS_TLSIndex nIndex, void *lpvValue) { if (nIndex == OS_INVALID_TLS_INDEX) { assert(0 && "OS_SetTLSValue(): Invalid TLS Index"); return false; } if (TlsSetValue(nIndex, lpvValue)) return true; else return false; } bool OS_FreeTLSIndex(OS_TLSIndex nIndex) { if (nIndex == OS_INVALID_TLS_INDEX) { assert(0 && "OS_SetTLSValue(): Invalid TLS Index"); return false; } if (TlsFree(nIndex)) return true; else return false; }
C++
// // Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // UnfoldShortCircuit is an AST traverser to output short-circuiting operators as if-else statements. // The results are assigned to s# temporaries, which are used by the main translator instead of // the original expression. // #include "compiler/UnfoldShortCircuit.h" #include "compiler/InfoSink.h" #include "compiler/OutputHLSL.h" namespace sh { UnfoldShortCircuit::UnfoldShortCircuit(TParseContext &context, OutputHLSL *outputHLSL) : mContext(context), mOutputHLSL(outputHLSL) { mTemporaryIndex = 0; } void UnfoldShortCircuit::traverse(TIntermNode *node) { int rewindIndex = mTemporaryIndex; node->traverse(this); mTemporaryIndex = rewindIndex; } bool UnfoldShortCircuit::visitBinary(Visit visit, TIntermBinary *node) { TInfoSinkBase &out = mOutputHLSL->getBodyStream(); switch (node->getOp()) { case EOpLogicalOr: // "x || y" is equivalent to "x ? true : y", which unfolds to "bool s; if(x) s = true; else s = y;", // and then further simplifies down to "bool s = x; if(!s) s = y;". { int i = mTemporaryIndex; out << "bool s" << i << ";\n"; out << "{\n"; mTemporaryIndex = i + 1; node->getLeft()->traverse(this); out << "s" << i << " = "; mTemporaryIndex = i + 1; node->getLeft()->traverse(mOutputHLSL); out << ";\n"; out << "if(!s" << i << ")\n" "{\n"; mTemporaryIndex = i + 1; node->getRight()->traverse(this); out << " s" << i << " = "; mTemporaryIndex = i + 1; node->getRight()->traverse(mOutputHLSL); out << ";\n" "}\n"; out << "}\n"; mTemporaryIndex = i + 1; } return false; case EOpLogicalAnd: // "x && y" is equivalent to "x ? y : false", which unfolds to "bool s; if(x) s = y; else s = false;", // and then further simplifies down to "bool s = x; if(s) s = y;". { int i = mTemporaryIndex; out << "bool s" << i << ";\n"; out << "{\n"; mTemporaryIndex = i + 1; node->getLeft()->traverse(this); out << "s" << i << " = "; mTemporaryIndex = i + 1; node->getLeft()->traverse(mOutputHLSL); out << ";\n"; out << "if(s" << i << ")\n" "{\n"; mTemporaryIndex = i + 1; node->getRight()->traverse(this); out << " s" << i << " = "; mTemporaryIndex = i + 1; node->getRight()->traverse(mOutputHLSL); out << ";\n" "}\n"; out << "}\n"; mTemporaryIndex = i + 1; } return false; default: return true; } } bool UnfoldShortCircuit::visitSelection(Visit visit, TIntermSelection *node) { TInfoSinkBase &out = mOutputHLSL->getBodyStream(); // Unfold "b ? x : y" into "type s; if(b) s = x; else s = y;" if (node->usesTernaryOperator()) { int i = mTemporaryIndex; out << mOutputHLSL->typeString(node->getType()) << " s" << i << ";\n"; out << "{\n"; mTemporaryIndex = i + 1; node->getCondition()->traverse(this); out << "if("; mTemporaryIndex = i + 1; node->getCondition()->traverse(mOutputHLSL); out << ")\n" "{\n"; mTemporaryIndex = i + 1; node->getTrueBlock()->traverse(this); out << " s" << i << " = "; mTemporaryIndex = i + 1; node->getTrueBlock()->traverse(mOutputHLSL); out << ";\n" "}\n" "else\n" "{\n"; mTemporaryIndex = i + 1; node->getFalseBlock()->traverse(this); out << " s" << i << " = "; mTemporaryIndex = i + 1; node->getFalseBlock()->traverse(mOutputHLSL); out << ";\n" "}\n"; out << "}\n"; mTemporaryIndex = i + 1; } return false; } bool UnfoldShortCircuit::visitLoop(Visit visit, TIntermLoop *node) { int rewindIndex = mTemporaryIndex; if (node->getInit()) { node->getInit()->traverse(this); } if (node->getCondition()) { node->getCondition()->traverse(this); } if (node->getExpression()) { node->getExpression()->traverse(this); } mTemporaryIndex = rewindIndex; return false; } int UnfoldShortCircuit::getNextTemporaryIndex() { return mTemporaryIndex++; } }
C++
// // Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/VariablePacker.h" #include <algorithm> #include "compiler/ShHandle.h" namespace { int GetSortOrder(ShDataType type) { switch (type) { case SH_FLOAT_MAT4: return 0; case SH_FLOAT_MAT2: return 1; case SH_FLOAT_VEC4: case SH_INT_VEC4: case SH_BOOL_VEC4: return 2; case SH_FLOAT_MAT3: return 3; case SH_FLOAT_VEC3: case SH_INT_VEC3: case SH_BOOL_VEC3: return 4; case SH_FLOAT_VEC2: case SH_INT_VEC2: case SH_BOOL_VEC2: return 5; case SH_FLOAT: case SH_INT: case SH_BOOL: case SH_SAMPLER_2D: case SH_SAMPLER_CUBE: case SH_SAMPLER_EXTERNAL_OES: case SH_SAMPLER_2D_RECT_ARB: return 6; default: ASSERT(false); return 7; } } } // namespace int VariablePacker::GetNumComponentsPerRow(ShDataType type) { switch (type) { case SH_FLOAT_MAT4: case SH_FLOAT_MAT2: case SH_FLOAT_VEC4: case SH_INT_VEC4: case SH_BOOL_VEC4: return 4; case SH_FLOAT_MAT3: case SH_FLOAT_VEC3: case SH_INT_VEC3: case SH_BOOL_VEC3: return 3; case SH_FLOAT_VEC2: case SH_INT_VEC2: case SH_BOOL_VEC2: return 2; case SH_FLOAT: case SH_INT: case SH_BOOL: case SH_SAMPLER_2D: case SH_SAMPLER_CUBE: case SH_SAMPLER_EXTERNAL_OES: case SH_SAMPLER_2D_RECT_ARB: return 1; default: ASSERT(false); return 5; } } int VariablePacker::GetNumRows(ShDataType type) { switch (type) { case SH_FLOAT_MAT4: return 4; case SH_FLOAT_MAT3: return 3; case SH_FLOAT_MAT2: return 2; case SH_FLOAT_VEC4: case SH_INT_VEC4: case SH_BOOL_VEC4: case SH_FLOAT_VEC3: case SH_INT_VEC3: case SH_BOOL_VEC3: case SH_FLOAT_VEC2: case SH_INT_VEC2: case SH_BOOL_VEC2: case SH_FLOAT: case SH_INT: case SH_BOOL: case SH_SAMPLER_2D: case SH_SAMPLER_CUBE: case SH_SAMPLER_EXTERNAL_OES: case SH_SAMPLER_2D_RECT_ARB: return 1; default: ASSERT(false); return 100000; } } struct TVariableInfoComparer { bool operator()(const TVariableInfo& lhs, const TVariableInfo& rhs) const { int lhsSortOrder = GetSortOrder(lhs.type); int rhsSortOrder = GetSortOrder(rhs.type); if (lhsSortOrder != rhsSortOrder) { return lhsSortOrder < rhsSortOrder; } // Sort by largest first. return lhs.size > rhs.size; } }; unsigned VariablePacker::makeColumnFlags(int column, int numComponentsPerRow) { return ((kColumnMask << (kNumColumns - numComponentsPerRow)) & kColumnMask) >> column; } void VariablePacker::fillColumns(int topRow, int numRows, int column, int numComponentsPerRow) { unsigned columnFlags = makeColumnFlags(column, numComponentsPerRow); for (int r = 0; r < numRows; ++r) { int row = topRow + r; ASSERT((rows_[row] & columnFlags) == 0); rows_[row] |= columnFlags; } } bool VariablePacker::searchColumn(int column, int numRows, int* destRow, int* destSize) { ASSERT(destRow); for (; topNonFullRow_ < maxRows_ && rows_[topNonFullRow_] == kColumnMask; ++topNonFullRow_) { } for (; bottomNonFullRow_ >= 0 && rows_[bottomNonFullRow_] == kColumnMask; --bottomNonFullRow_) { } if (bottomNonFullRow_ - topNonFullRow_ + 1 < numRows) { return false; } unsigned columnFlags = makeColumnFlags(column, 1); int topGoodRow = 0; int smallestGoodTop = -1; int smallestGoodSize = maxRows_ + 1; int bottomRow = bottomNonFullRow_ + 1; bool found = false; for (int row = topNonFullRow_; row <= bottomRow; ++row) { bool rowEmpty = row < bottomRow ? ((rows_[row] & columnFlags) == 0) : false; if (rowEmpty) { if (!found) { topGoodRow = row; found = true; } } else { if (found) { int size = row - topGoodRow; if (size >= numRows && size < smallestGoodSize) { smallestGoodSize = size; smallestGoodTop = topGoodRow; } } found = false; } } if (smallestGoodTop < 0) { return false; } *destRow = smallestGoodTop; if (destSize) { *destSize = smallestGoodSize; } return true; } bool VariablePacker::CheckVariablesWithinPackingLimits(int maxVectors, const TVariableInfoList& in_variables) { ASSERT(maxVectors > 0); maxRows_ = maxVectors; topNonFullRow_ = 0; bottomNonFullRow_ = maxRows_ - 1; TVariableInfoList variables(in_variables); // As per GLSL 1.017 Appendix A, Section 7 variables are packed in specific // order by type, then by size of array, largest first. std::sort(variables.begin(), variables.end(), TVariableInfoComparer()); rows_.clear(); rows_.resize(maxVectors, 0); // Packs the 4 column variables. size_t ii = 0; for (; ii < variables.size(); ++ii) { const TVariableInfo& variable = variables[ii]; if (GetNumComponentsPerRow(variable.type) != 4) { break; } topNonFullRow_ += GetNumRows(variable.type) * variable.size; } if (topNonFullRow_ > maxRows_) { return false; } // Packs the 3 column variables. int num3ColumnRows = 0; for (; ii < variables.size(); ++ii) { const TVariableInfo& variable = variables[ii]; if (GetNumComponentsPerRow(variable.type) != 3) { break; } num3ColumnRows += GetNumRows(variable.type) * variable.size; } if (topNonFullRow_ + num3ColumnRows > maxRows_) { return false; } fillColumns(topNonFullRow_, num3ColumnRows, 0, 3); // Packs the 2 column variables. int top2ColumnRow = topNonFullRow_ + num3ColumnRows; int twoColumnRowsAvailable = maxRows_ - top2ColumnRow; int rowsAvailableInColumns01 = twoColumnRowsAvailable; int rowsAvailableInColumns23 = twoColumnRowsAvailable; for (; ii < variables.size(); ++ii) { const TVariableInfo& variable = variables[ii]; if (GetNumComponentsPerRow(variable.type) != 2) { break; } int numRows = GetNumRows(variable.type) * variable.size; if (numRows <= rowsAvailableInColumns01) { rowsAvailableInColumns01 -= numRows; } else if (numRows <= rowsAvailableInColumns23) { rowsAvailableInColumns23 -= numRows; } else { return false; } } int numRowsUsedInColumns01 = twoColumnRowsAvailable - rowsAvailableInColumns01; int numRowsUsedInColumns23 = twoColumnRowsAvailable - rowsAvailableInColumns23; fillColumns(top2ColumnRow, numRowsUsedInColumns01, 0, 2); fillColumns(maxRows_ - numRowsUsedInColumns23, numRowsUsedInColumns23, 2, 2); // Packs the 1 column variables. for (; ii < variables.size(); ++ii) { const TVariableInfo& variable = variables[ii]; ASSERT(1 == GetNumComponentsPerRow(variable.type)); int numRows = GetNumRows(variable.type) * variable.size; int smallestColumn = -1; int smallestSize = maxRows_ + 1; int topRow = -1; for (int column = 0; column < kNumColumns; ++column) { int row = 0; int size = 0; if (searchColumn(column, numRows, &row, &size)) { if (size < smallestSize) { smallestSize = size; smallestColumn = column; topRow = row; } } } if (smallestColumn < 0) { return false; } fillColumns(topRow, numRows, smallestColumn, 1); } ASSERT(variables.size() == ii); return true; }
C++
// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/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) { it->visitSymbol(this); } void TIntermConstantUnion::traverse(TIntermTraverser* it) { it->visitConstantUnion(this); } // // Traverse a binary node. // void TIntermBinary::traverse(TIntermTraverser* it) { bool visit = true; // // visit the node before children if pre-visiting. // if(it->preVisit) { visit = it->visitBinary(PreVisit, this); } // // Visit the children, in the right order. // if(visit) { it->incrementDepth(); if(it->rightToLeft) { if(right) { right->traverse(it); } if(it->inVisit) { visit = it->visitBinary(InVisit, this); } if(visit && left) { left->traverse(it); } } else { if(left) { left->traverse(it); } if(it->inVisit) { visit = it->visitBinary(InVisit, this); } if(visit && right) { right->traverse(it); } } it->decrementDepth(); } // // Visit the node after the children, if requested and the traversal // hasn't been cancelled yet. // if(visit && it->postVisit) { it->visitBinary(PostVisit, this); } } // // Traverse a unary node. Same comments in binary node apply here. // void TIntermUnary::traverse(TIntermTraverser* it) { bool visit = true; if (it->preVisit) visit = it->visitUnary(PreVisit, this); if (visit) { it->incrementDepth(); operand->traverse(it); it->decrementDepth(); } if (visit && it->postVisit) it->visitUnary(PostVisit, this); } // // Traverse an aggregate node. Same comments in binary node apply here. // void TIntermAggregate::traverse(TIntermTraverser* it) { bool visit = true; if(it->preVisit) { visit = it->visitAggregate(PreVisit, this); } if(visit) { it->incrementDepth(); if(it->rightToLeft) { for(TIntermSequence::reverse_iterator sit = sequence.rbegin(); sit != sequence.rend(); sit++) { (*sit)->traverse(it); if(visit && it->inVisit) { if(*sit != sequence.front()) { visit = it->visitAggregate(InVisit, this); } } } } else { for(TIntermSequence::iterator sit = sequence.begin(); sit != sequence.end(); sit++) { (*sit)->traverse(it); if(visit && it->inVisit) { if(*sit != sequence.back()) { visit = it->visitAggregate(InVisit, this); } } } } it->decrementDepth(); } if(visit && it->postVisit) { it->visitAggregate(PostVisit, this); } } // // Traverse a selection node. Same comments in binary node apply here. // void TIntermSelection::traverse(TIntermTraverser* it) { bool visit = true; if (it->preVisit) visit = it->visitSelection(PreVisit, this); if (visit) { it->incrementDepth(); 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->decrementDepth(); } if (visit && it->postVisit) it->visitSelection(PostVisit, this); } // // Traverse a loop node. Same comments in binary node apply here. // void TIntermLoop::traverse(TIntermTraverser* it) { bool visit = true; if(it->preVisit) { visit = it->visitLoop(PreVisit, this); } if(visit) { it->incrementDepth(); if(it->rightToLeft) { if(expr) { expr->traverse(it); } if(body) { body->traverse(it); } if(cond) { cond->traverse(it); } } else { if(cond) { cond->traverse(it); } if(body) { body->traverse(it); } if(expr) { expr->traverse(it); } } it->decrementDepth(); } if(visit && it->postVisit) { it->visitLoop(PostVisit, this); } } // // Traverse a branch node. Same comments in binary node apply here. // void TIntermBranch::traverse(TIntermTraverser* it) { bool visit = true; if (it->preVisit) visit = it->visitBranch(PreVisit, this); if (visit && expression) { it->incrementDepth(); expression->traverse(it); it->decrementDepth(); } if (visit && it->postVisit) it->visitBranch(PostVisit, this); }
C++
// // Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // // Definition of the in-memory high-level intermediate representation // of shaders. This is a tree that parser creates. // // Nodes in the tree are defined as a hierarchy of classes derived from // TIntermNode. Each is a node in a tree. There is no preset branching factor; // each node can have it's own type of list of children. // #ifndef __INTERMEDIATE_H #define __INTERMEDIATE_H #include "GLSLANG/ShaderLang.h" #include <algorithm> #include "compiler/Common.h" #include "compiler/Types.h" #include "compiler/ConstantUnion.h" // // Operators used by the high-level (parse tree) representation. // enum TOperator { EOpNull, // if in a node, should only mean a node is still being built EOpSequence, // denotes a list of statements, or parameters, etc. EOpFunctionCall, EOpFunction, // For function definition EOpParameters, // an aggregate listing the parameters to a function EOpDeclaration, EOpPrototype, // // Unary operators // EOpNegative, EOpLogicalNot, EOpVectorLogicalNot, EOpPostIncrement, EOpPostDecrement, EOpPreIncrement, EOpPreDecrement, EOpConvIntToBool, EOpConvFloatToBool, EOpConvBoolToFloat, EOpConvIntToFloat, EOpConvFloatToInt, EOpConvBoolToInt, // // binary operations // EOpAdd, EOpSub, EOpMul, EOpDiv, EOpEqual, EOpNotEqual, EOpVectorEqual, EOpVectorNotEqual, EOpLessThan, EOpGreaterThan, EOpLessThanEqual, EOpGreaterThanEqual, EOpComma, EOpVectorTimesScalar, EOpVectorTimesMatrix, EOpMatrixTimesVector, EOpMatrixTimesScalar, EOpLogicalOr, EOpLogicalXor, EOpLogicalAnd, EOpIndexDirect, EOpIndexIndirect, EOpIndexDirectStruct, EOpVectorSwizzle, // // Built-in functions potentially mapped to operators // EOpRadians, EOpDegrees, EOpSin, EOpCos, EOpTan, EOpAsin, EOpAcos, EOpAtan, EOpPow, EOpExp, EOpLog, EOpExp2, EOpLog2, EOpSqrt, EOpInverseSqrt, EOpAbs, EOpSign, EOpFloor, EOpCeil, EOpFract, EOpMod, EOpMin, EOpMax, EOpClamp, EOpMix, EOpStep, EOpSmoothStep, EOpLength, EOpDistance, EOpDot, EOpCross, EOpNormalize, EOpFaceForward, EOpReflect, EOpRefract, EOpDFdx, // Fragment only, OES_standard_derivatives extension EOpDFdy, // Fragment only, OES_standard_derivatives extension EOpFwidth, // Fragment only, OES_standard_derivatives extension EOpMatrixTimesMatrix, EOpAny, EOpAll, // // Branch // EOpKill, // Fragment only EOpReturn, EOpBreak, EOpContinue, // // Constructors // EOpConstructInt, EOpConstructBool, EOpConstructFloat, EOpConstructVec2, EOpConstructVec3, EOpConstructVec4, EOpConstructBVec2, EOpConstructBVec3, EOpConstructBVec4, EOpConstructIVec2, EOpConstructIVec3, EOpConstructIVec4, EOpConstructMat2, EOpConstructMat3, EOpConstructMat4, EOpConstructStruct, // // moves // EOpAssign, EOpInitialize, EOpAddAssign, EOpSubAssign, EOpMulAssign, EOpVectorTimesMatrixAssign, EOpVectorTimesScalarAssign, EOpMatrixTimesScalarAssign, EOpMatrixTimesMatrixAssign, EOpDivAssign }; extern const char* getOperatorString(TOperator op); class TIntermTraverser; class TIntermAggregate; class TIntermBinary; class TIntermUnary; class TIntermConstantUnion; class TIntermSelection; class TIntermTyped; class TIntermSymbol; class TIntermLoop; class TInfoSink; // // Base class for the tree nodes // class TIntermNode { public: POOL_ALLOCATOR_NEW_DELETE(GlobalPoolAllocator) TIntermNode() { // TODO: Move this to TSourceLoc constructor // after getting rid of TPublicType. line.first_file = line.last_file = 0; line.first_line = line.last_line = 0; } virtual ~TIntermNode() { } const TSourceLoc& getLine() const { return line; } void setLine(const TSourceLoc& l) { line = l; } virtual void traverse(TIntermTraverser*) = 0; virtual TIntermTyped* getAsTyped() { return 0; } virtual TIntermConstantUnion* getAsConstantUnion() { return 0; } virtual TIntermAggregate* getAsAggregate() { return 0; } virtual TIntermBinary* getAsBinaryNode() { return 0; } virtual TIntermUnary* getAsUnaryNode() { return 0; } virtual TIntermSelection* getAsSelectionNode() { return 0; } virtual TIntermSymbol* getAsSymbolNode() { return 0; } virtual TIntermLoop* getAsLoopNode() { return 0; } protected: TSourceLoc line; }; // // This is just to help yacc. // struct TIntermNodePair { TIntermNode* node1; TIntermNode* node2; }; // // Intermediate class for nodes that have a type. // class TIntermTyped : public TIntermNode { public: TIntermTyped(const TType& t) : type(t) { } virtual TIntermTyped* getAsTyped() { return this; } void setType(const TType& t) { type = t; } const TType& getType() const { return type; } TType* getTypePointer() { return &type; } TBasicType getBasicType() const { return type.getBasicType(); } TQualifier getQualifier() const { return type.getQualifier(); } TPrecision getPrecision() const { return type.getPrecision(); } int getNominalSize() const { return type.getNominalSize(); } bool isMatrix() const { return type.isMatrix(); } bool isArray() const { return type.isArray(); } bool isVector() const { return type.isVector(); } bool isScalar() const { return type.isScalar(); } const char* getBasicString() const { return type.getBasicString(); } const char* getQualifierString() const { return type.getQualifierString(); } TString getCompleteString() const { return type.getCompleteString(); } int totalRegisterCount() const { return type.totalRegisterCount(); } int elementRegisterCount() const { return type.elementRegisterCount(); } int getArraySize() const { return type.getArraySize(); } protected: TType type; }; // // Handle for, do-while, and while loops. // enum TLoopType { ELoopFor, ELoopWhile, ELoopDoWhile }; class TIntermLoop : public TIntermNode { public: TIntermLoop(TLoopType aType, TIntermNode *aInit, TIntermTyped* aCond, TIntermTyped* aExpr, TIntermNode* aBody) : type(aType), init(aInit), cond(aCond), expr(aExpr), body(aBody), unrollFlag(false) { } virtual TIntermLoop* getAsLoopNode() { return this; } virtual void traverse(TIntermTraverser*); TLoopType getType() const { return type; } TIntermNode* getInit() { return init; } TIntermTyped* getCondition() { return cond; } TIntermTyped* getExpression() { return expr; } TIntermNode* getBody() { return body; } void setUnrollFlag(bool flag) { unrollFlag = flag; } bool getUnrollFlag() { return unrollFlag; } protected: TLoopType type; TIntermNode* init; // for-loop initialization TIntermTyped* cond; // loop exit condition TIntermTyped* expr; // for-loop expression TIntermNode* body; // loop body bool unrollFlag; // Whether the loop should be unrolled or not. }; // // Handle break, continue, return, and kill. // class TIntermBranch : public TIntermNode { public: TIntermBranch(TOperator op, TIntermTyped* e) : flowOp(op), expression(e) { } virtual void traverse(TIntermTraverser*); TOperator getFlowOp() { return flowOp; } TIntermTyped* getExpression() { return expression; } protected: TOperator flowOp; TIntermTyped* expression; // non-zero except for "return exp;" statements }; // // Nodes that correspond to symbols or constants in the source code. // class TIntermSymbol : public TIntermTyped { public: // if symbol is initialized as symbol(sym), the memory comes from the poolallocator of sym. If sym comes from // per process globalpoolallocator, then it causes increased memory usage per compile // it is essential to use "symbol = sym" to assign to symbol TIntermSymbol(int i, const TString& sym, const TType& t) : TIntermTyped(t), id(i) { symbol = sym; originalSymbol = sym; } int getId() const { return id; } const TString& getSymbol() const { return symbol; } void setId(int newId) { id = newId; } void setSymbol(const TString& sym) { symbol = sym; } const TString& getOriginalSymbol() const { return originalSymbol; } virtual void traverse(TIntermTraverser*); virtual TIntermSymbol* getAsSymbolNode() { return this; } protected: int id; TString symbol; TString originalSymbol; }; class TIntermConstantUnion : public TIntermTyped { public: TIntermConstantUnion(ConstantUnion *unionPointer, const TType& t) : TIntermTyped(t), unionArrayPointer(unionPointer) { } ConstantUnion* getUnionArrayPointer() const { return unionArrayPointer; } int getIConst(int index) const { return unionArrayPointer ? unionArrayPointer[index].getIConst() : 0; } float getFConst(int index) const { return unionArrayPointer ? unionArrayPointer[index].getFConst() : 0.0f; } bool getBConst(int index) const { return unionArrayPointer ? unionArrayPointer[index].getBConst() : false; } virtual TIntermConstantUnion* getAsConstantUnion() { return this; } virtual void traverse(TIntermTraverser*); TIntermTyped* fold(TOperator, TIntermTyped*, TInfoSink&); protected: ConstantUnion *unionArrayPointer; }; // // Intermediate class for node types that hold operators. // class TIntermOperator : public TIntermTyped { public: TOperator getOp() const { return op; } void setOp(TOperator o) { op = o; } bool modifiesState() const; bool isConstructor() const; protected: TIntermOperator(TOperator o) : TIntermTyped(TType(EbtFloat, EbpUndefined)), op(o) {} TIntermOperator(TOperator o, TType& t) : TIntermTyped(t), op(o) {} TOperator op; }; // // Nodes for all the basic binary math operators. // class TIntermBinary : public TIntermOperator { public: TIntermBinary(TOperator o) : TIntermOperator(o), addIndexClamp(false) {} virtual TIntermBinary* getAsBinaryNode() { return this; } virtual void traverse(TIntermTraverser*); void setLeft(TIntermTyped* n) { left = n; } void setRight(TIntermTyped* n) { right = n; } TIntermTyped* getLeft() const { return left; } TIntermTyped* getRight() const { return right; } bool promote(TInfoSink&); void setAddIndexClamp() { addIndexClamp = true; } bool getAddIndexClamp() { return addIndexClamp; } protected: TIntermTyped* left; TIntermTyped* right; // If set to true, wrap any EOpIndexIndirect with a clamp to bounds. bool addIndexClamp; }; // // Nodes for unary math operators. // class TIntermUnary : public TIntermOperator { public: TIntermUnary(TOperator o, TType& t) : TIntermOperator(o, t), operand(0), useEmulatedFunction(false) {} TIntermUnary(TOperator o) : TIntermOperator(o), operand(0), useEmulatedFunction(false) {} virtual void traverse(TIntermTraverser*); virtual TIntermUnary* getAsUnaryNode() { return this; } void setOperand(TIntermTyped* o) { operand = o; } TIntermTyped* getOperand() { return operand; } bool promote(TInfoSink&); void setUseEmulatedFunction() { useEmulatedFunction = true; } bool getUseEmulatedFunction() { return useEmulatedFunction; } protected: TIntermTyped* operand; // If set to true, replace the built-in function call with an emulated one // to work around driver bugs. bool useEmulatedFunction; }; typedef TVector<TIntermNode*> TIntermSequence; typedef TVector<int> TQualifierList; // // Nodes that operate on an arbitrary sized set of children. // class TIntermAggregate : public TIntermOperator { public: TIntermAggregate() : TIntermOperator(EOpNull), userDefined(false), useEmulatedFunction(false) { } TIntermAggregate(TOperator o) : TIntermOperator(o), useEmulatedFunction(false) { } ~TIntermAggregate() { } virtual TIntermAggregate* getAsAggregate() { return this; } virtual void traverse(TIntermTraverser*); TIntermSequence& getSequence() { return sequence; } void setName(const TString& n) { name = n; } const TString& getName() const { return name; } void setUserDefined() { userDefined = true; } bool isUserDefined() const { return userDefined; } void setOptimize(bool o) { optimize = o; } bool getOptimize() { return optimize; } void setDebug(bool d) { debug = d; } bool getDebug() { return debug; } void setUseEmulatedFunction() { useEmulatedFunction = true; } bool getUseEmulatedFunction() { return useEmulatedFunction; } protected: TIntermAggregate(const TIntermAggregate&); // disallow copy constructor TIntermAggregate& operator=(const TIntermAggregate&); // disallow assignment operator TIntermSequence sequence; TString name; bool userDefined; // used for user defined function names bool optimize; bool debug; // If set to true, replace the built-in function call with an emulated one // to work around driver bugs. bool useEmulatedFunction; }; // // For if tests. Simplified since there is no switch statement. // class TIntermSelection : public TIntermTyped { public: TIntermSelection(TIntermTyped* cond, TIntermNode* trueB, TIntermNode* falseB) : TIntermTyped(TType(EbtVoid, EbpUndefined)), condition(cond), trueBlock(trueB), falseBlock(falseB) {} TIntermSelection(TIntermTyped* cond, TIntermNode* trueB, TIntermNode* falseB, const TType& type) : TIntermTyped(type), condition(cond), trueBlock(trueB), falseBlock(falseB) {} virtual void traverse(TIntermTraverser*); bool usesTernaryOperator() const { return getBasicType() != EbtVoid; } TIntermNode* getCondition() const { return condition; } TIntermNode* getTrueBlock() const { return trueBlock; } TIntermNode* getFalseBlock() const { return falseBlock; } TIntermSelection* getAsSelectionNode() { return this; } protected: TIntermTyped* condition; TIntermNode* trueBlock; TIntermNode* falseBlock; }; enum Visit { PreVisit, InVisit, PostVisit }; // // For traversing the tree. User should derive from this, // put their traversal specific data in it, and then pass // it to a Traverse method. // // When using this, just fill in the methods for nodes you want visited. // Return false from a pre-visit to skip visiting that node's subtree. // class TIntermTraverser { public: POOL_ALLOCATOR_NEW_DELETE(GlobalPoolAllocator) TIntermTraverser(bool preVisit = true, bool inVisit = false, bool postVisit = false, bool rightToLeft = false) : preVisit(preVisit), inVisit(inVisit), postVisit(postVisit), rightToLeft(rightToLeft), depth(0), maxDepth(0) {} virtual ~TIntermTraverser() {}; virtual void visitSymbol(TIntermSymbol*) {} virtual void visitConstantUnion(TIntermConstantUnion*) {} virtual bool visitBinary(Visit visit, TIntermBinary*) {return true;} virtual bool visitUnary(Visit visit, TIntermUnary*) {return true;} virtual bool visitSelection(Visit visit, TIntermSelection*) {return true;} virtual bool visitAggregate(Visit visit, TIntermAggregate*) {return true;} virtual bool visitLoop(Visit visit, TIntermLoop*) {return true;} virtual bool visitBranch(Visit visit, TIntermBranch*) {return true;} int getMaxDepth() const {return maxDepth;} void incrementDepth() {depth++; maxDepth = std::max(maxDepth, depth); } void decrementDepth() {depth--;} // Return the original name if hash function pointer is NULL; // otherwise return the hashed name. static TString hash(const TString& name, ShHashFunction64 hashFunction); const bool preVisit; const bool inVisit; const bool postVisit; const bool rightToLeft; protected: int depth; int maxDepth; }; #endif // __INTERMEDIATE_H
C++
// // Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/TranslatorHLSL.h" #include "compiler/InitializeParseContext.h" #include "compiler/OutputHLSL.h" TranslatorHLSL::TranslatorHLSL(ShShaderType type, ShShaderSpec spec, ShShaderOutput output) : TCompiler(type, spec), mOutputType(output) { } void TranslatorHLSL::translate(TIntermNode *root) { TParseContext& parseContext = *GetGlobalParseContext(); sh::OutputHLSL outputHLSL(parseContext, getResources(), mOutputType); outputHLSL.output(); mActiveUniforms = outputHLSL.getUniforms(); }
C++
// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef _COMMON_INCLUDED_ #define _COMMON_INCLUDED_ #include <map> #include <sstream> #include <string> #include <vector> #include "compiler/PoolAlloc.h" struct TSourceLoc { int first_file; int first_line; int last_file; int last_line; }; // // Put POOL_ALLOCATOR_NEW_DELETE in base classes to make them use this scheme. // #define POOL_ALLOCATOR_NEW_DELETE(A) \ void* operator new(size_t s) { return (A).allocate(s); } \ void* operator new(size_t, void *_Where) { return (_Where); } \ void operator delete(void*) { } \ void operator delete(void *, void *) { } \ void* operator new[](size_t s) { return (A).allocate(s); } \ void* operator new[](size_t, void *_Where) { return (_Where); } \ void operator delete[](void*) { } \ void operator delete[](void *, void *) { } // // Pool version of string. // typedef pool_allocator<char> TStringAllocator; typedef std::basic_string <char, std::char_traits<char>, TStringAllocator> TString; typedef std::basic_ostringstream<char, std::char_traits<char>, TStringAllocator> TStringStream; inline TString* NewPoolTString(const char* s) { void* memory = GlobalPoolAllocator.allocate(sizeof(TString)); return new(memory) TString(s); } // // Persistent string memory. Should only be used for strings that survive // across compiles. // #define TPersistString std::string #define TPersistStringStream std::ostringstream // // Pool allocator versions of vectors, lists, and maps // template <class T> class TVector : public std::vector<T, pool_allocator<T> > { public: typedef typename std::vector<T, pool_allocator<T> >::size_type size_type; TVector() : std::vector<T, pool_allocator<T> >() {} TVector(const pool_allocator<T>& a) : std::vector<T, pool_allocator<T> >(a) {} TVector(size_type i): std::vector<T, pool_allocator<T> >(i) {} }; template <class K, class D, class CMP = std::less<K> > class TMap : public std::map<K, D, CMP, pool_allocator<std::pair<const K, D> > > { public: typedef pool_allocator<std::pair<const K, D> > tAllocator; TMap() : std::map<K, D, CMP, tAllocator>() {} // use correct two-stage name lookup supported in gcc 3.4 and above TMap(const tAllocator& a) : std::map<K, D, CMP, tAllocator>(std::map<K, D, CMP, tAllocator>::key_compare(), a) {} }; #endif // _COMMON_INCLUDED_
C++
// // Copyright (c) 2002-2011 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/BuiltInFunctionEmulator.h" #include "compiler/SymbolTable.h" namespace { // we use macros here instead of function definitions to work around more GLSL // compiler bugs, in particular on NVIDIA hardware on Mac OSX. Macros are // problematic because if the argument has side-effects they will be repeatedly // evaluated. This is unlikely to show up in real shaders, but is something to // consider. const char* kFunctionEmulationVertexSource[] = { "#error no emulation for cos(float)", "#error no emulation for cos(vec2)", "#error no emulation for cos(vec3)", "#error no emulation for cos(vec4)", "#define webgl_distance_emu(x, y) ((x) >= (y) ? (x) - (y) : (y) - (x))", "#error no emulation for distance(vec2, vec2)", "#error no emulation for distance(vec3, vec3)", "#error no emulation for distance(vec4, vec4)", "#define webgl_dot_emu(x, y) ((x) * (y))", "#error no emulation for dot(vec2, vec2)", "#error no emulation for dot(vec3, vec3)", "#error no emulation for dot(vec4, vec4)", "#define webgl_length_emu(x) ((x) >= 0.0 ? (x) : -(x))", "#error no emulation for length(vec2)", "#error no emulation for length(vec3)", "#error no emulation for length(vec4)", "#define webgl_normalize_emu(x) ((x) == 0.0 ? 0.0 : ((x) > 0.0 ? 1.0 : -1.0))", "#error no emulation for normalize(vec2)", "#error no emulation for normalize(vec3)", "#error no emulation for normalize(vec4)", "#define webgl_reflect_emu(I, N) ((I) - 2.0 * (N) * (I) * (N))", "#error no emulation for reflect(vec2, vec2)", "#error no emulation for reflect(vec3, vec3)", "#error no emulation for reflect(vec4, vec4)" }; const char* kFunctionEmulationFragmentSource[] = { "webgl_emu_precision float webgl_cos_emu(webgl_emu_precision float a) { return cos(a); }", "webgl_emu_precision vec2 webgl_cos_emu(webgl_emu_precision vec2 a) { return cos(a); }", "webgl_emu_precision vec3 webgl_cos_emu(webgl_emu_precision vec3 a) { return cos(a); }", "webgl_emu_precision vec4 webgl_cos_emu(webgl_emu_precision vec4 a) { return cos(a); }", "#define webgl_distance_emu(x, y) ((x) >= (y) ? (x) - (y) : (y) - (x))", "#error no emulation for distance(vec2, vec2)", "#error no emulation for distance(vec3, vec3)", "#error no emulation for distance(vec4, vec4)", "#define webgl_dot_emu(x, y) ((x) * (y))", "#error no emulation for dot(vec2, vec2)", "#error no emulation for dot(vec3, vec3)", "#error no emulation for dot(vec4, vec4)", "#define webgl_length_emu(x) ((x) >= 0.0 ? (x) : -(x))", "#error no emulation for length(vec2)", "#error no emulation for length(vec3)", "#error no emulation for length(vec4)", "#define webgl_normalize_emu(x) ((x) == 0.0 ? 0.0 : ((x) > 0.0 ? 1.0 : -1.0))", "#error no emulation for normalize(vec2)", "#error no emulation for normalize(vec3)", "#error no emulation for normalize(vec4)", "#define webgl_reflect_emu(I, N) ((I) - 2.0 * (N) * (I) * (N))", "#error no emulation for reflect(vec2, vec2)", "#error no emulation for reflect(vec3, vec3)", "#error no emulation for reflect(vec4, vec4)" }; const bool kFunctionEmulationVertexMask[] = { #if defined(__APPLE__) // Work around ATI driver bugs in Mac. false, // TFunctionCos1 false, // TFunctionCos2 false, // TFunctionCos3 false, // TFunctionCos4 true, // TFunctionDistance1_1 false, // TFunctionDistance2_2 false, // TFunctionDistance3_3 false, // TFunctionDistance4_4 true, // TFunctionDot1_1 false, // TFunctionDot2_2 false, // TFunctionDot3_3 false, // TFunctionDot4_4 true, // TFunctionLength1 false, // TFunctionLength2 false, // TFunctionLength3 false, // TFunctionLength4 true, // TFunctionNormalize1 false, // TFunctionNormalize2 false, // TFunctionNormalize3 false, // TFunctionNormalize4 true, // TFunctionReflect1_1 false, // TFunctionReflect2_2 false, // TFunctionReflect3_3 false, // TFunctionReflect4_4 #else // Work around D3D driver bug in Win. false, // TFunctionCos1 false, // TFunctionCos2 false, // TFunctionCos3 false, // TFunctionCos4 false, // TFunctionDistance1_1 false, // TFunctionDistance2_2 false, // TFunctionDistance3_3 false, // TFunctionDistance4_4 false, // TFunctionDot1_1 false, // TFunctionDot2_2 false, // TFunctionDot3_3 false, // TFunctionDot4_4 false, // TFunctionLength1 false, // TFunctionLength2 false, // TFunctionLength3 false, // TFunctionLength4 false, // TFunctionNormalize1 false, // TFunctionNormalize2 false, // TFunctionNormalize3 false, // TFunctionNormalize4 false, // TFunctionReflect1_1 false, // TFunctionReflect2_2 false, // TFunctionReflect3_3 false, // TFunctionReflect4_4 #endif false // TFunctionUnknown }; const bool kFunctionEmulationFragmentMask[] = { #if defined(__APPLE__) // Work around ATI driver bugs in Mac. true, // TFunctionCos1 true, // TFunctionCos2 true, // TFunctionCos3 true, // TFunctionCos4 true, // TFunctionDistance1_1 false, // TFunctionDistance2_2 false, // TFunctionDistance3_3 false, // TFunctionDistance4_4 true, // TFunctionDot1_1 false, // TFunctionDot2_2 false, // TFunctionDot3_3 false, // TFunctionDot4_4 true, // TFunctionLength1 false, // TFunctionLength2 false, // TFunctionLength3 false, // TFunctionLength4 true, // TFunctionNormalize1 false, // TFunctionNormalize2 false, // TFunctionNormalize3 false, // TFunctionNormalize4 true, // TFunctionReflect1_1 false, // TFunctionReflect2_2 false, // TFunctionReflect3_3 false, // TFunctionReflect4_4 #else // Work around D3D driver bug in Win. false, // TFunctionCos1 false, // TFunctionCos2 false, // TFunctionCos3 false, // TFunctionCos4 false, // TFunctionDistance1_1 false, // TFunctionDistance2_2 false, // TFunctionDistance3_3 false, // TFunctionDistance4_4 false, // TFunctionDot1_1 false, // TFunctionDot2_2 false, // TFunctionDot3_3 false, // TFunctionDot4_4 false, // TFunctionLength1 false, // TFunctionLength2 false, // TFunctionLength3 false, // TFunctionLength4 false, // TFunctionNormalize1 false, // TFunctionNormalize2 false, // TFunctionNormalize3 false, // TFunctionNormalize4 false, // TFunctionReflect1_1 false, // TFunctionReflect2_2 false, // TFunctionReflect3_3 false, // TFunctionReflect4_4 #endif false // TFunctionUnknown }; class BuiltInFunctionEmulationMarker : public TIntermTraverser { public: BuiltInFunctionEmulationMarker(BuiltInFunctionEmulator& emulator) : mEmulator(emulator) { } virtual bool visitUnary(Visit visit, TIntermUnary* node) { if (visit == PreVisit) { bool needToEmulate = mEmulator.SetFunctionCalled( node->getOp(), node->getOperand()->getType()); if (needToEmulate) node->setUseEmulatedFunction(); } return true; } virtual bool visitAggregate(Visit visit, TIntermAggregate* node) { if (visit == PreVisit) { // Here we handle all the built-in functions instead of the ones we // currently identified as problematic. switch (node->getOp()) { case EOpLessThan: case EOpGreaterThan: case EOpLessThanEqual: case EOpGreaterThanEqual: case EOpVectorEqual: case EOpVectorNotEqual: case EOpMod: case EOpPow: case EOpAtan: case EOpMin: case EOpMax: case EOpClamp: case EOpMix: case EOpStep: case EOpSmoothStep: case EOpDistance: case EOpDot: case EOpCross: case EOpFaceForward: case EOpReflect: case EOpRefract: case EOpMul: break; default: return true; }; const TIntermSequence& sequence = node->getSequence(); // Right now we only handle built-in functions with two parameters. if (sequence.size() != 2) return true; TIntermTyped* param1 = sequence[0]->getAsTyped(); TIntermTyped* param2 = sequence[1]->getAsTyped(); if (!param1 || !param2) return true; bool needToEmulate = mEmulator.SetFunctionCalled( node->getOp(), param1->getType(), param2->getType()); if (needToEmulate) node->setUseEmulatedFunction(); } return true; } private: BuiltInFunctionEmulator& mEmulator; }; } // anonymous namepsace BuiltInFunctionEmulator::BuiltInFunctionEmulator(ShShaderType shaderType) { if (shaderType == SH_FRAGMENT_SHADER) { mFunctionMask = kFunctionEmulationFragmentMask; mFunctionSource = kFunctionEmulationFragmentSource; } else { mFunctionMask = kFunctionEmulationVertexMask; mFunctionSource = kFunctionEmulationVertexSource; } } bool BuiltInFunctionEmulator::SetFunctionCalled( TOperator op, const TType& param) { TBuiltInFunction function = IdentifyFunction(op, param); return SetFunctionCalled(function); } bool BuiltInFunctionEmulator::SetFunctionCalled( TOperator op, const TType& param1, const TType& param2) { TBuiltInFunction function = IdentifyFunction(op, param1, param2); return SetFunctionCalled(function); } bool BuiltInFunctionEmulator::SetFunctionCalled( BuiltInFunctionEmulator::TBuiltInFunction function) { if (function == TFunctionUnknown || mFunctionMask[function] == false) return false; for (size_t i = 0; i < mFunctions.size(); ++i) { if (mFunctions[i] == function) return true; } mFunctions.push_back(function); return true; } void BuiltInFunctionEmulator::OutputEmulatedFunctionDefinition( TInfoSinkBase& out, bool withPrecision) const { if (mFunctions.size() == 0) return; out << "// BEGIN: Generated code for built-in function emulation\n\n"; if (withPrecision) { out << "#if defined(GL_FRAGMENT_PRECISION_HIGH)\n" << "#define webgl_emu_precision highp\n" << "#else\n" << "#define webgl_emu_precision mediump\n" << "#endif\n\n"; } else { out << "#define webgl_emu_precision\n\n"; } for (size_t i = 0; i < mFunctions.size(); ++i) { out << mFunctionSource[mFunctions[i]] << "\n\n"; } out << "// END: Generated code for built-in function emulation\n\n"; } BuiltInFunctionEmulator::TBuiltInFunction BuiltInFunctionEmulator::IdentifyFunction( TOperator op, const TType& param) { if (param.getNominalSize() > 4) return TFunctionUnknown; unsigned int function = TFunctionUnknown; switch (op) { case EOpCos: function = TFunctionCos1; break; case EOpLength: function = TFunctionLength1; break; case EOpNormalize: function = TFunctionNormalize1; break; default: break; } if (function == TFunctionUnknown) return TFunctionUnknown; if (param.isVector()) function += param.getNominalSize() - 1; return static_cast<TBuiltInFunction>(function); } BuiltInFunctionEmulator::TBuiltInFunction BuiltInFunctionEmulator::IdentifyFunction( TOperator op, const TType& param1, const TType& param2) { // Right now for all the emulated functions with two parameters, the two // parameters have the same type. if (param1.isVector() != param2.isVector() || param1.getNominalSize() != param2.getNominalSize() || param1.getNominalSize() > 4) return TFunctionUnknown; unsigned int function = TFunctionUnknown; switch (op) { case EOpDistance: function = TFunctionDistance1_1; break; case EOpDot: function = TFunctionDot1_1; break; case EOpReflect: function = TFunctionReflect1_1; break; default: break; } if (function == TFunctionUnknown) return TFunctionUnknown; if (param1.isVector()) function += param1.getNominalSize() - 1; return static_cast<TBuiltInFunction>(function); } void BuiltInFunctionEmulator::MarkBuiltInFunctionsForEmulation( TIntermNode* root) { ASSERT(root); BuiltInFunctionEmulationMarker marker(*this); root->traverse(&marker); } void BuiltInFunctionEmulator::Cleanup() { mFunctions.clear(); } //static TString BuiltInFunctionEmulator::GetEmulatedFunctionName( const TString& name) { ASSERT(name[name.length() - 1] == '('); return "webgl_" + name.substr(0, name.length() - 1) + "_emu("; }
C++
// // Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/BuiltInFunctionEmulator.h" #include "compiler/DetectCallDepth.h" #include "compiler/ForLoopUnroll.h" #include "compiler/Initialize.h" #include "compiler/InitializeParseContext.h" #include "compiler/MapLongVariableNames.h" #include "compiler/ParseHelper.h" #include "compiler/RenameFunction.h" #include "compiler/ShHandle.h" #include "compiler/ValidateLimitations.h" #include "compiler/VariablePacker.h" #include "compiler/depgraph/DependencyGraph.h" #include "compiler/depgraph/DependencyGraphOutput.h" #include "compiler/timing/RestrictFragmentShaderTiming.h" #include "compiler/timing/RestrictVertexShaderTiming.h" #include "third_party/compiler/ArrayBoundsClamper.h" bool isWebGLBasedSpec(ShShaderSpec spec) { return spec == SH_WEBGL_SPEC || spec == SH_CSS_SHADERS_SPEC; } namespace { bool InitializeSymbolTable( const TBuiltInStrings& builtInStrings, ShShaderType type, ShShaderSpec spec, const ShBuiltInResources& resources, TInfoSink& infoSink, TSymbolTable& symbolTable) { TIntermediate intermediate(infoSink); TExtensionBehavior extBehavior; InitExtensionBehavior(resources, extBehavior); // The builtins deliberately don't specify precisions for the function // arguments and return types. For that reason we don't try to check them. TParseContext parseContext(symbolTable, extBehavior, intermediate, type, spec, 0, false, NULL, infoSink); parseContext.fragmentPrecisionHigh = resources.FragmentPrecisionHigh == 1; GlobalParseContext = &parseContext; assert(symbolTable.isEmpty()); // // 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(); for (TBuiltInStrings::const_iterator i = builtInStrings.begin(); i != builtInStrings.end(); ++i) { const char* builtInShaders = i->c_str(); int builtInLengths = static_cast<int>(i->size()); if (builtInLengths <= 0) continue; if (PaParseStrings(1, &builtInShaders, &builtInLengths, &parseContext) != 0) { infoSink.info.prefix(EPrefixInternalError); infoSink.info << "Unable to parse built-ins"; return false; } } IdentifyBuiltIns(type, spec, resources, symbolTable); return true; } class TScopedPoolAllocator { public: TScopedPoolAllocator(TPoolAllocator* allocator, bool pushPop) : mAllocator(allocator), mPushPopAllocator(pushPop) { if (mPushPopAllocator) mAllocator->push(); SetGlobalPoolAllocator(mAllocator); } ~TScopedPoolAllocator() { SetGlobalPoolAllocator(NULL); if (mPushPopAllocator) mAllocator->pop(); } private: TPoolAllocator* mAllocator; bool mPushPopAllocator; }; } // namespace TShHandleBase::TShHandleBase() { allocator.push(); SetGlobalPoolAllocator(&allocator); } TShHandleBase::~TShHandleBase() { SetGlobalPoolAllocator(NULL); allocator.popAll(); } TCompiler::TCompiler(ShShaderType type, ShShaderSpec spec) : shaderType(type), shaderSpec(spec), maxUniformVectors(0), maxExpressionComplexity(0), maxCallStackDepth(0), fragmentPrecisionHigh(false), clampingStrategy(SH_CLAMP_WITH_CLAMP_INTRINSIC), builtInFunctionEmulator(type) { longNameMap = LongNameMap::GetInstance(); } TCompiler::~TCompiler() { ASSERT(longNameMap); longNameMap->Release(); } bool TCompiler::Init(const ShBuiltInResources& resources) { maxUniformVectors = (shaderType == SH_VERTEX_SHADER) ? resources.MaxVertexUniformVectors : resources.MaxFragmentUniformVectors; maxExpressionComplexity = resources.MaxExpressionComplexity; maxCallStackDepth = resources.MaxCallStackDepth; TScopedPoolAllocator scopedAlloc(&allocator, false); // Generate built-in symbol table. if (!InitBuiltInSymbolTable(resources)) return false; InitExtensionBehavior(resources, extensionBehavior); fragmentPrecisionHigh = resources.FragmentPrecisionHigh == 1; arrayBoundsClamper.SetClampingStrategy(resources.ArrayIndexClampingStrategy); clampingStrategy = resources.ArrayIndexClampingStrategy; hashFunction = resources.HashFunction; return true; } bool TCompiler::compile(const char* const shaderStrings[], size_t numStrings, int compileOptions) { TScopedPoolAllocator scopedAlloc(&allocator, true); clearResults(); if (numStrings == 0) return true; // If compiling for WebGL, validate loop and indexing as well. if (isWebGLBasedSpec(shaderSpec)) compileOptions |= SH_VALIDATE_LOOP_INDEXING; // First string is path of source file if flag is set. The actual source follows. const char* sourcePath = NULL; size_t firstSource = 0; if (compileOptions & SH_SOURCE_PATH) { sourcePath = shaderStrings[0]; ++firstSource; } TIntermediate intermediate(infoSink); TParseContext parseContext(symbolTable, extensionBehavior, intermediate, shaderType, shaderSpec, compileOptions, true, sourcePath, infoSink); parseContext.fragmentPrecisionHigh = fragmentPrecisionHigh; GlobalParseContext = &parseContext; // We preserve symbols at the built-in level from compile-to-compile. // Start pushing the user-defined symbols at global level. symbolTable.push(); if (!symbolTable.atGlobalLevel()) { infoSink.info.prefix(EPrefixInternalError); infoSink.info << "Wrong symbol table level"; } // Parse shader. bool success = (PaParseStrings(numStrings - firstSource, &shaderStrings[firstSource], NULL, &parseContext) == 0) && (parseContext.treeRoot != NULL); if (success) { TIntermNode* root = parseContext.treeRoot; success = intermediate.postProcess(root); if (success) success = detectCallDepth(root, infoSink, (compileOptions & SH_LIMIT_CALL_STACK_DEPTH) != 0); if (success && (compileOptions & SH_VALIDATE_LOOP_INDEXING)) success = validateLimitations(root); if (success && (compileOptions & SH_TIMING_RESTRICTIONS)) success = enforceTimingRestrictions(root, (compileOptions & SH_DEPENDENCY_GRAPH) != 0); if (success && shaderSpec == SH_CSS_SHADERS_SPEC) rewriteCSSShader(root); // Unroll for-loop markup needs to happen after validateLimitations pass. if (success && (compileOptions & SH_UNROLL_FOR_LOOP_WITH_INTEGER_INDEX)) ForLoopUnroll::MarkForLoopsWithIntegerIndicesForUnrolling(root); // Built-in function emulation needs to happen after validateLimitations pass. if (success && (compileOptions & SH_EMULATE_BUILT_IN_FUNCTIONS)) builtInFunctionEmulator.MarkBuiltInFunctionsForEmulation(root); // Clamping uniform array bounds needs to happen after validateLimitations pass. if (success && (compileOptions & SH_CLAMP_INDIRECT_ARRAY_BOUNDS)) arrayBoundsClamper.MarkIndirectArrayBoundsForClamping(root); // Disallow expressions deemed too complex. if (success && (compileOptions & SH_LIMIT_EXPRESSION_COMPLEXITY)) success = limitExpressionComplexity(root); // Call mapLongVariableNames() before collectAttribsUniforms() so in // collectAttribsUniforms() we already have the mapped symbol names and // we could composite mapped and original variable names. // Also, if we hash all the names, then no need to do this for long names. if (success && (compileOptions & SH_MAP_LONG_VARIABLE_NAMES) && hashFunction == NULL) mapLongVariableNames(root); if (success && (compileOptions & SH_ATTRIBUTES_UNIFORMS)) { collectAttribsUniforms(root); if (compileOptions & SH_ENFORCE_PACKING_RESTRICTIONS) { success = enforcePackingRestrictions(); if (!success) { infoSink.info.prefix(EPrefixError); infoSink.info << "too many uniforms"; } } } if (success && (compileOptions & SH_INTERMEDIATE_TREE)) intermediate.outputTree(root); if (success && (compileOptions & SH_OBJECT_CODE)) translate(root); } // Cleanup memory. intermediate.remove(parseContext.treeRoot); // Ensure symbol table is returned to the built-in level, // throwing away all but the built-ins. while (!symbolTable.atBuiltInLevel()) symbolTable.pop(); return success; } bool TCompiler::InitBuiltInSymbolTable(const ShBuiltInResources& resources) { TBuiltIns builtIns; compileResources = resources; builtIns.initialize(shaderType, shaderSpec, resources, extensionBehavior); return InitializeSymbolTable(builtIns.getBuiltInStrings(), shaderType, shaderSpec, resources, infoSink, symbolTable); } void TCompiler::clearResults() { arrayBoundsClamper.Cleanup(); infoSink.info.erase(); infoSink.obj.erase(); infoSink.debug.erase(); attribs.clear(); uniforms.clear(); builtInFunctionEmulator.Cleanup(); nameMap.clear(); } bool TCompiler::detectCallDepth(TIntermNode* root, TInfoSink& infoSink, bool limitCallStackDepth) { DetectCallDepth detect(infoSink, limitCallStackDepth, maxCallStackDepth); root->traverse(&detect); switch (detect.detectCallDepth()) { case DetectCallDepth::kErrorNone: return true; case DetectCallDepth::kErrorMissingMain: infoSink.info.prefix(EPrefixError); infoSink.info << "Missing main()"; return false; case DetectCallDepth::kErrorRecursion: infoSink.info.prefix(EPrefixError); infoSink.info << "Function recursion detected"; return false; case DetectCallDepth::kErrorMaxDepthExceeded: infoSink.info.prefix(EPrefixError); infoSink.info << "Function call stack too deep"; return false; default: UNREACHABLE(); return false; } } void TCompiler::rewriteCSSShader(TIntermNode* root) { RenameFunction renamer("main(", "css_main("); root->traverse(&renamer); } bool TCompiler::validateLimitations(TIntermNode* root) { ValidateLimitations validate(shaderType, infoSink.info); root->traverse(&validate); return validate.numErrors() == 0; } bool TCompiler::enforceTimingRestrictions(TIntermNode* root, bool outputGraph) { if (shaderSpec != SH_WEBGL_SPEC) { infoSink.info << "Timing restrictions must be enforced under the WebGL spec."; return false; } if (shaderType == SH_FRAGMENT_SHADER) { TDependencyGraph graph(root); // Output any errors first. bool success = enforceFragmentShaderTimingRestrictions(graph); // Then, output the dependency graph. if (outputGraph) { TDependencyGraphOutput output(infoSink.info); output.outputAllSpanningTrees(graph); } return success; } else { return enforceVertexShaderTimingRestrictions(root); } } bool TCompiler::limitExpressionComplexity(TIntermNode* root) { TIntermTraverser traverser; root->traverse(&traverser); TDependencyGraph graph(root); for (TFunctionCallVector::const_iterator iter = graph.beginUserDefinedFunctionCalls(); iter != graph.endUserDefinedFunctionCalls(); ++iter) { TGraphFunctionCall* samplerSymbol = *iter; TDependencyGraphTraverser graphTraverser; samplerSymbol->traverse(&graphTraverser); } if (traverser.getMaxDepth() > maxExpressionComplexity) { infoSink.info << "Expression too complex."; return false; } return true; } bool TCompiler::enforceFragmentShaderTimingRestrictions(const TDependencyGraph& graph) { RestrictFragmentShaderTiming restrictor(infoSink.info); restrictor.enforceRestrictions(graph); return restrictor.numErrors() == 0; } bool TCompiler::enforceVertexShaderTimingRestrictions(TIntermNode* root) { RestrictVertexShaderTiming restrictor(infoSink.info); restrictor.enforceRestrictions(root); return restrictor.numErrors() == 0; } void TCompiler::collectAttribsUniforms(TIntermNode* root) { CollectAttribsUniforms collect(attribs, uniforms, hashFunction); root->traverse(&collect); } bool TCompiler::enforcePackingRestrictions() { VariablePacker packer; return packer.CheckVariablesWithinPackingLimits(maxUniformVectors, uniforms); } void TCompiler::mapLongVariableNames(TIntermNode* root) { ASSERT(longNameMap); MapLongVariableNames map(longNameMap); root->traverse(&map); } int TCompiler::getMappedNameMaxLength() const { return MAX_SHORTENED_IDENTIFIER_SIZE + 1; } const TExtensionBehavior& TCompiler::getExtensionBehavior() const { return extensionBehavior; } const ShBuiltInResources& TCompiler::getResources() const { return compileResources; } const ArrayBoundsClamper& TCompiler::getArrayBoundsClamper() const { return arrayBoundsClamper; } ShArrayIndexClampingStrategy TCompiler::getArrayIndexClampingStrategy() const { return clampingStrategy; } const BuiltInFunctionEmulator& TCompiler::getBuiltInFunctionEmulator() const { return builtInFunctionEmulator; }
C++
// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/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(TInfoSinkBase& i) : sink(i) { } TInfoSinkBase& sink; protected: void visitSymbol(TIntermSymbol*); void visitConstantUnion(TIntermConstantUnion*); bool visitBinary(Visit visit, TIntermBinary*); bool visitUnary(Visit visit, TIntermUnary*); bool visitSelection(Visit visit, TIntermSelection*); bool visitAggregate(Visit visit, TIntermAggregate*); bool visitLoop(Visit visit, TIntermLoop*); bool visitBranch(Visit visit, TIntermBranch*); }; TString TType::getCompleteString() const { TStringStream stream; if (qualifier != EvqTemporary && qualifier != EvqGlobal) stream << getQualifierString() << " " << getPrecisionString() << " "; if (array) stream << "array[" << getArraySize() << "] of "; if (matrix) stream << size << "X" << size << " matrix of "; else if (size > 1) stream << size << "-component vector of "; stream << getBasicString(); return stream.str(); } // // Helper functions for printing, not part of traversing. // void OutputTreeText(TInfoSinkBase& sink, TIntermNode* node, const int depth) { int i; sink.location(node->getLine()); for (i = 0; i < depth; ++i) sink << " "; } // // 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 TOutputTraverser::visitSymbol(TIntermSymbol* node) { OutputTreeText(sink, node, depth); sink << "'" << node->getSymbol() << "' "; sink << "(" << node->getCompleteString() << ")\n"; } bool TOutputTraverser::visitBinary(Visit visit, TIntermBinary* node) { TInfoSinkBase& out = sink; OutputTreeText(out, node, depth); switch (node->getOp()) { case EOpAssign: out << "move second child to first child"; break; case EOpInitialize: out << "initialize first child with second child"; break; case EOpAddAssign: out << "add second child into first child"; break; case EOpSubAssign: out << "subtract second child into first child"; break; case EOpMulAssign: out << "multiply second child into first child"; break; case EOpVectorTimesMatrixAssign: out << "matrix mult second child into first child"; break; case EOpVectorTimesScalarAssign: out << "vector scale second child into first child"; break; case EOpMatrixTimesScalarAssign: out << "matrix scale second child into first child"; break; case EOpMatrixTimesMatrixAssign: out << "matrix mult second child into first child"; break; case EOpDivAssign: out << "divide second child into first child"; break; case EOpIndexDirect: out << "direct index"; break; case EOpIndexIndirect: out << "indirect index"; break; case EOpIndexDirectStruct: out << "direct index for structure"; break; case EOpVectorSwizzle: out << "vector swizzle"; break; case EOpAdd: out << "add"; break; case EOpSub: out << "subtract"; break; case EOpMul: out << "component-wise multiply"; break; case EOpDiv: out << "divide"; break; case EOpEqual: out << "Compare Equal"; break; case EOpNotEqual: out << "Compare Not Equal"; break; case EOpLessThan: out << "Compare Less Than"; break; case EOpGreaterThan: out << "Compare Greater Than"; break; case EOpLessThanEqual: out << "Compare Less Than or Equal"; break; case EOpGreaterThanEqual: out << "Compare Greater Than or Equal"; break; case EOpVectorTimesScalar: out << "vector-scale"; break; case EOpVectorTimesMatrix: out << "vector-times-matrix"; break; case EOpMatrixTimesVector: out << "matrix-times-vector"; break; case EOpMatrixTimesScalar: out << "matrix-scale"; break; case EOpMatrixTimesMatrix: out << "matrix-multiply"; break; case EOpLogicalOr: out << "logical-or"; break; case EOpLogicalXor: out << "logical-xor"; break; case EOpLogicalAnd: out << "logical-and"; break; default: out << "<unknown op>"; } out << " (" << node->getCompleteString() << ")"; out << "\n"; return true; } bool TOutputTraverser::visitUnary(Visit visit, TIntermUnary* node) { TInfoSinkBase& out = sink; OutputTreeText(out, node, depth); switch (node->getOp()) { case EOpNegative: out << "Negate value"; break; case EOpVectorLogicalNot: case EOpLogicalNot: out << "Negate conditional"; break; case EOpPostIncrement: out << "Post-Increment"; break; case EOpPostDecrement: out << "Post-Decrement"; break; case EOpPreIncrement: out << "Pre-Increment"; break; case EOpPreDecrement: out << "Pre-Decrement"; break; case EOpConvIntToBool: out << "Convert int to bool"; break; case EOpConvFloatToBool:out << "Convert float to bool";break; case EOpConvBoolToFloat:out << "Convert bool to float";break; case EOpConvIntToFloat: out << "Convert int to float"; break; case EOpConvFloatToInt: out << "Convert float to int"; break; case EOpConvBoolToInt: out << "Convert bool to int"; break; case EOpRadians: out << "radians"; break; case EOpDegrees: out << "degrees"; break; case EOpSin: out << "sine"; break; case EOpCos: out << "cosine"; break; case EOpTan: out << "tangent"; break; case EOpAsin: out << "arc sine"; break; case EOpAcos: out << "arc cosine"; break; case EOpAtan: out << "arc tangent"; break; case EOpExp: out << "exp"; break; case EOpLog: out << "log"; break; case EOpExp2: out << "exp2"; break; case EOpLog2: out << "log2"; break; case EOpSqrt: out << "sqrt"; break; case EOpInverseSqrt: out << "inverse sqrt"; break; case EOpAbs: out << "Absolute value"; break; case EOpSign: out << "Sign"; break; case EOpFloor: out << "Floor"; break; case EOpCeil: out << "Ceiling"; break; case EOpFract: out << "Fraction"; break; case EOpLength: out << "length"; break; case EOpNormalize: out << "normalize"; break; // case EOpDPdx: out << "dPdx"; break; // case EOpDPdy: out << "dPdy"; break; // case EOpFwidth: out << "fwidth"; break; case EOpAny: out << "any"; break; case EOpAll: out << "all"; break; default: out.prefix(EPrefixError); out << "Bad unary op"; } out << " (" << node->getCompleteString() << ")"; out << "\n"; return true; } bool TOutputTraverser::visitAggregate(Visit visit, TIntermAggregate* node) { TInfoSinkBase& out = sink; if (node->getOp() == EOpNull) { out.prefix(EPrefixError); out << "node is still EOpNull!"; return true; } OutputTreeText(out, node, depth); switch (node->getOp()) { case EOpSequence: out << "Sequence\n"; return true; case EOpComma: out << "Comma\n"; return true; case EOpFunction: out << "Function Definition: " << node->getName(); break; case EOpFunctionCall: out << "Function Call: " << node->getName(); break; case EOpParameters: out << "Function Parameters: "; break; case EOpConstructFloat: out << "Construct float"; break; case EOpConstructVec2: out << "Construct vec2"; break; case EOpConstructVec3: out << "Construct vec3"; break; case EOpConstructVec4: out << "Construct vec4"; break; case EOpConstructBool: out << "Construct bool"; break; case EOpConstructBVec2: out << "Construct bvec2"; break; case EOpConstructBVec3: out << "Construct bvec3"; break; case EOpConstructBVec4: out << "Construct bvec4"; break; case EOpConstructInt: out << "Construct int"; break; case EOpConstructIVec2: out << "Construct ivec2"; break; case EOpConstructIVec3: out << "Construct ivec3"; break; case EOpConstructIVec4: out << "Construct ivec4"; break; case EOpConstructMat2: out << "Construct mat2"; break; case EOpConstructMat3: out << "Construct mat3"; break; case EOpConstructMat4: out << "Construct mat4"; break; case EOpConstructStruct: out << "Construct structure"; break; case EOpLessThan: out << "Compare Less Than"; break; case EOpGreaterThan: out << "Compare Greater Than"; break; case EOpLessThanEqual: out << "Compare Less Than or Equal"; break; case EOpGreaterThanEqual: out << "Compare Greater Than or Equal"; break; case EOpVectorEqual: out << "Equal"; break; case EOpVectorNotEqual: out << "NotEqual"; break; case EOpMod: out << "mod"; break; case EOpPow: out << "pow"; break; case EOpAtan: out << "arc tangent"; break; case EOpMin: out << "min"; break; case EOpMax: out << "max"; break; case EOpClamp: out << "clamp"; break; case EOpMix: out << "mix"; break; case EOpStep: out << "step"; break; case EOpSmoothStep: out << "smoothstep"; break; case EOpDistance: out << "distance"; break; case EOpDot: out << "dot-product"; break; case EOpCross: out << "cross-product"; break; case EOpFaceForward: out << "face-forward"; break; case EOpReflect: out << "reflect"; break; case EOpRefract: out << "refract"; break; case EOpMul: out << "component-wise multiply"; break; case EOpDeclaration: out << "Declaration: "; break; default: out.prefix(EPrefixError); out << "Bad aggregation op"; } if (node->getOp() != EOpSequence && node->getOp() != EOpParameters) out << " (" << node->getCompleteString() << ")"; out << "\n"; return true; } bool TOutputTraverser::visitSelection(Visit visit, TIntermSelection* node) { TInfoSinkBase& out = sink; OutputTreeText(out, node, depth); out << "Test condition and select"; out << " (" << node->getCompleteString() << ")\n"; ++depth; OutputTreeText(sink, node, depth); out << "Condition\n"; node->getCondition()->traverse(this); OutputTreeText(sink, node, depth); if (node->getTrueBlock()) { out << "true case\n"; node->getTrueBlock()->traverse(this); } else out << "true case is null\n"; if (node->getFalseBlock()) { OutputTreeText(sink, node, depth); out << "false case\n"; node->getFalseBlock()->traverse(this); } --depth; return false; } void TOutputTraverser::visitConstantUnion(TIntermConstantUnion* node) { TInfoSinkBase& out = sink; size_t size = node->getType().getObjectSize(); for (size_t i = 0; i < size; i++) { OutputTreeText(out, node, depth); switch (node->getUnionArrayPointer()[i].getType()) { case EbtBool: if (node->getUnionArrayPointer()[i].getBConst()) out << "true"; else out << "false"; out << " (" << "const bool" << ")"; out << "\n"; break; case EbtFloat: out << node->getUnionArrayPointer()[i].getFConst(); out << " (const float)\n"; break; case EbtInt: out << node->getUnionArrayPointer()[i].getIConst(); out << " (const int)\n"; break; default: out.message(EPrefixInternalError, node->getLine(), "Unknown constant"); break; } } } bool TOutputTraverser::visitLoop(Visit visit, TIntermLoop* node) { TInfoSinkBase& out = sink; OutputTreeText(out, node, depth); out << "Loop with condition "; if (node->getType() == ELoopDoWhile) out << "not "; out << "tested first\n"; ++depth; OutputTreeText(sink, node, depth); if (node->getCondition()) { out << "Loop Condition\n"; node->getCondition()->traverse(this); } else out << "No loop condition\n"; OutputTreeText(sink, node, depth); if (node->getBody()) { out << "Loop Body\n"; node->getBody()->traverse(this); } else out << "No loop body\n"; if (node->getExpression()) { OutputTreeText(sink, node, depth); out << "Loop Terminal Expression\n"; node->getExpression()->traverse(this); } --depth; return false; } bool TOutputTraverser::visitBranch(Visit visit, TIntermBranch* node) { TInfoSinkBase& out = sink; OutputTreeText(out, node, depth); switch (node->getFlowOp()) { case EOpKill: out << "Branch: Kill"; break; case EOpBreak: out << "Branch: Break"; break; case EOpContinue: out << "Branch: Continue"; break; case EOpReturn: out << "Branch: Return"; break; default: out << "Branch: Unknown Branch"; break; } if (node->getExpression()) { out << " with expression\n"; ++depth; node->getExpression()->traverse(this); --depth; } else out << "\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.info); root->traverse(&it); }
C++
// // Copyright (c) 2002-2011 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_DETECT_RECURSION_H_ #define COMPILER_DETECT_RECURSION_H_ #include "GLSLANG/ShaderLang.h" #include <limits.h> #include "compiler/intermediate.h" #include "compiler/VariableInfo.h" class TInfoSink; // Traverses intermediate tree to detect function recursion. class DetectCallDepth : public TIntermTraverser { public: enum ErrorCode { kErrorMissingMain, kErrorRecursion, kErrorMaxDepthExceeded, kErrorNone }; DetectCallDepth(TInfoSink& infoSync, bool limitCallStackDepth, int maxCallStackDepth); ~DetectCallDepth(); virtual bool visitAggregate(Visit, TIntermAggregate*); bool checkExceedsMaxDepth(int depth); ErrorCode detectCallDepth(); private: class FunctionNode { public: static const int kInfiniteCallDepth = INT_MAX; FunctionNode(const TString& fname); const TString& getName() const; // If a function is already in the callee list, this becomes a no-op. void addCallee(FunctionNode* callee); // Returns kInifinityCallDepth if recursive function calls are detected. int detectCallDepth(DetectCallDepth* detectCallDepth, int depth); // Reset state. void reset(); private: // mangled function name is unique. TString name; // functions that are directly called by this function. TVector<FunctionNode*> callees; Visit visit; }; ErrorCode detectCallDepthForFunction(FunctionNode* func); FunctionNode* findFunctionByName(const TString& name); void resetFunctionNodes(); TInfoSink& getInfoSink() { return infoSink; } TVector<FunctionNode*> functions; FunctionNode* currentFunction; TInfoSink& infoSink; int maxDepth; DetectCallDepth(const DetectCallDepth&); void operator=(const DetectCallDepth&); }; #endif // COMPILER_DETECT_RECURSION_H_
C++
// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef _POOLALLOC_INCLUDED_ #define _POOLALLOC_INCLUDED_ #ifdef _DEBUG #define GUARD_BLOCKS // define to enable guard block sanity checking #endif // // This header defines an allocator that can be used to efficiently // allocate a large number of small requests for heap memory, with the // intention that they are not individually deallocated, but rather // collectively deallocated at one time. // // This simultaneously // // * Makes each individual allocation much more efficient; the // typical allocation is trivial. // * Completely avoids the cost of doing individual deallocation. // * Saves the trouble of tracking down and plugging a large class of leaks. // // Individual classes can use this allocator by supplying their own // new and delete methods. // // STL containers can use this allocator by using the pool_allocator // class as the allocator (second) template argument. // #include <stddef.h> #include <string.h> #include <vector> // If we are using guard blocks, we must track each indivual // allocation. If we aren't using guard blocks, these // never get instantiated, so won't have any impact. // class TAllocation { public: TAllocation(size_t size, unsigned char* mem, TAllocation* prev = 0) : size(size), mem(mem), prevAlloc(prev) { // Allocations are bracketed: // [allocationHeader][initialGuardBlock][userData][finalGuardBlock] // This would be cleaner with if (guardBlockSize)..., but that // makes the compiler print warnings about 0 length memsets, // even with the if() protecting them. #ifdef GUARD_BLOCKS memset(preGuard(), guardBlockBeginVal, guardBlockSize); memset(data(), userDataFill, size); memset(postGuard(), guardBlockEndVal, guardBlockSize); #endif } void check() const { checkGuardBlock(preGuard(), guardBlockBeginVal, "before"); checkGuardBlock(postGuard(), guardBlockEndVal, "after"); } void checkAllocList() const; // Return total size needed to accomodate user buffer of 'size', // plus our tracking data. inline static size_t allocationSize(size_t size) { return size + 2 * guardBlockSize + headerSize(); } // Offset from surrounding buffer to get to user data buffer. inline static unsigned char* offsetAllocation(unsigned char* m) { return m + guardBlockSize + headerSize(); } private: void checkGuardBlock(unsigned char* blockMem, unsigned char val, const char* locText) const; // Find offsets to pre and post guard blocks, and user data buffer unsigned char* preGuard() const { return mem + headerSize(); } unsigned char* data() const { return preGuard() + guardBlockSize; } unsigned char* postGuard() const { return data() + size; } size_t size; // size of the user data area unsigned char* mem; // beginning of our allocation (pts to header) TAllocation* prevAlloc; // prior allocation in the chain // Support MSVC++ 6.0 const static unsigned char guardBlockBeginVal; const static unsigned char guardBlockEndVal; const static unsigned char userDataFill; const static size_t guardBlockSize; #ifdef GUARD_BLOCKS inline static size_t headerSize() { return sizeof(TAllocation); } #else inline static size_t headerSize() { return 0; } #endif }; // // There are several stacks. One is to track the pushing and popping // of the user, and not yet implemented. The others are simply a // repositories of free pages or used pages. // // Page stacks are linked together with a simple header at the beginning // of each allocation obtained from the underlying OS. Multi-page allocations // are returned to the OS. Individual page allocations are kept for future // re-use. // // The "page size" used is not, nor must it match, the underlying OS // page size. But, having it be about that size or equal to a set of // pages is likely most optimal. // class TPoolAllocator { public: TPoolAllocator(int growthIncrement = 8*1024, int allocationAlignment = 16); // // Don't call the destructor just to free up the memory, call pop() // ~TPoolAllocator(); // // Call push() to establish a new place to pop memory too. Does not // have to be called to get things started. // void push(); // // Call pop() to free all memory allocated since the last call to push(), // or if no last call to push, frees all memory since first allocation. // void pop(); // // Call popAll() to free all memory allocated. // void popAll(); // // Call allocate() to actually acquire memory. Returns 0 if no memory // available, otherwise a properly aligned pointer to 'numBytes' of memory. // void* allocate(size_t numBytes); // // There is no deallocate. The point of this class is that // deallocation can be skipped by the user of it, as the model // of use is to simultaneously deallocate everything at once // by calling pop(), and to not have to solve memory leak problems. // protected: friend struct tHeader; struct tHeader { tHeader(tHeader* nextPage, size_t pageCount) : nextPage(nextPage), pageCount(pageCount) #ifdef GUARD_BLOCKS , lastAllocation(0) #endif { } ~tHeader() { #ifdef GUARD_BLOCKS if (lastAllocation) lastAllocation->checkAllocList(); #endif } tHeader* nextPage; size_t pageCount; #ifdef GUARD_BLOCKS TAllocation* lastAllocation; #endif }; struct tAllocState { size_t offset; tHeader* page; }; typedef std::vector<tAllocState> tAllocStack; // Track allocations if and only if we're using guard blocks void* initializeAllocation(tHeader* block, unsigned char* memory, size_t numBytes) { #ifdef GUARD_BLOCKS new(memory) TAllocation(numBytes, memory, block->lastAllocation); block->lastAllocation = reinterpret_cast<TAllocation*>(memory); #endif // This is optimized entirely away if GUARD_BLOCKS is not defined. return TAllocation::offsetAllocation(memory); } size_t pageSize; // granularity of allocation from the OS size_t alignment; // all returned allocations will be aligned at // this granularity, which will be a power of 2 size_t alignmentMask; size_t headerSkip; // amount of memory to skip to make room for the // header (basically, size of header, rounded // up to make it aligned size_t currentPageOffset; // next offset in top of inUseList to allocate from tHeader* freeList; // list of popped memory tHeader* inUseList; // list of all memory currently being used tAllocStack stack; // stack of where to allocate from, to partition pool int numCalls; // just an interesting statistic size_t totalBytes; // just an interesting statistic private: TPoolAllocator& operator=(const TPoolAllocator&); // dont allow assignment operator TPoolAllocator(const TPoolAllocator&); // dont allow default copy constructor }; // // There could potentially be many pools with pops happening at // different times. But a simple use is to have a global pop // with everyone using the same global allocator. // extern TPoolAllocator& GetGlobalPoolAllocator(); extern void SetGlobalPoolAllocator(TPoolAllocator* poolAllocator); #define GlobalPoolAllocator GetGlobalPoolAllocator() struct TThreadGlobalPools { TPoolAllocator* globalPoolAllocator; }; // // This STL compatible allocator is intended to be used as the allocator // parameter to templatized STL containers, like vector and map. // // It will use the pools for allocation, and not // do any deallocation, but will still do destruction. // template<class T> class pool_allocator { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef T value_type; template<class Other> struct rebind { typedef pool_allocator<Other> other; }; pointer address(reference x) const { return &x; } const_pointer address(const_reference x) const { return &x; } pool_allocator() : allocator(&GlobalPoolAllocator) { } pool_allocator(TPoolAllocator& a) : allocator(&a) { } pool_allocator(const pool_allocator<T>& p) : allocator(p.allocator) { } template <class Other> pool_allocator<T>& operator=(const pool_allocator<Other>& p) { allocator = p.allocator; return *this; } template<class Other> pool_allocator(const pool_allocator<Other>& p) : allocator(&p.getAllocator()) { } #if defined(__SUNPRO_CC) && !defined(_RWSTD_ALLOCATOR) // libCStd on some platforms have a different allocate/deallocate interface. // Caller pre-bakes sizeof(T) into 'n' which is the number of bytes to be // allocated, not the number of elements. void* allocate(size_type n) { return getAllocator().allocate(n); } void* allocate(size_type n, const void*) { return getAllocator().allocate(n); } void deallocate(void*, size_type) {} #else pointer allocate(size_type n) { return reinterpret_cast<pointer>(getAllocator().allocate(n * sizeof(T))); } pointer allocate(size_type n, const void*) { return reinterpret_cast<pointer>(getAllocator().allocate(n * sizeof(T))); } void deallocate(pointer, size_type) {} #endif // _RWSTD_ALLOCATOR void construct(pointer p, const T& val) { new ((void *)p) T(val); } void destroy(pointer p) { p->T::~T(); } bool operator==(const pool_allocator& rhs) const { return &getAllocator() == &rhs.getAllocator(); } bool operator!=(const pool_allocator& rhs) const { return &getAllocator() != &rhs.getAllocator(); } size_type max_size() const { return static_cast<size_type>(-1) / sizeof(T); } size_type max_size(int size) const { return static_cast<size_type>(-1) / size; } void setAllocator(TPoolAllocator* a) { allocator = a; } TPoolAllocator& getAllocator() const { return *allocator; } protected: TPoolAllocator* allocator; }; #endif // _POOLALLOC_INCLUDED_
C++
// // Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/VersionGLSL.h" static const int GLSL_VERSION_110 = 110; static const int GLSL_VERSION_120 = 120; // We need to scan for the following: // 1. "invariant" keyword: This can occur in both - vertex and fragment shaders // but only at the global scope. // 2. "gl_PointCoord" built-in variable: This can only occur in fragment shader // but inside any scope. // 3. Call to a matrix constructor with another matrix as argument. // (These constructors were reserved in GLSL version 1.10.) // 4. Arrays as "out" function parameters. // GLSL spec section 6.1.1: "When calling a function, expressions that do // not evaluate to l-values cannot be passed to parameters declared as // out or inout." // GLSL 1.1 section 5.8: "Other binary or unary expressions, // non-dereferenced arrays, function names, swizzles with repeated fields, // and constants cannot be l-values." // GLSL 1.2 relaxed the restriction on arrays, section 5.8: "Variables that // are built-in types, entire structures or arrays... are all l-values." // // TODO(alokp): The following two cases of invariant decalaration get lost // during parsing - they do not get carried over to the intermediate tree. // Handle these cases: // 1. When a pragma is used to force all output variables to be invariant: // - #pragma STDGL invariant(all) // 2. When a previously decalared or built-in variable is marked invariant: // - invariant gl_Position; // - varying vec3 color; invariant color; // TVersionGLSL::TVersionGLSL(ShShaderType type) : mShaderType(type), mVersion(GLSL_VERSION_110) { } void TVersionGLSL::visitSymbol(TIntermSymbol* node) { if (node->getSymbol() == "gl_PointCoord") updateVersion(GLSL_VERSION_120); } void TVersionGLSL::visitConstantUnion(TIntermConstantUnion*) { } bool TVersionGLSL::visitBinary(Visit, TIntermBinary*) { return true; } bool TVersionGLSL::visitUnary(Visit, TIntermUnary*) { return true; } bool TVersionGLSL::visitSelection(Visit, TIntermSelection*) { return true; } bool TVersionGLSL::visitAggregate(Visit, TIntermAggregate* node) { bool visitChildren = true; switch (node->getOp()) { case EOpSequence: // We need to visit sequence children to get to global or inner scope. visitChildren = true; break; case EOpDeclaration: { const TIntermSequence& sequence = node->getSequence(); TQualifier qualifier = sequence.front()->getAsTyped()->getQualifier(); if ((qualifier == EvqInvariantVaryingIn) || (qualifier == EvqInvariantVaryingOut)) { updateVersion(GLSL_VERSION_120); } break; } case EOpParameters: { const TIntermSequence& params = node->getSequence(); for (TIntermSequence::const_iterator iter = params.begin(); iter != params.end(); ++iter) { const TIntermTyped* param = (*iter)->getAsTyped(); if (param->isArray()) { TQualifier qualifier = param->getQualifier(); if ((qualifier == EvqOut) || (qualifier == EvqInOut)) { updateVersion(GLSL_VERSION_120); break; } } } // Fully processed. No need to visit children. visitChildren = false; break; } case EOpConstructMat2: case EOpConstructMat3: case EOpConstructMat4: { const TIntermSequence& sequence = node->getSequence(); if (sequence.size() == 1) { TIntermTyped* typed = sequence.front()->getAsTyped(); if (typed && typed->isMatrix()) { updateVersion(GLSL_VERSION_120); } } break; } default: break; } return visitChildren; } bool TVersionGLSL::visitLoop(Visit, TIntermLoop*) { return true; } bool TVersionGLSL::visitBranch(Visit, TIntermBranch*) { return true; } void TVersionGLSL::updateVersion(int version) { mVersion = std::max(version, mVersion); }
C++
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/DirectiveHandler.h" #include <sstream> #include "compiler/debug.h" #include "compiler/Diagnostics.h" static TBehavior getBehavior(const std::string& str) { static const std::string kRequire("require"); static const std::string kEnable("enable"); static const std::string kDisable("disable"); static const std::string kWarn("warn"); if (str == kRequire) return EBhRequire; else if (str == kEnable) return EBhEnable; else if (str == kDisable) return EBhDisable; else if (str == kWarn) return EBhWarn; return EBhUndefined; } TDirectiveHandler::TDirectiveHandler(TExtensionBehavior& extBehavior, TDiagnostics& diagnostics) : mExtensionBehavior(extBehavior), mDiagnostics(diagnostics) { } TDirectiveHandler::~TDirectiveHandler() { } void TDirectiveHandler::handleError(const pp::SourceLocation& loc, const std::string& msg) { mDiagnostics.writeInfo(pp::Diagnostics::ERROR, loc, msg, "", ""); } void TDirectiveHandler::handlePragma(const pp::SourceLocation& loc, const std::string& name, const std::string& value) { static const std::string kSTDGL("STDGL"); static const std::string kOptimize("optimize"); static const std::string kDebug("debug"); static const std::string kOn("on"); static const std::string kOff("off"); bool invalidValue = false; if (name == kSTDGL) { // The STDGL pragma is used to reserve pragmas for use by future // revisions of GLSL. Ignore it. return; } else if (name == kOptimize) { if (value == kOn) mPragma.optimize = true; else if (value == kOff) mPragma.optimize = false; else invalidValue = true; } else if (name == kDebug) { if (value == kOn) mPragma.debug = true; else if (value == kOff) mPragma.debug = false; else invalidValue = true; } else { mDiagnostics.report(pp::Diagnostics::UNRECOGNIZED_PRAGMA, loc, name); return; } if (invalidValue) mDiagnostics.writeInfo(pp::Diagnostics::ERROR, loc, "invalid pragma value", value, "'on' or 'off' expected"); } void TDirectiveHandler::handleExtension(const pp::SourceLocation& loc, const std::string& name, const std::string& behavior) { static const std::string kExtAll("all"); TBehavior behaviorVal = getBehavior(behavior); if (behaviorVal == EBhUndefined) { mDiagnostics.writeInfo(pp::Diagnostics::ERROR, loc, "behavior", name, "invalid"); return; } if (name == kExtAll) { if (behaviorVal == EBhRequire) { mDiagnostics.writeInfo(pp::Diagnostics::ERROR, loc, "extension", name, "cannot have 'require' behavior"); } else if (behaviorVal == EBhEnable) { mDiagnostics.writeInfo(pp::Diagnostics::ERROR, loc, "extension", name, "cannot have 'enable' behavior"); } else { for (TExtensionBehavior::iterator iter = mExtensionBehavior.begin(); iter != mExtensionBehavior.end(); ++iter) iter->second = behaviorVal; } return; } TExtensionBehavior::iterator iter = mExtensionBehavior.find(name); if (iter != mExtensionBehavior.end()) { iter->second = behaviorVal; return; } pp::Diagnostics::Severity severity = pp::Diagnostics::ERROR; switch (behaviorVal) { case EBhRequire: severity = pp::Diagnostics::ERROR; break; case EBhEnable: case EBhWarn: case EBhDisable: severity = pp::Diagnostics::WARNING; break; default: UNREACHABLE(); break; } mDiagnostics.writeInfo(severity, loc, "extension", name, "is not supported"); } void TDirectiveHandler::handleVersion(const pp::SourceLocation& loc, int version) { static const int kVersion = 100; if (version != kVersion) { std::stringstream stream; stream << version; std::string str = stream.str(); mDiagnostics.writeInfo(pp::Diagnostics::ERROR, loc, "version number", str, "not supported"); } }
C++
// // Copyright (c) 2002-2011 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/TranslatorESSL.h" #include "compiler/OutputESSL.h" TranslatorESSL::TranslatorESSL(ShShaderType type, ShShaderSpec spec) : TCompiler(type, spec) { } void TranslatorESSL::translate(TIntermNode* root) { TInfoSinkBase& sink = getInfoSink().obj; // Write built-in extension behaviors. writeExtensionBehavior(); // Write emulated built-in functions if needed. getBuiltInFunctionEmulator().OutputEmulatedFunctionDefinition( sink, getShaderType() == SH_FRAGMENT_SHADER); // Write array bounds clamping emulation if needed. getArrayBoundsClamper().OutputClampingFunctionDefinition(sink); // Write translated shader. TOutputESSL outputESSL(sink, getArrayIndexClampingStrategy(), getHashFunction(), getNameMap(), getSymbolTable()); root->traverse(&outputESSL); } void TranslatorESSL::writeExtensionBehavior() { TInfoSinkBase& sink = getInfoSink().obj; const TExtensionBehavior& extensionBehavior = getExtensionBehavior(); for (TExtensionBehavior::const_iterator iter = extensionBehavior.begin(); iter != extensionBehavior.end(); ++iter) { if (iter->second != EBhUndefined) { sink << "#extension " << iter->first << " : " << getBehaviorString(iter->second) << "\n"; } } }
C++
// // Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/ForLoopUnroll.h" namespace { class IntegerForLoopUnrollMarker : public TIntermTraverser { public: virtual bool visitLoop(Visit, TIntermLoop* node) { // This is called after ValidateLimitations pass, so all the ASSERT // should never fail. // See ValidateLimitations::validateForLoopInit(). ASSERT(node); ASSERT(node->getType() == ELoopFor); ASSERT(node->getInit()); TIntermAggregate* decl = node->getInit()->getAsAggregate(); ASSERT(decl && decl->getOp() == EOpDeclaration); TIntermSequence& declSeq = decl->getSequence(); ASSERT(declSeq.size() == 1); TIntermBinary* declInit = declSeq[0]->getAsBinaryNode(); ASSERT(declInit && declInit->getOp() == EOpInitialize); ASSERT(declInit->getLeft()); TIntermSymbol* symbol = declInit->getLeft()->getAsSymbolNode(); ASSERT(symbol); TBasicType type = symbol->getBasicType(); ASSERT(type == EbtInt || type == EbtFloat); if (type == EbtInt) node->setUnrollFlag(true); return true; } }; } // anonymous namepsace void ForLoopUnroll::FillLoopIndexInfo(TIntermLoop* node, TLoopIndexInfo& info) { ASSERT(node->getType() == ELoopFor); ASSERT(node->getUnrollFlag()); TIntermNode* init = node->getInit(); ASSERT(init != NULL); TIntermAggregate* decl = init->getAsAggregate(); ASSERT((decl != NULL) && (decl->getOp() == EOpDeclaration)); TIntermSequence& declSeq = decl->getSequence(); ASSERT(declSeq.size() == 1); TIntermBinary* declInit = declSeq[0]->getAsBinaryNode(); ASSERT((declInit != NULL) && (declInit->getOp() == EOpInitialize)); TIntermSymbol* symbol = declInit->getLeft()->getAsSymbolNode(); ASSERT(symbol != NULL); ASSERT(symbol->getBasicType() == EbtInt); info.id = symbol->getId(); ASSERT(declInit->getRight() != NULL); TIntermConstantUnion* initNode = declInit->getRight()->getAsConstantUnion(); ASSERT(initNode != NULL); info.initValue = evaluateIntConstant(initNode); info.currentValue = info.initValue; TIntermNode* cond = node->getCondition(); ASSERT(cond != NULL); TIntermBinary* binOp = cond->getAsBinaryNode(); ASSERT(binOp != NULL); ASSERT(binOp->getRight() != NULL); ASSERT(binOp->getRight()->getAsConstantUnion() != NULL); info.incrementValue = getLoopIncrement(node); info.stopValue = evaluateIntConstant( binOp->getRight()->getAsConstantUnion()); info.op = binOp->getOp(); } void ForLoopUnroll::Step() { ASSERT(mLoopIndexStack.size() > 0); TLoopIndexInfo& info = mLoopIndexStack[mLoopIndexStack.size() - 1]; info.currentValue += info.incrementValue; } bool ForLoopUnroll::SatisfiesLoopCondition() { ASSERT(mLoopIndexStack.size() > 0); TLoopIndexInfo& info = mLoopIndexStack[mLoopIndexStack.size() - 1]; // Relational operator is one of: > >= < <= == or !=. switch (info.op) { case EOpEqual: return (info.currentValue == info.stopValue); case EOpNotEqual: return (info.currentValue != info.stopValue); case EOpLessThan: return (info.currentValue < info.stopValue); case EOpGreaterThan: return (info.currentValue > info.stopValue); case EOpLessThanEqual: return (info.currentValue <= info.stopValue); case EOpGreaterThanEqual: return (info.currentValue >= info.stopValue); default: UNREACHABLE(); } return false; } bool ForLoopUnroll::NeedsToReplaceSymbolWithValue(TIntermSymbol* symbol) { for (TVector<TLoopIndexInfo>::iterator i = mLoopIndexStack.begin(); i != mLoopIndexStack.end(); ++i) { if (i->id == symbol->getId()) return true; } return false; } int ForLoopUnroll::GetLoopIndexValue(TIntermSymbol* symbol) { for (TVector<TLoopIndexInfo>::iterator i = mLoopIndexStack.begin(); i != mLoopIndexStack.end(); ++i) { if (i->id == symbol->getId()) return i->currentValue; } UNREACHABLE(); return false; } void ForLoopUnroll::Push(TLoopIndexInfo& info) { mLoopIndexStack.push_back(info); } void ForLoopUnroll::Pop() { mLoopIndexStack.pop_back(); } // static void ForLoopUnroll::MarkForLoopsWithIntegerIndicesForUnrolling( TIntermNode* root) { ASSERT(root); IntegerForLoopUnrollMarker marker; root->traverse(&marker); } int ForLoopUnroll::getLoopIncrement(TIntermLoop* node) { TIntermNode* expr = node->getExpression(); ASSERT(expr != NULL); // for expression has one of the following forms: // loop_index++ // loop_index-- // loop_index += constant_expression // loop_index -= constant_expression // ++loop_index // --loop_index // The last two forms are not specified in the spec, but I am assuming // its an oversight. TIntermUnary* unOp = expr->getAsUnaryNode(); TIntermBinary* binOp = unOp ? NULL : expr->getAsBinaryNode(); TOperator op = EOpNull; TIntermConstantUnion* incrementNode = NULL; if (unOp != NULL) { op = unOp->getOp(); } else if (binOp != NULL) { op = binOp->getOp(); ASSERT(binOp->getRight() != NULL); incrementNode = binOp->getRight()->getAsConstantUnion(); ASSERT(incrementNode != NULL); } int increment = 0; // The operator is one of: ++ -- += -=. switch (op) { case EOpPostIncrement: case EOpPreIncrement: ASSERT((unOp != NULL) && (binOp == NULL)); increment = 1; break; case EOpPostDecrement: case EOpPreDecrement: ASSERT((unOp != NULL) && (binOp == NULL)); increment = -1; break; case EOpAddAssign: ASSERT((unOp == NULL) && (binOp != NULL)); increment = evaluateIntConstant(incrementNode); break; case EOpSubAssign: ASSERT((unOp == NULL) && (binOp != NULL)); increment = - evaluateIntConstant(incrementNode); break; default: ASSERT(false); } return increment; } int ForLoopUnroll::evaluateIntConstant(TIntermConstantUnion* node) { ASSERT((node != NULL) && (node->getUnionArrayPointer() != NULL)); return node->getIConst(0); }
C++
// // Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // // Build the intermediate representation. // #include <float.h> #include <limits.h> #include <algorithm> #include "compiler/HashNames.h" #include "compiler/localintermediate.h" #include "compiler/QualifierAlive.h" #include "compiler/RemoveTree.h" bool CompareStructure(const TType& leftNodeType, ConstantUnion* rightUnionArray, ConstantUnion* leftUnionArray); static TPrecision GetHigherPrecision( TPrecision left, TPrecision right ){ return left > right ? left : right; } const char* getOperatorString(TOperator op) { switch (op) { case EOpInitialize: return "="; case EOpAssign: return "="; case EOpAddAssign: return "+="; case EOpSubAssign: return "-="; case EOpDivAssign: return "/="; // Fall-through. case EOpMulAssign: case EOpVectorTimesMatrixAssign: case EOpVectorTimesScalarAssign: case EOpMatrixTimesScalarAssign: case EOpMatrixTimesMatrixAssign: return "*="; // Fall-through. case EOpIndexDirect: case EOpIndexIndirect: return "[]"; case EOpIndexDirectStruct: return "."; case EOpVectorSwizzle: return "."; case EOpAdd: return "+"; case EOpSub: return "-"; case EOpMul: return "*"; case EOpDiv: return "/"; case EOpMod: UNIMPLEMENTED(); break; case EOpEqual: return "=="; case EOpNotEqual: return "!="; case EOpLessThan: return "<"; case EOpGreaterThan: return ">"; case EOpLessThanEqual: return "<="; case EOpGreaterThanEqual: return ">="; // Fall-through. case EOpVectorTimesScalar: case EOpVectorTimesMatrix: case EOpMatrixTimesVector: case EOpMatrixTimesScalar: case EOpMatrixTimesMatrix: return "*"; case EOpLogicalOr: return "||"; case EOpLogicalXor: return "^^"; case EOpLogicalAnd: return "&&"; case EOpNegative: return "-"; case EOpVectorLogicalNot: return "not"; case EOpLogicalNot: return "!"; case EOpPostIncrement: return "++"; case EOpPostDecrement: return "--"; case EOpPreIncrement: return "++"; case EOpPreDecrement: return "--"; // Fall-through. case EOpConvIntToBool: case EOpConvFloatToBool: return "bool"; // Fall-through. case EOpConvBoolToFloat: case EOpConvIntToFloat: return "float"; // Fall-through. case EOpConvFloatToInt: case EOpConvBoolToInt: return "int"; case EOpRadians: return "radians"; case EOpDegrees: return "degrees"; case EOpSin: return "sin"; case EOpCos: return "cos"; case EOpTan: return "tan"; case EOpAsin: return "asin"; case EOpAcos: return "acos"; case EOpAtan: return "atan"; case EOpExp: return "exp"; case EOpLog: return "log"; case EOpExp2: return "exp2"; case EOpLog2: return "log2"; case EOpSqrt: return "sqrt"; case EOpInverseSqrt: return "inversesqrt"; case EOpAbs: return "abs"; case EOpSign: return "sign"; case EOpFloor: return "floor"; case EOpCeil: return "ceil"; case EOpFract: return "fract"; case EOpLength: return "length"; case EOpNormalize: return "normalize"; case EOpDFdx: return "dFdx"; case EOpDFdy: return "dFdy"; case EOpFwidth: return "fwidth"; case EOpAny: return "any"; case EOpAll: return "all"; default: break; } return ""; } //////////////////////////////////////////////////////////////////////////// // // First set of functions are to help build the intermediate representation. // These functions are not member functions of the nodes. // They are called from parser productions. // ///////////////////////////////////////////////////////////////////////////// // // Add a terminal node for an identifier in an expression. // // Returns the added node. // TIntermSymbol* TIntermediate::addSymbol(int id, const TString& name, const TType& type, const TSourceLoc& line) { TIntermSymbol* node = new TIntermSymbol(id, name, type); node->setLine(line); return node; } // // Connect two nodes with a new parent that does a binary operation on the nodes. // // Returns the added node. // TIntermTyped* TIntermediate::addBinaryMath(TOperator op, TIntermTyped* left, TIntermTyped* right, const TSourceLoc& line, TSymbolTable& symbolTable) { switch (op) { case EOpEqual: case EOpNotEqual: if (left->isArray()) return 0; break; case EOpLessThan: case EOpGreaterThan: case EOpLessThanEqual: case EOpGreaterThanEqual: if (left->isMatrix() || left->isArray() || left->isVector() || left->getBasicType() == EbtStruct) { return 0; } break; case EOpLogicalOr: case EOpLogicalXor: case EOpLogicalAnd: if (left->getBasicType() != EbtBool || left->isMatrix() || left->isArray() || left->isVector()) { return 0; } break; case EOpAdd: case EOpSub: case EOpDiv: case EOpMul: if (left->getBasicType() == EbtStruct || left->getBasicType() == EbtBool) return 0; default: break; } // // First try converting the children to compatible types. // if (left->getType().getStruct() && right->getType().getStruct()) { if (left->getType() != right->getType()) return 0; } else { TIntermTyped* child = addConversion(op, left->getType(), right); if (child) right = child; else { child = addConversion(op, right->getType(), left); if (child) left = child; else return 0; } } // // Need a new node holding things together then. Make // one and promote it to the right type. // TIntermBinary* node = new TIntermBinary(op); node->setLine(line); node->setLeft(left); node->setRight(right); if (!node->promote(infoSink)) return 0; // // See if we can fold constants. // TIntermTyped* typedReturnNode = 0; TIntermConstantUnion *leftTempConstant = left->getAsConstantUnion(); TIntermConstantUnion *rightTempConstant = right->getAsConstantUnion(); if (leftTempConstant && rightTempConstant) { typedReturnNode = leftTempConstant->fold(node->getOp(), rightTempConstant, infoSink); if (typedReturnNode) return typedReturnNode; } return node; } // // Connect two nodes through an assignment. // // Returns the added node. // TIntermTyped* TIntermediate::addAssign(TOperator op, TIntermTyped* left, TIntermTyped* right, const TSourceLoc& line) { // // Like adding binary math, except the conversion can only go // from right to left. // TIntermBinary* node = new TIntermBinary(op); node->setLine(line); TIntermTyped* child = addConversion(op, left->getType(), right); if (child == 0) return 0; node->setLeft(left); node->setRight(child); if (! node->promote(infoSink)) return 0; return node; } // // Connect two nodes through an index operator, where the left node is the base // of an array or struct, and the right node is a direct or indirect offset. // // Returns the added node. // The caller should set the type of the returned node. // TIntermTyped* TIntermediate::addIndex(TOperator op, TIntermTyped* base, TIntermTyped* index, const TSourceLoc& line) { TIntermBinary* node = new TIntermBinary(op); node->setLine(line); node->setLeft(base); node->setRight(index); // caller should set the type return node; } // // Add one node as the parent of another that it operates on. // // Returns the added node. // TIntermTyped* TIntermediate::addUnaryMath(TOperator op, TIntermNode* childNode, const TSourceLoc& line, TSymbolTable& symbolTable) { TIntermUnary* node; TIntermTyped* child = childNode->getAsTyped(); if (child == 0) { infoSink.info.message(EPrefixInternalError, line, "Bad type in AddUnaryMath"); return 0; } switch (op) { case EOpLogicalNot: if (child->getType().getBasicType() != EbtBool || child->getType().isMatrix() || child->getType().isArray() || child->getType().isVector()) { return 0; } break; case EOpPostIncrement: case EOpPreIncrement: case EOpPostDecrement: case EOpPreDecrement: case EOpNegative: if (child->getType().getBasicType() == EbtStruct || child->getType().isArray()) return 0; default: break; } // // Do we need to promote the operand? // // Note: Implicit promotions were removed from the language. // TBasicType newType = EbtVoid; switch (op) { case EOpConstructInt: newType = EbtInt; break; case EOpConstructBool: newType = EbtBool; break; case EOpConstructFloat: newType = EbtFloat; break; default: break; } if (newType != EbtVoid) { child = addConversion(op, TType(newType, child->getPrecision(), EvqTemporary, child->getNominalSize(), child->isMatrix(), child->isArray()), child); if (child == 0) return 0; } // // For constructors, we are now done, it's all in the conversion. // switch (op) { case EOpConstructInt: case EOpConstructBool: case EOpConstructFloat: return child; default: break; } TIntermConstantUnion *childTempConstant = 0; if (child->getAsConstantUnion()) childTempConstant = child->getAsConstantUnion(); // // Make a new node for the operator. // node = new TIntermUnary(op); node->setLine(line); node->setOperand(child); if (! node->promote(infoSink)) return 0; if (childTempConstant) { TIntermTyped* newChild = childTempConstant->fold(op, 0, infoSink); if (newChild) return newChild; } return node; } // // This is the safe way to change the operator on an aggregate, as it // does lots of error checking and fixing. Especially for establishing // a function call's operation on it's set of parameters. Sequences // of instructions are also aggregates, but they just direnctly set // their operator to EOpSequence. // // Returns an aggregate node, which could be the one passed in if // it was already an aggregate but no operator was set. // TIntermAggregate* TIntermediate::setAggregateOperator(TIntermNode* node, TOperator op, const TSourceLoc& line) { TIntermAggregate* aggNode; // // Make sure we have an aggregate. If not turn it into one. // if (node) { aggNode = node->getAsAggregate(); if (aggNode == 0 || aggNode->getOp() != EOpNull) { // // Make an aggregate containing this node. // aggNode = new TIntermAggregate(); aggNode->getSequence().push_back(node); } } else aggNode = new TIntermAggregate(); // // Set the operator. // aggNode->setOp(op); aggNode->setLine(line); return aggNode; } // // Convert one type to another. // // Returns the node representing the conversion, which could be the same // node passed in if no conversion was needed. // // Return 0 if a conversion can't be done. // TIntermTyped* TIntermediate::addConversion(TOperator op, const TType& type, TIntermTyped* node) { // // Does the base type allow operation? // switch (node->getBasicType()) { case EbtVoid: case EbtSampler2D: case EbtSamplerCube: return 0; default: break; } // // Otherwise, if types are identical, no problem // if (type == node->getType()) return node; // // If one's a structure, then no conversions. // if (type.getStruct() || node->getType().getStruct()) return 0; // // If one's an array, then no conversions. // if (type.isArray() || node->getType().isArray()) return 0; TBasicType promoteTo; switch (op) { // // Explicit conversions // case EOpConstructBool: promoteTo = EbtBool; break; case EOpConstructFloat: promoteTo = EbtFloat; break; case EOpConstructInt: promoteTo = EbtInt; break; default: // // implicit conversions were removed from the language. // if (type.getBasicType() != node->getType().getBasicType()) return 0; // // Size and structure could still differ, but that's // handled by operator promotion. // return node; } if (node->getAsConstantUnion()) { return (promoteConstantUnion(promoteTo, node->getAsConstantUnion())); } else { // // Add a new newNode for the conversion. // TIntermUnary* newNode = 0; TOperator newOp = EOpNull; switch (promoteTo) { case EbtFloat: switch (node->getBasicType()) { case EbtInt: newOp = EOpConvIntToFloat; break; case EbtBool: newOp = EOpConvBoolToFloat; break; default: infoSink.info.message(EPrefixInternalError, node->getLine(), "Bad promotion node"); return 0; } break; case EbtBool: switch (node->getBasicType()) { case EbtInt: newOp = EOpConvIntToBool; break; case EbtFloat: newOp = EOpConvFloatToBool; break; default: infoSink.info.message(EPrefixInternalError, node->getLine(), "Bad promotion node"); return 0; } break; case EbtInt: switch (node->getBasicType()) { case EbtBool: newOp = EOpConvBoolToInt; break; case EbtFloat: newOp = EOpConvFloatToInt; break; default: infoSink.info.message(EPrefixInternalError, node->getLine(), "Bad promotion node"); return 0; } break; default: infoSink.info.message(EPrefixInternalError, node->getLine(), "Bad promotion type"); return 0; } TType type(promoteTo, node->getPrecision(), EvqTemporary, node->getNominalSize(), node->isMatrix(), node->isArray()); newNode = new TIntermUnary(newOp, type); newNode->setLine(node->getLine()); newNode->setOperand(node); return newNode; } } // // Safe way to combine two nodes into an aggregate. Works with null pointers, // a node that's not a aggregate yet, etc. // // Returns the resulting aggregate, unless 0 was passed in for // both existing nodes. // TIntermAggregate* TIntermediate::growAggregate(TIntermNode* left, TIntermNode* right, const TSourceLoc& line) { if (left == 0 && right == 0) return 0; TIntermAggregate* aggNode = 0; if (left) aggNode = left->getAsAggregate(); if (!aggNode || aggNode->getOp() != EOpNull) { aggNode = new TIntermAggregate; if (left) aggNode->getSequence().push_back(left); } if (right) aggNode->getSequence().push_back(right); aggNode->setLine(line); return aggNode; } // // Turn an existing node into an aggregate. // // Returns an aggregate, unless 0 was passed in for the existing node. // TIntermAggregate* TIntermediate::makeAggregate(TIntermNode* node, const TSourceLoc& line) { if (node == 0) return 0; TIntermAggregate* aggNode = new TIntermAggregate; aggNode->getSequence().push_back(node); aggNode->setLine(line); return aggNode; } // // For "if" test nodes. There are three children; a condition, // a true path, and a false path. The two paths are in the // nodePair. // // Returns the selection node created. // TIntermNode* TIntermediate::addSelection(TIntermTyped* cond, TIntermNodePair nodePair, const TSourceLoc& line) { // // For compile time constant selections, prune the code and // test now. // if (cond->getAsTyped() && cond->getAsTyped()->getAsConstantUnion()) { if (cond->getAsConstantUnion()->getBConst(0) == true) return nodePair.node1 ? setAggregateOperator(nodePair.node1, EOpSequence, nodePair.node1->getLine()) : NULL; else return nodePair.node2 ? setAggregateOperator(nodePair.node2, EOpSequence, nodePair.node2->getLine()) : NULL; } TIntermSelection* node = new TIntermSelection(cond, nodePair.node1, nodePair.node2); node->setLine(line); return node; } TIntermTyped* TIntermediate::addComma(TIntermTyped* left, TIntermTyped* right, const TSourceLoc& line) { if (left->getType().getQualifier() == EvqConst && right->getType().getQualifier() == EvqConst) { return right; } else { TIntermTyped *commaAggregate = growAggregate(left, right, line); commaAggregate->getAsAggregate()->setOp(EOpComma); commaAggregate->setType(right->getType()); commaAggregate->getTypePointer()->setQualifier(EvqTemporary); return commaAggregate; } } // // For "?:" test nodes. There are three children; a condition, // a true path, and a false path. The two paths are specified // as separate parameters. // // Returns the selection node created, or 0 if one could not be. // TIntermTyped* TIntermediate::addSelection(TIntermTyped* cond, TIntermTyped* trueBlock, TIntermTyped* falseBlock, const TSourceLoc& line) { // // Get compatible types. // TIntermTyped* child = addConversion(EOpSequence, trueBlock->getType(), falseBlock); if (child) falseBlock = child; else { child = addConversion(EOpSequence, falseBlock->getType(), trueBlock); if (child) trueBlock = child; else return 0; } // // See if all the operands are constant, then fold it otherwise not. // if (cond->getAsConstantUnion() && trueBlock->getAsConstantUnion() && falseBlock->getAsConstantUnion()) { if (cond->getAsConstantUnion()->getBConst(0)) return trueBlock; else return falseBlock; } // // Make a selection node. // TIntermSelection* node = new TIntermSelection(cond, trueBlock, falseBlock, trueBlock->getType()); node->getTypePointer()->setQualifier(EvqTemporary); node->setLine(line); return node; } // // Constant terminal nodes. Has a union that contains bool, float or int constants // // Returns the constant union node created. // TIntermConstantUnion* TIntermediate::addConstantUnion(ConstantUnion* unionArrayPointer, const TType& t, const TSourceLoc& line) { TIntermConstantUnion* node = new TIntermConstantUnion(unionArrayPointer, t); node->setLine(line); return node; } TIntermTyped* TIntermediate::addSwizzle(TVectorFields& fields, const TSourceLoc& line) { TIntermAggregate* node = new TIntermAggregate(EOpSequence); node->setLine(line); TIntermConstantUnion* constIntNode; TIntermSequence &sequenceVector = node->getSequence(); ConstantUnion* unionArray; for (int i = 0; i < fields.num; i++) { unionArray = new ConstantUnion[1]; unionArray->setIConst(fields.offsets[i]); constIntNode = addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConst), line); sequenceVector.push_back(constIntNode); } return node; } // // Create loop nodes. // TIntermNode* TIntermediate::addLoop(TLoopType type, TIntermNode* init, TIntermTyped* cond, TIntermTyped* expr, TIntermNode* body, const TSourceLoc& line) { TIntermNode* node = new TIntermLoop(type, init, cond, expr, body); node->setLine(line); return node; } // // Add branches. // TIntermBranch* TIntermediate::addBranch(TOperator branchOp, const TSourceLoc& line) { return addBranch(branchOp, 0, line); } TIntermBranch* TIntermediate::addBranch(TOperator branchOp, TIntermTyped* expression, const TSourceLoc& line) { TIntermBranch* node = new TIntermBranch(branchOp, expression); node->setLine(line); return node; } // // This is to be executed once the final root is put on top by the parsing // process. // bool TIntermediate::postProcess(TIntermNode* root) { if (root == 0) return true; // // First, finish off the top level sequence, if any // TIntermAggregate* aggRoot = root->getAsAggregate(); if (aggRoot && aggRoot->getOp() == EOpNull) aggRoot->setOp(EOpSequence); return true; } // // This deletes the tree. // void TIntermediate::remove(TIntermNode* root) { if (root) RemoveAllTreeNodes(root); } //////////////////////////////////////////////////////////////// // // Member functions of the nodes used for building the tree. // //////////////////////////////////////////////////////////////// // // Say whether or not an operation node changes the value of a variable. // // Returns true if state is modified. // bool TIntermOperator::modifiesState() const { switch (op) { case EOpPostIncrement: case EOpPostDecrement: case EOpPreIncrement: case EOpPreDecrement: case EOpAssign: case EOpAddAssign: case EOpSubAssign: case EOpMulAssign: case EOpVectorTimesMatrixAssign: case EOpVectorTimesScalarAssign: case EOpMatrixTimesScalarAssign: case EOpMatrixTimesMatrixAssign: case EOpDivAssign: return true; default: return false; } } // // returns true if the operator is for one of the constructors // bool TIntermOperator::isConstructor() const { switch (op) { case EOpConstructVec2: case EOpConstructVec3: case EOpConstructVec4: case EOpConstructMat2: case EOpConstructMat3: case EOpConstructMat4: case EOpConstructFloat: case EOpConstructIVec2: case EOpConstructIVec3: case EOpConstructIVec4: case EOpConstructInt: case EOpConstructBVec2: case EOpConstructBVec3: case EOpConstructBVec4: case EOpConstructBool: case EOpConstructStruct: return true; default: return false; } } // // Make sure the type of a unary operator is appropriate for its // combination of operation and operand type. // // Returns false in nothing makes sense. // bool TIntermUnary::promote(TInfoSink&) { switch (op) { case EOpLogicalNot: if (operand->getBasicType() != EbtBool) return false; break; case EOpNegative: case EOpPostIncrement: case EOpPostDecrement: case EOpPreIncrement: case EOpPreDecrement: if (operand->getBasicType() == EbtBool) return false; break; // operators for built-ins are already type checked against their prototype case EOpAny: case EOpAll: case EOpVectorLogicalNot: return true; default: if (operand->getBasicType() != EbtFloat) return false; } setType(operand->getType()); type.setQualifier(EvqTemporary); return true; } // // Establishes the type of the resultant operation, as well as // makes the operator the correct one for the operands. // // Returns false if operator can't work on operands. // bool TIntermBinary::promote(TInfoSink& infoSink) { // This function only handles scalars, vectors, and matrices. if (left->isArray() || right->isArray()) { infoSink.info.message(EPrefixInternalError, getLine(), "Invalid operation for arrays"); return false; } // GLSL ES 2.0 does not support implicit type casting. // So the basic type should always match. if (left->getBasicType() != right->getBasicType()) return false; // // Base assumption: just make the type the same as the left // operand. Then only deviations from this need be coded. // setType(left->getType()); // The result gets promoted to the highest precision. TPrecision higherPrecision = GetHigherPrecision(left->getPrecision(), right->getPrecision()); getTypePointer()->setPrecision(higherPrecision); // Binary operations results in temporary variables unless both // operands are const. if (left->getQualifier() != EvqConst || right->getQualifier() != EvqConst) { getTypePointer()->setQualifier(EvqTemporary); } int size = std::max(left->getNominalSize(), right->getNominalSize()); // // All scalars. Code after this test assumes this case is removed! // if (size == 1) { switch (op) { // // Promote to conditional // case EOpEqual: case EOpNotEqual: case EOpLessThan: case EOpGreaterThan: case EOpLessThanEqual: case EOpGreaterThanEqual: setType(TType(EbtBool, EbpUndefined)); break; // // And and Or operate on conditionals // case EOpLogicalAnd: case EOpLogicalOr: // Both operands must be of type bool. if (left->getBasicType() != EbtBool || right->getBasicType() != EbtBool) return false; setType(TType(EbtBool, EbpUndefined)); break; default: break; } return true; } // If we reach here, at least one of the operands is vector or matrix. // The other operand could be a scalar, vector, or matrix. // Are the sizes compatible? // if (left->getNominalSize() != right->getNominalSize()) { // If the nominal size of operands do not match: // One of them must be scalar. if (left->getNominalSize() != 1 && right->getNominalSize() != 1) return false; // Operator cannot be of type pure assignment. if (op == EOpAssign || op == EOpInitialize) return false; } // // Can these two operands be combined? // TBasicType basicType = left->getBasicType(); switch (op) { case EOpMul: if (!left->isMatrix() && right->isMatrix()) { if (left->isVector()) op = EOpVectorTimesMatrix; else { op = EOpMatrixTimesScalar; setType(TType(basicType, higherPrecision, EvqTemporary, size, true)); } } else if (left->isMatrix() && !right->isMatrix()) { if (right->isVector()) { op = EOpMatrixTimesVector; setType(TType(basicType, higherPrecision, EvqTemporary, size, false)); } else { op = EOpMatrixTimesScalar; } } else if (left->isMatrix() && right->isMatrix()) { op = EOpMatrixTimesMatrix; } else if (!left->isMatrix() && !right->isMatrix()) { if (left->isVector() && right->isVector()) { // leave as component product } else if (left->isVector() || right->isVector()) { op = EOpVectorTimesScalar; setType(TType(basicType, higherPrecision, EvqTemporary, size, false)); } } else { infoSink.info.message(EPrefixInternalError, getLine(), "Missing elses"); return false; } break; case EOpMulAssign: if (!left->isMatrix() && right->isMatrix()) { if (left->isVector()) op = EOpVectorTimesMatrixAssign; else { return false; } } else if (left->isMatrix() && !right->isMatrix()) { if (right->isVector()) { return false; } else { op = EOpMatrixTimesScalarAssign; } } else if (left->isMatrix() && right->isMatrix()) { op = EOpMatrixTimesMatrixAssign; } else if (!left->isMatrix() && !right->isMatrix()) { if (left->isVector() && right->isVector()) { // leave as component product } else if (left->isVector() || right->isVector()) { if (! left->isVector()) return false; op = EOpVectorTimesScalarAssign; setType(TType(basicType, higherPrecision, EvqTemporary, size, false)); } } else { infoSink.info.message(EPrefixInternalError, getLine(), "Missing elses"); return false; } break; case EOpAssign: case EOpInitialize: case EOpAdd: case EOpSub: case EOpDiv: case EOpAddAssign: case EOpSubAssign: case EOpDivAssign: if ((left->isMatrix() && right->isVector()) || (left->isVector() && right->isMatrix())) return false; setType(TType(basicType, higherPrecision, EvqTemporary, size, left->isMatrix() || right->isMatrix())); break; case EOpEqual: case EOpNotEqual: case EOpLessThan: case EOpGreaterThan: case EOpLessThanEqual: case EOpGreaterThanEqual: if ((left->isMatrix() && right->isVector()) || (left->isVector() && right->isMatrix())) return false; setType(TType(EbtBool, EbpUndefined)); break; default: return false; } return true; } bool CompareStruct(const TType& leftNodeType, ConstantUnion* rightUnionArray, ConstantUnion* leftUnionArray) { const TTypeList* fields = leftNodeType.getStruct(); size_t structSize = fields->size(); size_t index = 0; for (size_t j = 0; j < structSize; j++) { size_t size = (*fields)[j]->getObjectSize(); for (size_t i = 0; i < size; i++) { if ((*fields)[j]->getBasicType() == EbtStruct) { if (!CompareStructure(*(*fields)[j], &rightUnionArray[index], &leftUnionArray[index])) return false; } else { if (leftUnionArray[index] != rightUnionArray[index]) return false; index++; } } } return true; } bool CompareStructure(const TType& leftNodeType, ConstantUnion* rightUnionArray, ConstantUnion* leftUnionArray) { if (leftNodeType.isArray()) { TType typeWithoutArrayness = leftNodeType; typeWithoutArrayness.clearArrayness(); size_t arraySize = leftNodeType.getArraySize(); for (size_t i = 0; i < arraySize; ++i) { size_t offset = typeWithoutArrayness.getObjectSize() * i; if (!CompareStruct(typeWithoutArrayness, &rightUnionArray[offset], &leftUnionArray[offset])) return false; } } else return CompareStruct(leftNodeType, rightUnionArray, leftUnionArray); return true; } // // The fold functions see if an operation on a constant can be done in place, // without generating run-time code. // // Returns the node to keep using, which may or may not be the node passed in. // TIntermTyped* TIntermConstantUnion::fold(TOperator op, TIntermTyped* constantNode, TInfoSink& infoSink) { ConstantUnion *unionArray = getUnionArrayPointer(); size_t objectSize = getType().getObjectSize(); if (constantNode) { // binary operations TIntermConstantUnion *node = constantNode->getAsConstantUnion(); ConstantUnion *rightUnionArray = node->getUnionArrayPointer(); TType returnType = getType(); // for a case like float f = 1.2 + vec4(2,3,4,5); if (constantNode->getType().getObjectSize() == 1 && objectSize > 1) { rightUnionArray = new ConstantUnion[objectSize]; for (size_t i = 0; i < objectSize; ++i) rightUnionArray[i] = *node->getUnionArrayPointer(); returnType = getType(); } else if (constantNode->getType().getObjectSize() > 1 && objectSize == 1) { // for a case like float f = vec4(2,3,4,5) + 1.2; unionArray = new ConstantUnion[constantNode->getType().getObjectSize()]; for (size_t i = 0; i < constantNode->getType().getObjectSize(); ++i) unionArray[i] = *getUnionArrayPointer(); returnType = node->getType(); objectSize = constantNode->getType().getObjectSize(); } ConstantUnion* tempConstArray = 0; TIntermConstantUnion *tempNode; bool boolNodeFlag = false; switch(op) { case EOpAdd: tempConstArray = new ConstantUnion[objectSize]; {// support MSVC++6.0 for (size_t i = 0; i < objectSize; i++) tempConstArray[i] = unionArray[i] + rightUnionArray[i]; } break; case EOpSub: tempConstArray = new ConstantUnion[objectSize]; {// support MSVC++6.0 for (size_t i = 0; i < objectSize; i++) tempConstArray[i] = unionArray[i] - rightUnionArray[i]; } break; case EOpMul: case EOpVectorTimesScalar: case EOpMatrixTimesScalar: tempConstArray = new ConstantUnion[objectSize]; {// support MSVC++6.0 for (size_t i = 0; i < objectSize; i++) tempConstArray[i] = unionArray[i] * rightUnionArray[i]; } break; case EOpMatrixTimesMatrix: if (getType().getBasicType() != EbtFloat || node->getBasicType() != EbtFloat) { infoSink.info.message(EPrefixInternalError, getLine(), "Constant Folding cannot be done for matrix multiply"); return 0; } {// support MSVC++6.0 int size = getNominalSize(); tempConstArray = new ConstantUnion[size*size]; for (int row = 0; row < size; row++) { for (int column = 0; column < size; column++) { tempConstArray[size * column + row].setFConst(0.0f); for (int i = 0; i < size; i++) { tempConstArray[size * column + row].setFConst(tempConstArray[size * column + row].getFConst() + unionArray[i * size + row].getFConst() * (rightUnionArray[column * size + i].getFConst())); } } } } break; case EOpDiv: tempConstArray = new ConstantUnion[objectSize]; {// support MSVC++6.0 for (size_t i = 0; i < objectSize; i++) { switch (getType().getBasicType()) { case EbtFloat: if (rightUnionArray[i] == 0.0f) { infoSink.info.message(EPrefixWarning, getLine(), "Divide by zero error during constant folding"); tempConstArray[i].setFConst(unionArray[i].getFConst() < 0 ? -FLT_MAX : FLT_MAX); } else tempConstArray[i].setFConst(unionArray[i].getFConst() / rightUnionArray[i].getFConst()); break; case EbtInt: if (rightUnionArray[i] == 0) { infoSink.info.message(EPrefixWarning, getLine(), "Divide by zero error during constant folding"); tempConstArray[i].setIConst(INT_MAX); } else tempConstArray[i].setIConst(unionArray[i].getIConst() / rightUnionArray[i].getIConst()); break; default: infoSink.info.message(EPrefixInternalError, getLine(), "Constant folding cannot be done for \"/\""); return 0; } } } break; case EOpMatrixTimesVector: if (node->getBasicType() != EbtFloat) { infoSink.info.message(EPrefixInternalError, getLine(), "Constant Folding cannot be done for matrix times vector"); return 0; } tempConstArray = new ConstantUnion[getNominalSize()]; {// support MSVC++6.0 for (int size = getNominalSize(), i = 0; i < size; i++) { tempConstArray[i].setFConst(0.0f); for (int j = 0; j < size; j++) { tempConstArray[i].setFConst(tempConstArray[i].getFConst() + ((unionArray[j*size + i].getFConst()) * rightUnionArray[j].getFConst())); } } } tempNode = new TIntermConstantUnion(tempConstArray, node->getType()); tempNode->setLine(getLine()); return tempNode; case EOpVectorTimesMatrix: if (getType().getBasicType() != EbtFloat) { infoSink.info.message(EPrefixInternalError, getLine(), "Constant Folding cannot be done for vector times matrix"); return 0; } tempConstArray = new ConstantUnion[getNominalSize()]; {// support MSVC++6.0 for (int size = getNominalSize(), i = 0; i < size; i++) { tempConstArray[i].setFConst(0.0f); for (int j = 0; j < size; j++) { tempConstArray[i].setFConst(tempConstArray[i].getFConst() + ((unionArray[j].getFConst()) * rightUnionArray[i*size + j].getFConst())); } } } break; case EOpLogicalAnd: // this code is written for possible future use, will not get executed currently tempConstArray = new ConstantUnion[objectSize]; {// support MSVC++6.0 for (size_t i = 0; i < objectSize; i++) tempConstArray[i] = unionArray[i] && rightUnionArray[i]; } break; case EOpLogicalOr: // this code is written for possible future use, will not get executed currently tempConstArray = new ConstantUnion[objectSize]; {// support MSVC++6.0 for (size_t i = 0; i < objectSize; i++) tempConstArray[i] = unionArray[i] || rightUnionArray[i]; } break; case EOpLogicalXor: tempConstArray = new ConstantUnion[objectSize]; {// support MSVC++6.0 for (size_t i = 0; i < objectSize; i++) switch (getType().getBasicType()) { case EbtBool: tempConstArray[i].setBConst((unionArray[i] == rightUnionArray[i]) ? false : true); break; default: assert(false && "Default missing"); } } break; case EOpLessThan: assert(objectSize == 1); tempConstArray = new ConstantUnion[1]; tempConstArray->setBConst(*unionArray < *rightUnionArray); returnType = TType(EbtBool, EbpUndefined, EvqConst); break; case EOpGreaterThan: assert(objectSize == 1); tempConstArray = new ConstantUnion[1]; tempConstArray->setBConst(*unionArray > *rightUnionArray); returnType = TType(EbtBool, EbpUndefined, EvqConst); break; case EOpLessThanEqual: { assert(objectSize == 1); ConstantUnion constant; constant.setBConst(*unionArray > *rightUnionArray); tempConstArray = new ConstantUnion[1]; tempConstArray->setBConst(!constant.getBConst()); returnType = TType(EbtBool, EbpUndefined, EvqConst); break; } case EOpGreaterThanEqual: { assert(objectSize == 1); ConstantUnion constant; constant.setBConst(*unionArray < *rightUnionArray); tempConstArray = new ConstantUnion[1]; tempConstArray->setBConst(!constant.getBConst()); returnType = TType(EbtBool, EbpUndefined, EvqConst); break; } case EOpEqual: if (getType().getBasicType() == EbtStruct) { if (!CompareStructure(node->getType(), node->getUnionArrayPointer(), unionArray)) boolNodeFlag = true; } else { for (size_t i = 0; i < objectSize; i++) { if (unionArray[i] != rightUnionArray[i]) { boolNodeFlag = true; break; // break out of for loop } } } tempConstArray = new ConstantUnion[1]; if (!boolNodeFlag) { tempConstArray->setBConst(true); } else { tempConstArray->setBConst(false); } tempNode = new TIntermConstantUnion(tempConstArray, TType(EbtBool, EbpUndefined, EvqConst)); tempNode->setLine(getLine()); return tempNode; case EOpNotEqual: if (getType().getBasicType() == EbtStruct) { if (CompareStructure(node->getType(), node->getUnionArrayPointer(), unionArray)) boolNodeFlag = true; } else { for (size_t i = 0; i < objectSize; i++) { if (unionArray[i] == rightUnionArray[i]) { boolNodeFlag = true; break; // break out of for loop } } } tempConstArray = new ConstantUnion[1]; if (!boolNodeFlag) { tempConstArray->setBConst(true); } else { tempConstArray->setBConst(false); } tempNode = new TIntermConstantUnion(tempConstArray, TType(EbtBool, EbpUndefined, EvqConst)); tempNode->setLine(getLine()); return tempNode; default: infoSink.info.message(EPrefixInternalError, getLine(), "Invalid operator for constant folding"); return 0; } tempNode = new TIntermConstantUnion(tempConstArray, returnType); tempNode->setLine(getLine()); return tempNode; } else { // // Do unary operations // TIntermConstantUnion *newNode = 0; ConstantUnion* tempConstArray = new ConstantUnion[objectSize]; for (size_t i = 0; i < objectSize; i++) { switch(op) { case EOpNegative: switch (getType().getBasicType()) { case EbtFloat: tempConstArray[i].setFConst(-unionArray[i].getFConst()); break; case EbtInt: tempConstArray[i].setIConst(-unionArray[i].getIConst()); break; default: infoSink.info.message(EPrefixInternalError, getLine(), "Unary operation not folded into constant"); return 0; } break; case EOpLogicalNot: // this code is written for possible future use, will not get executed currently switch (getType().getBasicType()) { case EbtBool: tempConstArray[i].setBConst(!unionArray[i].getBConst()); break; default: infoSink.info.message(EPrefixInternalError, getLine(), "Unary operation not folded into constant"); return 0; } break; default: return 0; } } newNode = new TIntermConstantUnion(tempConstArray, getType()); newNode->setLine(getLine()); return newNode; } } TIntermTyped* TIntermediate::promoteConstantUnion(TBasicType promoteTo, TIntermConstantUnion* node) { size_t size = node->getType().getObjectSize(); ConstantUnion *leftUnionArray = new ConstantUnion[size]; for (size_t i = 0; i < size; i++) { switch (promoteTo) { case EbtFloat: switch (node->getType().getBasicType()) { case EbtInt: leftUnionArray[i].setFConst(static_cast<float>(node->getIConst(i))); break; case EbtBool: leftUnionArray[i].setFConst(static_cast<float>(node->getBConst(i))); break; case EbtFloat: leftUnionArray[i].setFConst(static_cast<float>(node->getFConst(i))); break; default: infoSink.info.message(EPrefixInternalError, node->getLine(), "Cannot promote"); return 0; } break; case EbtInt: switch (node->getType().getBasicType()) { case EbtInt: leftUnionArray[i].setIConst(static_cast<int>(node->getIConst(i))); break; case EbtBool: leftUnionArray[i].setIConst(static_cast<int>(node->getBConst(i))); break; case EbtFloat: leftUnionArray[i].setIConst(static_cast<int>(node->getFConst(i))); break; default: infoSink.info.message(EPrefixInternalError, node->getLine(), "Cannot promote"); return 0; } break; case EbtBool: switch (node->getType().getBasicType()) { case EbtInt: leftUnionArray[i].setBConst(node->getIConst(i) != 0); break; case EbtBool: leftUnionArray[i].setBConst(node->getBConst(i)); break; case EbtFloat: leftUnionArray[i].setBConst(node->getFConst(i) != 0.0f); break; default: infoSink.info.message(EPrefixInternalError, node->getLine(), "Cannot promote"); return 0; } break; default: infoSink.info.message(EPrefixInternalError, node->getLine(), "Incorrect data type found"); return 0; } } const TType& t = node->getType(); return addConstantUnion(leftUnionArray, TType(promoteTo, t.getPrecision(), t.getQualifier(), t.getNominalSize(), t.isMatrix(), t.isArray()), node->getLine()); } // static TString TIntermTraverser::hash(const TString& name, ShHashFunction64 hashFunction) { if (hashFunction == NULL || name.empty()) return name; khronos_uint64_t number = (*hashFunction)(name.c_str(), name.length()); TStringStream stream; stream << HASHED_NAME_PREFIX << std::hex << number; TString hashedName = stream.str(); return hashedName; }
C++
// // Copyright (c) 2002-2011 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_TRANSLATORESSL_H_ #define COMPILER_TRANSLATORESSL_H_ #include "compiler/ShHandle.h" class TranslatorESSL : public TCompiler { public: TranslatorESSL(ShShaderType type, ShShaderSpec spec); protected: virtual void translate(TIntermNode* root); private: void writeExtensionBehavior(); }; #endif // COMPILER_TRANSLATORESSL_H_
C++
// // Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_OUTPUTHLSL_H_ #define COMPILER_OUTPUTHLSL_H_ #include <list> #include <set> #include <map> #define GL_APICALL #include <GLES2/gl2.h> #include "compiler/intermediate.h" #include "compiler/ParseHelper.h" #include "compiler/Uniform.h" namespace sh { class UnfoldShortCircuit; class OutputHLSL : public TIntermTraverser { public: OutputHLSL(TParseContext &context, const ShBuiltInResources& resources, ShShaderOutput outputType); ~OutputHLSL(); void output(); TInfoSinkBase &getBodyStream(); const ActiveUniforms &getUniforms(); TString typeString(const TType &type); TString textureString(const TType &type); static TString qualifierString(TQualifier qualifier); static TString arrayString(const TType &type); static TString initializer(const TType &type); static TString decorate(const TString &string); // Prepends an underscore to avoid naming clashes static TString decorateUniform(const TString &string, const TType &type); static TString decorateField(const TString &string, const TType &structure); protected: void header(); // Visit AST nodes and output their code to the body stream void visitSymbol(TIntermSymbol*); void visitConstantUnion(TIntermConstantUnion*); bool visitBinary(Visit visit, TIntermBinary*); bool visitUnary(Visit visit, TIntermUnary*); bool visitSelection(Visit visit, TIntermSelection*); bool visitAggregate(Visit visit, TIntermAggregate*); bool visitLoop(Visit visit, TIntermLoop*); bool visitBranch(Visit visit, TIntermBranch*); void traverseStatements(TIntermNode *node); bool isSingleStatement(TIntermNode *node); bool handleExcessiveLoop(TIntermLoop *node); void outputTriplet(Visit visit, const TString &preString, const TString &inString, const TString &postString); void outputLineDirective(int line); TString argumentString(const TIntermSymbol *symbol); int vectorSize(const TType &type) const; void addConstructor(const TType &type, const TString &name, const TIntermSequence *parameters); const ConstantUnion *writeConstantUnion(const TType &type, const ConstantUnion *constUnion); TString scopeString(unsigned int depthLimit); TString scopedStruct(const TString &typeName); TString structLookup(const TString &typeName); TParseContext &mContext; const ShShaderOutput mOutputType; UnfoldShortCircuit *mUnfoldShortCircuit; bool mInsideFunction; // Output streams TInfoSinkBase mHeader; TInfoSinkBase mBody; TInfoSinkBase mFooter; typedef std::map<TString, TIntermSymbol*> ReferencedSymbols; ReferencedSymbols mReferencedUniforms; ReferencedSymbols mReferencedAttributes; ReferencedSymbols mReferencedVaryings; // Parameters determining what goes in the header output bool mUsesTexture2D; bool mUsesTexture2D_bias; bool mUsesTexture2DLod; bool mUsesTexture2DProj; bool mUsesTexture2DProj_bias; bool mUsesTexture2DProjLod; bool mUsesTextureCube; bool mUsesTextureCube_bias; bool mUsesTextureCubeLod; bool mUsesTexture2DLod0; bool mUsesTexture2DLod0_bias; bool mUsesTexture2DProjLod0; bool mUsesTexture2DProjLod0_bias; bool mUsesTextureCubeLod0; bool mUsesTextureCubeLod0_bias; bool mUsesFragColor; bool mUsesFragData; bool mUsesDepthRange; bool mUsesFragCoord; bool mUsesPointCoord; bool mUsesFrontFacing; bool mUsesPointSize; bool mUsesFragDepth; bool mUsesXor; bool mUsesMod1; bool mUsesMod2v; bool mUsesMod2f; bool mUsesMod3v; bool mUsesMod3f; bool mUsesMod4v; bool mUsesMod4f; bool mUsesFaceforward1; bool mUsesFaceforward2; bool mUsesFaceforward3; bool mUsesFaceforward4; bool mUsesEqualMat2; bool mUsesEqualMat3; bool mUsesEqualMat4; bool mUsesEqualVec2; bool mUsesEqualVec3; bool mUsesEqualVec4; bool mUsesEqualIVec2; bool mUsesEqualIVec3; bool mUsesEqualIVec4; bool mUsesEqualBVec2; bool mUsesEqualBVec3; bool mUsesEqualBVec4; bool mUsesAtan2_1; bool mUsesAtan2_2; bool mUsesAtan2_3; bool mUsesAtan2_4; int mNumRenderTargets; typedef std::set<TString> Constructors; Constructors mConstructors; typedef std::set<TString> StructNames; StructNames mStructNames; typedef std::list<TString> StructDeclarations; StructDeclarations mStructDeclarations; typedef std::vector<int> ScopeBracket; ScopeBracket mScopeBracket; unsigned int mScopeDepth; int mUniqueIndex; // For creating unique names bool mContainsLoopDiscontinuity; bool mOutputLod0Function; bool mInsideDiscontinuousLoop; TIntermSymbol *mExcessiveLoopIndex; int mUniformRegister; int mSamplerRegister; TString registerString(TIntermSymbol *operand); int samplerRegister(TIntermSymbol *sampler); int uniformRegister(TIntermSymbol *uniform); void declareUniform(const TType &type, const TString &name, int index); static GLenum glVariableType(const TType &type); static GLenum glVariablePrecision(const TType &type); ActiveUniforms mActiveUniforms; }; } #endif // COMPILER_OUTPUTHLSL_H_
C++
// // Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef _TYPES_INCLUDED #define _TYPES_INCLUDED #include "compiler/BaseTypes.h" #include "compiler/Common.h" #include "compiler/debug.h" class TType; struct TPublicType; typedef TVector<TType*> TTypeList; inline TTypeList* NewPoolTTypeList() { void* memory = GlobalPoolAllocator.allocate(sizeof(TTypeList)); return new(memory) TTypeList; } // // Base class for things that have a type. // class TType { public: POOL_ALLOCATOR_NEW_DELETE(GlobalPoolAllocator) TType() {} TType(TBasicType t, TPrecision p, TQualifier q = EvqTemporary, int s = 1, bool m = false, bool a = false) : type(t), precision(p), qualifier(q), size(s), matrix(m), array(a), arraySize(0), structure(0), structureSize(0), deepestStructNesting(0), fieldName(0), mangled(0), typeName(0) { } explicit TType(const TPublicType &p); TType(TTypeList* userDef, const TString& n, TPrecision p = EbpUndefined) : type(EbtStruct), precision(p), qualifier(EvqTemporary), size(1), matrix(false), array(false), arraySize(0), structure(userDef), structureSize(0), deepestStructNesting(0), fieldName(0), mangled(0) { typeName = NewPoolTString(n.c_str()); } TBasicType getBasicType() const { return type; } void setBasicType(TBasicType t) { type = t; } TPrecision getPrecision() const { return precision; } void setPrecision(TPrecision p) { precision = p; } TQualifier getQualifier() const { return qualifier; } void setQualifier(TQualifier q) { qualifier = q; } // One-dimensional size of single instance type int getNominalSize() const { return size; } void setNominalSize(int s) { size = s; } // Full size of single instance of type size_t getObjectSize() const; int elementRegisterCount() const { TTypeList *structure = getStruct(); if (structure) { int registerCount = 0; for (size_t i = 0; i < structure->size(); i++) { registerCount += (*structure)[i]->totalRegisterCount(); } return registerCount; } else if (isMatrix()) { return getNominalSize(); } else { return 1; } } int totalRegisterCount() const { if (array) { return arraySize * elementRegisterCount(); } else { return elementRegisterCount(); } } bool isMatrix() const { return matrix ? true : false; } void setMatrix(bool m) { matrix = m; } bool isArray() const { return array ? true : false; } int getArraySize() const { return arraySize; } void setArraySize(int s) { array = true; arraySize = s; } void clearArrayness() { array = false; arraySize = 0; } bool isVector() const { return size > 1 && !matrix; } bool isScalar() const { return size == 1 && !matrix && !structure; } TTypeList* getStruct() const { return structure; } void setStruct(TTypeList* s) { structure = s; computeDeepestStructNesting(); } const TString& getTypeName() const { assert(typeName); return *typeName; } void setTypeName(const TString& n) { typeName = NewPoolTString(n.c_str()); } bool isField() const { return fieldName != 0; } const TString& getFieldName() const { assert(fieldName); return *fieldName; } void setFieldName(const TString& n) { fieldName = NewPoolTString(n.c_str()); } TString& getMangledName() { if (!mangled) { mangled = NewPoolTString(""); buildMangledName(*mangled); *mangled += ';' ; } return *mangled; } bool sameElementType(const TType& right) const { return type == right.type && size == right.size && matrix == right.matrix && structure == right.structure; } bool operator==(const TType& right) const { return type == right.type && size == right.size && matrix == right.matrix && array == right.array && (!array || arraySize == right.arraySize) && structure == right.structure; // don't check the qualifier, it's not ever what's being sought after } bool operator!=(const TType& right) const { return !operator==(right); } bool operator<(const TType& right) const { if (type != right.type) return type < right.type; if (size != right.size) return size < right.size; if (matrix != right.matrix) return matrix < right.matrix; if (array != right.array) return array < right.array; if (arraySize != right.arraySize) return arraySize < right.arraySize; if (structure != right.structure) return structure < right.structure; return false; } const char* getBasicString() const { return ::getBasicString(type); } const char* getPrecisionString() const { return ::getPrecisionString(precision); } const char* getQualifierString() const { return ::getQualifierString(qualifier); } TString getCompleteString() const; // If this type is a struct, returns the deepest struct nesting of // any field in the struct. For example: // struct nesting1 { // vec4 position; // }; // struct nesting2 { // nesting1 field1; // vec4 field2; // }; // For type "nesting2", this method would return 2 -- the number // of structures through which indirection must occur to reach the // deepest field (nesting2.field1.position). int getDeepestStructNesting() const { return deepestStructNesting; } bool isStructureContainingArrays() const; private: void buildMangledName(TString&); size_t getStructSize() const; void computeDeepestStructNesting(); TBasicType type : 6; TPrecision precision; TQualifier qualifier : 7; int size : 8; // size of vector or matrix, not size of array unsigned int matrix : 1; unsigned int array : 1; int arraySize; TTypeList* structure; // 0 unless this is a struct mutable size_t structureSize; int deepestStructNesting; TString *fieldName; // for structure field names TString *mangled; TString *typeName; // for structure field type name }; // // This is a workaround for a problem with the yacc stack, It can't have // types that it thinks have non-trivial constructors. It should // just be used while recognizing the grammar, not anything else. Pointers // could be used, but also trying to avoid lots of memory management overhead. // // Not as bad as it looks, there is no actual assumption that the fields // match up or are name the same or anything like that. // struct TPublicType { TBasicType type; TQualifier qualifier; TPrecision precision; int size; // size of vector or matrix, not size of array bool matrix; bool array; int arraySize; TType* userDef; TSourceLoc line; void setBasic(TBasicType bt, TQualifier q, const TSourceLoc& ln) { type = bt; qualifier = q; precision = EbpUndefined; size = 1; matrix = false; array = false; arraySize = 0; userDef = 0; line = ln; } void setAggregate(int s, bool m = false) { size = s; matrix = m; } void setArray(bool a, int s = 0) { array = a; arraySize = s; } bool isStructureContainingArrays() const { if (!userDef) { return false; } return userDef->isStructureContainingArrays(); } }; #endif // _TYPES_INCLUDED_
C++
// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/intermediate.h" class TAliveTraverser : public TIntermTraverser { public: TAliveTraverser(TQualifier q) : TIntermTraverser(true, false, false, true), found(false), qualifier(q) { } bool wasFound() { return found; } protected: bool found; TQualifier qualifier; void visitSymbol(TIntermSymbol*); bool visitSelection(Visit, TIntermSelection*); }; // // 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 TAliveTraverser::visitSymbol(TIntermSymbol* node) { // // If it's what we're looking for, record it. // if (node->getQualifier() == qualifier) found = true; } bool TAliveTraverser::visitSelection(Visit preVisit, TIntermSelection* node) { if (wasFound()) return false; return true; }
C++
// // Copyright (c) 2002-2011 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef CROSSCOMPILERGLSL_OUTPUTESSL_H_ #define CROSSCOMPILERGLSL_OUTPUTESSL_H_ #include "compiler/OutputGLSLBase.h" class TOutputESSL : public TOutputGLSLBase { public: TOutputESSL(TInfoSinkBase& objSink, ShArrayIndexClampingStrategy clampingStrategy, ShHashFunction64 hashFunction, NameMap& nameMap, TSymbolTable& symbolTable); protected: virtual bool writeVariablePrecision(TPrecision precision); }; #endif // CROSSCOMPILERGLSL_OUTPUTESSL_H_
C++
// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // SearchSymbol is an AST traverser to detect the use of a given symbol name // #include "compiler/SearchSymbol.h" #include "compiler/InfoSink.h" #include "compiler/OutputHLSL.h" namespace sh { SearchSymbol::SearchSymbol(const TString &symbol) : mSymbol(symbol) { match = false; } void SearchSymbol::traverse(TIntermNode *node) { node->traverse(this); } void SearchSymbol::visitSymbol(TIntermSymbol *symbolNode) { if (symbolNode->getSymbol() == mSymbol) { match = true; } } bool SearchSymbol::foundMatch() const { return match; } }
C++
// // Copyright (c) 2011 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/intermediate.h" struct TLoopIndexInfo { int id; int initValue; int stopValue; int incrementValue; TOperator op; int currentValue; }; class ForLoopUnroll { public: ForLoopUnroll() { } void FillLoopIndexInfo(TIntermLoop* node, TLoopIndexInfo& info); // Update the info.currentValue for the next loop iteration. void Step(); // Return false if loop condition is no longer satisfied. bool SatisfiesLoopCondition(); // Check if the symbol is the index of a loop that's unrolled. bool NeedsToReplaceSymbolWithValue(TIntermSymbol* symbol); // Return the current value of a given loop index symbol. int GetLoopIndexValue(TIntermSymbol* symbol); void Push(TLoopIndexInfo& info); void Pop(); static void MarkForLoopsWithIntegerIndicesForUnrolling(TIntermNode* root); private: int getLoopIncrement(TIntermLoop* node); int evaluateIntConstant(TIntermConstantUnion* node); TVector<TLoopIndexInfo> mLoopIndexStack; };
C++
// // Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_MAP_LONG_VARIABLE_NAMES_H_ #define COMPILER_MAP_LONG_VARIABLE_NAMES_H_ #include "GLSLANG/ShaderLang.h" #include "compiler/intermediate.h" #include "compiler/VariableInfo.h" // This size does not include '\0' in the end. #define MAX_SHORTENED_IDENTIFIER_SIZE 32 // This is a ref-counted singleton. GetInstance() returns a pointer to the // singleton, and after use, call Release(). GetInstance() and Release() should // be paired. class LongNameMap { public: static LongNameMap* GetInstance(); void Release(); // Return the mapped name if <originalName, mappedName> is in the map; // otherwise, return NULL. const char* Find(const char* originalName) const; // Insert a pair into the map. void Insert(const char* originalName, const char* mappedName); // Return the number of entries in the map. size_t Size() const; private: LongNameMap(); ~LongNameMap(); size_t refCount; std::map<std::string, std::string> mLongNameMap; }; // Traverses intermediate tree to map attributes and uniforms names that are // longer than MAX_SHORTENED_IDENTIFIER_SIZE to MAX_SHORTENED_IDENTIFIER_SIZE. class MapLongVariableNames : public TIntermTraverser { public: MapLongVariableNames(LongNameMap* globalMap); virtual void visitSymbol(TIntermSymbol*); virtual bool visitLoop(Visit, TIntermLoop*); private: TString mapGlobalLongName(const TString& name); LongNameMap* mGlobalMap; }; #endif // COMPILER_MAP_LONG_VARIABLE_NAMES_H_
C++
/* A Bison parser, made by GNU Bison 2.7. */ /* Bison implementation for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2012 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "2.7" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 1 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* Copy the first part of user declarations. */ // // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // This file is auto-generated by generate_parser.sh. DO NOT EDIT! // Ignore errors in auto-generated code. #if defined(__GNUC__) #pragma GCC diagnostic ignored "-Wunused-function" #pragma GCC diagnostic ignored "-Wunused-variable" #pragma GCC diagnostic ignored "-Wswitch-enum" #elif defined(_MSC_VER) #pragma warning(disable: 4065) #pragma warning(disable: 4189) #pragma warning(disable: 4505) #pragma warning(disable: 4701) #endif #include "compiler/SymbolTable.h" #include "compiler/ParseHelper.h" #include "GLSLANG/ShaderLang.h" #define YYENABLE_NLS 0 #define YYLEX_PARAM context->scanner # ifndef YY_NULL # if defined __cplusplus && 201103L <= __cplusplus # define YY_NULL nullptr # else # define YY_NULL 0 # endif # endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* In a future release of Bison, this section will be replaced by #include "glslang_tab.h". */ #ifndef YY_YY_GLSLANG_TAB_H_INCLUDED # define YY_YY_GLSLANG_TAB_H_INCLUDED /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int yydebug; #endif /* "%code requires" blocks. */ #define YYLTYPE TSourceLoc #define YYLTYPE_IS_DECLARED 1 /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { INVARIANT = 258, HIGH_PRECISION = 259, MEDIUM_PRECISION = 260, LOW_PRECISION = 261, PRECISION = 262, ATTRIBUTE = 263, CONST_QUAL = 264, BOOL_TYPE = 265, FLOAT_TYPE = 266, INT_TYPE = 267, BREAK = 268, CONTINUE = 269, DO = 270, ELSE = 271, FOR = 272, IF = 273, DISCARD = 274, RETURN = 275, BVEC2 = 276, BVEC3 = 277, BVEC4 = 278, IVEC2 = 279, IVEC3 = 280, IVEC4 = 281, VEC2 = 282, VEC3 = 283, VEC4 = 284, MATRIX2 = 285, MATRIX3 = 286, MATRIX4 = 287, IN_QUAL = 288, OUT_QUAL = 289, INOUT_QUAL = 290, UNIFORM = 291, VARYING = 292, STRUCT = 293, VOID_TYPE = 294, WHILE = 295, SAMPLER2D = 296, SAMPLERCUBE = 297, SAMPLER_EXTERNAL_OES = 298, SAMPLER2DRECT = 299, IDENTIFIER = 300, TYPE_NAME = 301, FLOATCONSTANT = 302, INTCONSTANT = 303, BOOLCONSTANT = 304, LEFT_OP = 305, RIGHT_OP = 306, INC_OP = 307, DEC_OP = 308, LE_OP = 309, GE_OP = 310, EQ_OP = 311, NE_OP = 312, AND_OP = 313, OR_OP = 314, XOR_OP = 315, MUL_ASSIGN = 316, DIV_ASSIGN = 317, ADD_ASSIGN = 318, MOD_ASSIGN = 319, LEFT_ASSIGN = 320, RIGHT_ASSIGN = 321, AND_ASSIGN = 322, XOR_ASSIGN = 323, OR_ASSIGN = 324, SUB_ASSIGN = 325, LEFT_PAREN = 326, RIGHT_PAREN = 327, LEFT_BRACKET = 328, RIGHT_BRACKET = 329, LEFT_BRACE = 330, RIGHT_BRACE = 331, DOT = 332, COMMA = 333, COLON = 334, EQUAL = 335, SEMICOLON = 336, BANG = 337, DASH = 338, TILDE = 339, PLUS = 340, STAR = 341, SLASH = 342, PERCENT = 343, LEFT_ANGLE = 344, RIGHT_ANGLE = 345, VERTICAL_BAR = 346, CARET = 347, AMPERSAND = 348, QUESTION = 349 }; #endif #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE { struct { union { TString *string; float f; int i; bool b; }; TSymbol* symbol; } lex; struct { TOperator op; union { TIntermNode* intermNode; TIntermNodePair nodePair; TIntermTyped* intermTypedNode; TIntermAggregate* intermAggregate; }; union { TPublicType type; TPrecision precision; TQualifier qualifier; TFunction* function; TParameter param; TType* field; TTypeList* structure; }; } interm; } YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 #endif #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; } YYLTYPE; # define yyltype YYLTYPE /* obsolescent; will be withdrawn */ # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); #else int yyparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int yyparse (TParseContext* context); #else int yyparse (); #endif #endif /* ! YYPARSE_PARAM */ #endif /* !YY_YY_GLSLANG_TAB_H_INCLUDED */ /* Copy the second part of user declarations. */ extern int yylex(YYSTYPE* yylval, YYLTYPE* yylloc, void* yyscanner); static void yyerror(YYLTYPE* yylloc, TParseContext* context, const char* reason); #define YYLLOC_DEFAULT(Current, Rhs, N) \ do { \ if (YYID(N)) { \ (Current).first_file = YYRHSLOC(Rhs, 1).first_file; \ (Current).first_line = YYRHSLOC(Rhs, 1).first_line; \ (Current).last_file = YYRHSLOC(Rhs, N).last_file; \ (Current).last_line = YYRHSLOC(Rhs, N).last_line; \ } \ else { \ (Current).first_file = YYRHSLOC(Rhs, 0).last_file; \ (Current).first_line = YYRHSLOC(Rhs, 0).last_line; \ (Current).last_file = YYRHSLOC(Rhs, 0).last_file; \ (Current).last_line = YYRHSLOC(Rhs, 0).last_line; \ } \ } while (0) #define VERTEX_ONLY(S, L) { \ if (context->shaderType != SH_VERTEX_SHADER) { \ context->error(L, " supported in vertex shaders only ", S); \ context->recover(); \ } \ } #define FRAG_ONLY(S, L) { \ if (context->shaderType != SH_FRAGMENT_SHADER) { \ context->error(L, " supported in fragment shaders only ", S); \ context->recover(); \ } \ } #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #elif (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) typedef signed char yytype_int8; #else typedef short int yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(Msgid) dgettext ("bison-runtime", Msgid) # endif # endif # ifndef YY_ # define YY_(Msgid) Msgid # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(E) ((void) (E)) #else # define YYUSE(E) /* empty */ #endif /* Identity function, used to suppress warnings about constant conditions. */ #ifndef lint # define YYID(N) (N) #else #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static int YYID (int yyi) #else static int YYID (yyi) int yyi; #endif { return yyi; } #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ /* Use EXIT_SUCCESS as a witness for stdlib.h. */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's `empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL \ && defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss_alloc; YYSTYPE yyvs_alloc; YYLTYPE yyls_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE) + sizeof (YYLTYPE)) \ + 2 * YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (YYID (0)) #endif #if defined YYCOPY_NEEDED && YYCOPY_NEEDED /* Copy COUNT objects from SRC to DST. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(Dst, Src, Count) \ __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src))) # else # define YYCOPY(Dst, Src, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (Dst)[yyi] = (Src)[yyi]; \ } \ while (YYID (0)) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL 74 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 1490 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 95 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 84 /* YYNRULES -- Number of rules. */ #define YYNRULES 202 /* YYNRULES -- Number of states. */ #define YYNSTATES 307 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 349 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94 }; #if YYDEBUG /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ static const yytype_uint16 yyprhs[] = { 0, 0, 3, 5, 7, 9, 11, 13, 15, 17, 21, 23, 28, 30, 34, 37, 40, 42, 44, 46, 50, 53, 56, 59, 61, 64, 68, 71, 73, 75, 77, 80, 83, 86, 88, 90, 92, 94, 98, 102, 104, 108, 112, 114, 116, 120, 124, 128, 132, 134, 138, 142, 144, 146, 148, 150, 154, 156, 160, 162, 166, 168, 174, 176, 180, 182, 184, 186, 188, 190, 192, 196, 198, 201, 204, 209, 212, 214, 216, 219, 223, 227, 230, 236, 240, 243, 247, 250, 251, 253, 255, 257, 259, 261, 265, 271, 278, 284, 286, 289, 294, 300, 305, 308, 310, 313, 315, 317, 319, 322, 324, 326, 329, 331, 333, 335, 337, 342, 344, 346, 348, 350, 352, 354, 356, 358, 360, 362, 364, 366, 368, 370, 372, 374, 376, 378, 380, 382, 384, 386, 387, 394, 395, 401, 403, 406, 410, 412, 416, 418, 423, 425, 427, 429, 431, 433, 435, 437, 439, 441, 444, 445, 446, 452, 454, 456, 457, 460, 461, 464, 467, 471, 473, 476, 478, 481, 487, 491, 493, 495, 500, 501, 508, 509, 518, 519, 527, 529, 531, 533, 534, 537, 541, 544, 547, 550, 554, 557, 559, 562, 564, 566, 567 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const yytype_int16 yyrhs[] = { 175, 0, -1, 45, -1, 46, -1, 45, -1, 97, -1, 48, -1, 47, -1, 49, -1, 71, 124, 72, -1, 98, -1, 99, 73, 100, 74, -1, 101, -1, 99, 77, 96, -1, 99, 52, -1, 99, 53, -1, 124, -1, 102, -1, 103, -1, 99, 77, 103, -1, 105, 72, -1, 104, 72, -1, 106, 39, -1, 106, -1, 106, 122, -1, 105, 78, 122, -1, 107, 71, -1, 142, -1, 45, -1, 99, -1, 52, 108, -1, 53, 108, -1, 109, 108, -1, 85, -1, 83, -1, 82, -1, 108, -1, 110, 86, 108, -1, 110, 87, 108, -1, 110, -1, 111, 85, 110, -1, 111, 83, 110, -1, 111, -1, 112, -1, 113, 89, 112, -1, 113, 90, 112, -1, 113, 54, 112, -1, 113, 55, 112, -1, 113, -1, 114, 56, 113, -1, 114, 57, 113, -1, 114, -1, 115, -1, 116, -1, 117, -1, 118, 58, 117, -1, 118, -1, 119, 60, 118, -1, 119, -1, 120, 59, 119, -1, 120, -1, 120, 94, 124, 79, 122, -1, 121, -1, 108, 123, 122, -1, 80, -1, 61, -1, 62, -1, 63, -1, 70, -1, 122, -1, 124, 78, 122, -1, 121, -1, 127, 81, -1, 135, 81, -1, 7, 140, 141, 81, -1, 128, 72, -1, 130, -1, 129, -1, 130, 132, -1, 129, 78, 132, -1, 137, 45, 71, -1, 139, 96, -1, 139, 96, 73, 125, 74, -1, 138, 133, 131, -1, 133, 131, -1, 138, 133, 134, -1, 133, 134, -1, -1, 33, -1, 34, -1, 35, -1, 139, -1, 136, -1, 135, 78, 96, -1, 135, 78, 96, 73, 74, -1, 135, 78, 96, 73, 125, 74, -1, 135, 78, 96, 80, 150, -1, 137, -1, 137, 96, -1, 137, 96, 73, 74, -1, 137, 96, 73, 125, 74, -1, 137, 96, 80, 150, -1, 3, 45, -1, 139, -1, 138, 139, -1, 9, -1, 8, -1, 37, -1, 3, 37, -1, 36, -1, 141, -1, 140, 141, -1, 4, -1, 5, -1, 6, -1, 142, -1, 142, 73, 125, 74, -1, 39, -1, 11, -1, 12, -1, 10, -1, 27, -1, 28, -1, 29, -1, 21, -1, 22, -1, 23, -1, 24, -1, 25, -1, 26, -1, 30, -1, 31, -1, 32, -1, 41, -1, 42, -1, 43, -1, 44, -1, 143, -1, 46, -1, -1, 38, 96, 75, 144, 146, 76, -1, -1, 38, 75, 145, 146, 76, -1, 147, -1, 146, 147, -1, 139, 148, 81, -1, 149, -1, 148, 78, 149, -1, 96, -1, 96, 73, 125, 74, -1, 122, -1, 126, -1, 154, -1, 153, -1, 151, -1, 163, -1, 164, -1, 167, -1, 174, -1, 75, 76, -1, -1, -1, 75, 155, 162, 156, 76, -1, 161, -1, 153, -1, -1, 159, 161, -1, -1, 160, 153, -1, 75, 76, -1, 75, 162, 76, -1, 152, -1, 162, 152, -1, 81, -1, 124, 81, -1, 18, 71, 124, 72, 165, -1, 158, 16, 158, -1, 158, -1, 124, -1, 137, 96, 80, 150, -1, -1, 40, 71, 168, 166, 72, 157, -1, -1, 15, 169, 158, 40, 71, 124, 72, 81, -1, -1, 17, 71, 170, 171, 173, 72, 157, -1, 163, -1, 151, -1, 166, -1, -1, 172, 81, -1, 172, 81, 124, -1, 14, 81, -1, 13, 81, -1, 20, 81, -1, 20, 124, 81, -1, 19, 81, -1, 176, -1, 175, 176, -1, 177, -1, 126, -1, -1, 127, 178, 161, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 179, 179, 180, 183, 226, 229, 242, 247, 252, 258, 261, 336, 339, 440, 450, 463, 471, 571, 574, 582, 585, 591, 595, 602, 608, 617, 625, 680, 690, 693, 703, 713, 734, 735, 736, 741, 742, 750, 761, 762, 770, 781, 785, 786, 796, 806, 816, 829, 830, 840, 853, 857, 861, 865, 866, 879, 880, 893, 894, 907, 908, 925, 926, 939, 940, 941, 942, 943, 947, 950, 961, 969, 996, 1001, 1015, 1052, 1055, 1062, 1070, 1091, 1112, 1122, 1150, 1155, 1165, 1170, 1180, 1183, 1186, 1189, 1195, 1202, 1205, 1227, 1245, 1269, 1292, 1296, 1314, 1322, 1354, 1374, 1395, 1404, 1427, 1430, 1436, 1444, 1452, 1460, 1470, 1477, 1480, 1483, 1489, 1492, 1507, 1511, 1515, 1519, 1523, 1528, 1533, 1538, 1543, 1548, 1553, 1558, 1563, 1568, 1573, 1578, 1583, 1587, 1591, 1599, 1607, 1611, 1624, 1624, 1638, 1638, 1647, 1650, 1666, 1702, 1706, 1712, 1719, 1734, 1738, 1742, 1743, 1749, 1750, 1751, 1752, 1753, 1757, 1758, 1758, 1758, 1768, 1769, 1773, 1773, 1774, 1774, 1779, 1782, 1792, 1795, 1801, 1802, 1806, 1814, 1818, 1828, 1833, 1850, 1850, 1855, 1855, 1862, 1862, 1870, 1873, 1879, 1882, 1888, 1892, 1899, 1906, 1913, 1920, 1931, 1940, 1944, 1951, 1954, 1960, 1960 }; #endif #if YYDEBUG || YYERROR_VERBOSE || 0 /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "INVARIANT", "HIGH_PRECISION", "MEDIUM_PRECISION", "LOW_PRECISION", "PRECISION", "ATTRIBUTE", "CONST_QUAL", "BOOL_TYPE", "FLOAT_TYPE", "INT_TYPE", "BREAK", "CONTINUE", "DO", "ELSE", "FOR", "IF", "DISCARD", "RETURN", "BVEC2", "BVEC3", "BVEC4", "IVEC2", "IVEC3", "IVEC4", "VEC2", "VEC3", "VEC4", "MATRIX2", "MATRIX3", "MATRIX4", "IN_QUAL", "OUT_QUAL", "INOUT_QUAL", "UNIFORM", "VARYING", "STRUCT", "VOID_TYPE", "WHILE", "SAMPLER2D", "SAMPLERCUBE", "SAMPLER_EXTERNAL_OES", "SAMPLER2DRECT", "IDENTIFIER", "TYPE_NAME", "FLOATCONSTANT", "INTCONSTANT", "BOOLCONSTANT", "LEFT_OP", "RIGHT_OP", "INC_OP", "DEC_OP", "LE_OP", "GE_OP", "EQ_OP", "NE_OP", "AND_OP", "OR_OP", "XOR_OP", "MUL_ASSIGN", "DIV_ASSIGN", "ADD_ASSIGN", "MOD_ASSIGN", "LEFT_ASSIGN", "RIGHT_ASSIGN", "AND_ASSIGN", "XOR_ASSIGN", "OR_ASSIGN", "SUB_ASSIGN", "LEFT_PAREN", "RIGHT_PAREN", "LEFT_BRACKET", "RIGHT_BRACKET", "LEFT_BRACE", "RIGHT_BRACE", "DOT", "COMMA", "COLON", "EQUAL", "SEMICOLON", "BANG", "DASH", "TILDE", "PLUS", "STAR", "SLASH", "PERCENT", "LEFT_ANGLE", "RIGHT_ANGLE", "VERTICAL_BAR", "CARET", "AMPERSAND", "QUESTION", "$accept", "identifier", "variable_identifier", "primary_expression", "postfix_expression", "integer_expression", "function_call", "function_call_or_method", "function_call_generic", "function_call_header_no_parameters", "function_call_header_with_parameters", "function_call_header", "function_identifier", "unary_expression", "unary_operator", "multiplicative_expression", "additive_expression", "shift_expression", "relational_expression", "equality_expression", "and_expression", "exclusive_or_expression", "inclusive_or_expression", "logical_and_expression", "logical_xor_expression", "logical_or_expression", "conditional_expression", "assignment_expression", "assignment_operator", "expression", "constant_expression", "declaration", "function_prototype", "function_declarator", "function_header_with_parameters", "function_header", "parameter_declarator", "parameter_declaration", "parameter_qualifier", "parameter_type_specifier", "init_declarator_list", "single_declaration", "fully_specified_type", "type_qualifier", "type_specifier", "precision_qualifier", "type_specifier_no_prec", "type_specifier_nonarray", "struct_specifier", "$@1", "$@2", "struct_declaration_list", "struct_declaration", "struct_declarator_list", "struct_declarator", "initializer", "declaration_statement", "statement", "simple_statement", "compound_statement", "$@3", "$@4", "statement_no_new_scope", "statement_with_scope", "$@5", "$@6", "compound_statement_no_new_scope", "statement_list", "expression_statement", "selection_statement", "selection_rest_statement", "condition", "iteration_statement", "$@7", "$@8", "$@9", "for_init_statement", "conditionopt", "for_rest_statement", "jump_statement", "translation_unit", "external_declaration", "function_definition", "$@10", YY_NULL }; #endif # ifdef YYPRINT /* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to token YYLEX-NUM. */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349 }; # endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 95, 96, 96, 97, 98, 98, 98, 98, 98, 99, 99, 99, 99, 99, 99, 100, 101, 102, 102, 103, 103, 104, 104, 105, 105, 106, 107, 107, 108, 108, 108, 108, 109, 109, 109, 110, 110, 110, 111, 111, 111, 112, 113, 113, 113, 113, 113, 114, 114, 114, 115, 116, 117, 118, 118, 119, 119, 120, 120, 121, 121, 122, 122, 123, 123, 123, 123, 123, 124, 124, 125, 126, 126, 126, 127, 128, 128, 129, 129, 130, 131, 131, 132, 132, 132, 132, 133, 133, 133, 133, 134, 135, 135, 135, 135, 135, 136, 136, 136, 136, 136, 136, 137, 137, 138, 138, 138, 138, 138, 139, 139, 140, 140, 140, 141, 141, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 144, 143, 145, 143, 146, 146, 147, 148, 148, 149, 149, 150, 151, 152, 152, 153, 153, 153, 153, 153, 154, 155, 156, 154, 157, 157, 159, 158, 160, 158, 161, 161, 162, 162, 163, 163, 164, 165, 165, 166, 166, 168, 167, 169, 167, 170, 167, 171, 171, 172, 172, 173, 173, 174, 174, 174, 174, 174, 175, 175, 176, 176, 178, 177 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 1, 1, 1, 1, 1, 1, 1, 3, 1, 4, 1, 3, 2, 2, 1, 1, 1, 3, 2, 2, 2, 1, 2, 3, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 3, 3, 1, 3, 3, 1, 1, 3, 3, 3, 3, 1, 3, 3, 1, 1, 1, 1, 3, 1, 3, 1, 3, 1, 5, 1, 3, 1, 1, 1, 1, 1, 1, 3, 1, 2, 2, 4, 2, 1, 1, 2, 3, 3, 2, 5, 3, 2, 3, 2, 0, 1, 1, 1, 1, 1, 3, 5, 6, 5, 1, 2, 4, 5, 4, 2, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 6, 0, 5, 1, 2, 3, 1, 3, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 5, 1, 1, 0, 2, 0, 2, 2, 3, 1, 2, 1, 2, 5, 3, 1, 1, 4, 0, 6, 0, 8, 0, 7, 1, 1, 1, 0, 2, 3, 2, 2, 2, 3, 2, 1, 2, 1, 1, 0, 3 }; /* YYDEFACT[STATE-NAME] -- Default reduction number in state STATE-NUM. Performed when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const yytype_uint8 yydefact[] = { 0, 0, 112, 113, 114, 0, 106, 105, 120, 118, 119, 124, 125, 126, 127, 128, 129, 121, 122, 123, 130, 131, 132, 109, 107, 0, 117, 133, 134, 135, 136, 138, 200, 201, 0, 77, 87, 0, 92, 97, 0, 103, 0, 110, 115, 137, 0, 197, 199, 108, 102, 0, 2, 3, 141, 0, 72, 0, 75, 87, 0, 88, 89, 90, 78, 0, 87, 0, 73, 2, 98, 104, 111, 0, 1, 198, 0, 0, 139, 0, 202, 79, 84, 86, 91, 0, 93, 80, 0, 0, 4, 7, 6, 8, 0, 0, 0, 35, 34, 33, 5, 10, 29, 12, 17, 18, 0, 0, 23, 0, 36, 0, 39, 42, 43, 48, 51, 52, 53, 54, 56, 58, 60, 71, 0, 27, 74, 0, 0, 143, 0, 0, 0, 182, 0, 0, 0, 0, 0, 160, 169, 173, 36, 62, 69, 0, 151, 0, 115, 154, 171, 153, 152, 0, 155, 156, 157, 158, 81, 83, 85, 0, 0, 99, 0, 150, 101, 30, 31, 0, 14, 15, 0, 0, 21, 20, 0, 22, 24, 26, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 116, 148, 0, 146, 142, 144, 0, 193, 192, 167, 184, 0, 196, 194, 0, 180, 159, 0, 65, 66, 67, 68, 64, 0, 0, 174, 170, 172, 0, 94, 0, 96, 100, 9, 0, 16, 2, 3, 13, 19, 25, 37, 38, 41, 40, 46, 47, 44, 45, 49, 50, 55, 57, 59, 0, 0, 0, 145, 140, 0, 0, 0, 0, 0, 195, 0, 161, 63, 70, 0, 95, 11, 0, 0, 147, 0, 166, 168, 187, 186, 189, 167, 178, 0, 0, 0, 82, 61, 149, 0, 188, 0, 0, 177, 175, 0, 0, 162, 0, 190, 0, 167, 0, 164, 181, 163, 0, 191, 185, 176, 179, 183 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { -1, 196, 100, 101, 102, 229, 103, 104, 105, 106, 107, 108, 109, 142, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 143, 144, 218, 145, 124, 146, 147, 34, 35, 36, 82, 64, 65, 83, 37, 38, 39, 40, 41, 42, 43, 125, 45, 130, 77, 128, 129, 197, 198, 166, 149, 150, 151, 152, 212, 280, 299, 254, 255, 256, 300, 153, 154, 155, 289, 279, 156, 260, 204, 257, 275, 286, 287, 157, 46, 47, 48, 57 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ #define YYPACT_NINF -261 static const yytype_int16 yypact[] = { 1327, -20, -261, -261, -261, 113, -261, -261, -261, -261, -261, -261, -261, -261, -261, -261, -261, -261, -261, -261, -261, -261, -261, -261, -261, -19, -261, -261, -261, -261, -261, -261, -261, -61, -40, -28, 75, -7, -261, 24, 1370, -261, 1444, -261, -11, -261, 1283, -261, -261, -261, -261, 1444, -261, -261, -261, 6, -261, 54, -261, 88, 62, -261, -261, -261, -261, 1370, 59, 91, -261, 36, -50, -261, -261, 1051, -261, -261, 63, 1370, -261, 293, -261, -261, -261, -261, 91, 1370, -12, -261, 856, 1051, 77, -261, -261, -261, 1051, 1051, 1051, -261, -261, -261, -261, -261, -14, -261, -261, -261, 84, -44, 1116, 95, -261, 1051, 53, 3, -261, -36, 89, -261, -261, -261, 104, 107, -45, -261, 96, -261, -261, 91, 1184, -261, 1370, 92, 93, -261, 98, 101, 94, 921, 105, 102, -261, -261, 72, -261, -261, 9, -261, -61, 42, -261, -261, -261, -261, 376, -261, -261, -261, -261, 106, -261, -261, 986, 1051, -261, 103, -261, -261, -261, -261, -41, -261, -261, 1051, 1407, -261, -261, 1051, 110, -261, -261, -261, 1051, 1051, 1051, 1051, 1051, 1051, 1051, 1051, 1051, 1051, 1051, 1051, 1051, 1051, -261, 109, 23, -261, -261, -261, 1227, -261, -261, 111, -261, 1051, -261, -261, 25, -261, -261, 459, -261, -261, -261, -261, -261, 1051, 1051, -261, -261, -261, 1051, -261, 114, -261, -261, -261, 115, 112, 77, 116, -261, -261, -261, -261, -261, 53, 53, -261, -261, -261, -261, -36, -36, -261, 104, 107, 76, 1051, 91, -261, -261, 145, 54, 625, 708, -6, -261, 791, 459, -261, -261, 117, -261, -261, 1051, 120, -261, 124, -261, -261, -261, -261, 791, 111, 112, 91, 125, 122, -261, -261, -261, 1051, -261, 118, 128, 180, -261, 126, 542, -261, -5, 1051, 542, 111, 1051, -261, -261, -261, 123, 112, -261, -261, -261, -261 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -261, -24, -261, -261, -261, -261, -261, -261, 34, -261, -261, -261, -261, 32, -261, -33, -261, -27, -26, -261, -261, -261, 14, 16, 18, -261, -66, -87, -261, -92, -85, 11, 12, -261, -261, -261, 141, 150, 161, 143, -261, -261, -231, 5, -30, 224, -18, 0, -261, -261, -261, 100, -119, -261, -17, -156, -25, -145, -243, -261, -261, -261, -64, -260, -261, -261, -52, 21, -22, -261, -261, -39, -261, -261, -261, -261, -261, -261, -261, -261, -261, 191, -261, -261 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If YYTABLE_NINF, syntax error. */ #define YYTABLE_NINF -166 static const yytype_int16 yytable[] = { 44, 55, 165, 164, 169, 80, 226, 123, 222, 200, 71, 32, 33, 272, 193, 70, 288, 49, 185, 186, 56, 178, 123, 88, 72, 50, 52, 53, 175, 278, 89, 228, 58, 76, 176, 84, 304, 219, 170, 171, 44, 66, 44, 86, 278, 209, 44, 127, 298, 194, 59, 44, 298, 187, 188, 84, 54, 32, 33, 172, 158, 161, 73, 173, 66, 44, 276, 301, 162, 69, 53, 67, 219, 219, 68, 165, 225, 44, 60, 148, 230, 78, 200, 6, 7, 44, 183, 219, 184, 235, 220, 60, 61, 62, 63, 123, 6, 7, 127, 49, 127, 251, 249, 219, 252, 110, 259, 87, 61, 62, 63, 23, 24, -27, 258, 73, 222, 2, 3, 4, 110, 61, 62, 63, 23, 24, 167, 168, 44, 79, 44, 262, 263, 213, 214, 215, 52, 53, 264, 181, 182, 305, 216, 180, 126, 189, 190, -76, -28, 233, 238, 239, 217, 148, 219, 267, 174, 123, 240, 241, 242, 243, 191, 244, 245, 268, 179, 192, 277, 205, 195, 127, 206, 202, 203, 207, 210, 227, 211, 223, 282, -117, 250, 277, 123, 270, -165, -138, 265, 266, 219, 281, 293, 110, 283, 284, 296, 291, 292, 294, 295, 44, 302, 271, 306, 246, 297, 234, 247, 81, 165, 248, 148, 236, 237, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 159, 85, 160, 51, 201, 303, 273, 261, 269, 274, 285, 75, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 290, 110, 148, 148, 0, 0, 148, 148, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 148, 0, 0, 0, 0, 0, 0, 110, 0, 0, 0, 0, 0, 0, 0, 0, 148, 0, 0, 0, 148, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 131, 132, 133, 0, 134, 135, 136, 137, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 0, 0, 23, 24, 25, 26, 138, 27, 28, 29, 30, 90, 31, 91, 92, 93, 0, 0, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 139, 140, 0, 0, 0, 0, 141, 97, 98, 0, 99, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 131, 132, 133, 0, 134, 135, 136, 137, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 0, 0, 23, 24, 25, 26, 138, 27, 28, 29, 30, 90, 31, 91, 92, 93, 0, 0, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 139, 221, 0, 0, 0, 0, 141, 97, 98, 0, 99, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 131, 132, 133, 0, 134, 135, 136, 137, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 0, 0, 23, 24, 25, 26, 138, 27, 28, 29, 30, 90, 31, 91, 92, 93, 0, 0, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 139, 0, 0, 0, 0, 0, 141, 97, 98, 0, 99, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 131, 132, 133, 0, 134, 135, 136, 137, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 0, 0, 23, 24, 25, 26, 138, 27, 28, 29, 30, 90, 31, 91, 92, 93, 0, 0, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 79, 0, 0, 0, 0, 0, 141, 97, 98, 0, 99, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 131, 132, 133, 0, 134, 135, 136, 137, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 0, 0, 23, 24, 25, 26, 138, 27, 28, 29, 30, 90, 31, 91, 92, 93, 0, 0, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 141, 97, 98, 0, 99, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 0, 0, 0, 0, 0, 0, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 0, 0, 23, 24, 25, 26, 0, 27, 28, 29, 30, 90, 31, 91, 92, 93, 0, 0, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 141, 97, 98, 0, 99, 60, 2, 3, 4, 0, 6, 7, 8, 9, 10, 0, 0, 0, 0, 0, 0, 0, 0, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 0, 0, 23, 24, 25, 26, 0, 27, 28, 29, 30, 90, 31, 91, 92, 93, 0, 0, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 8, 9, 10, 0, 0, 0, 0, 97, 98, 0, 99, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 0, 0, 0, 0, 25, 26, 0, 27, 28, 29, 30, 90, 31, 91, 92, 93, 0, 0, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 163, 8, 9, 10, 0, 0, 0, 0, 97, 98, 0, 99, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 0, 0, 0, 0, 25, 26, 0, 27, 28, 29, 30, 90, 31, 91, 92, 93, 0, 0, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 8, 9, 10, 0, 0, 0, 208, 97, 98, 0, 99, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 0, 0, 0, 0, 25, 26, 0, 27, 28, 29, 30, 90, 31, 91, 92, 93, 0, 0, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 224, 8, 9, 10, 0, 0, 0, 0, 97, 98, 0, 99, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 0, 0, 0, 0, 25, 26, 0, 27, 28, 29, 30, 90, 31, 91, 92, 93, 0, 0, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 8, 9, 10, 0, 0, 0, 0, 97, 98, 0, 99, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 0, 0, 0, 0, 25, 177, 0, 27, 28, 29, 30, 90, 31, 91, 92, 93, 0, 0, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 2, 3, 4, 0, 0, 0, 8, 9, 10, 0, 97, 98, 0, 99, 0, 0, 0, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 0, 0, 0, 0, 25, 26, 0, 27, 28, 29, 30, 0, 31, 2, 3, 4, 0, 0, 0, 8, 9, 10, 0, 0, 0, 0, 0, 0, 0, 0, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 199, 0, 0, 0, 0, 25, 26, 0, 27, 28, 29, 30, 0, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 74, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 0, 0, 0, 0, 0, 253, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 0, 0, 23, 24, 25, 26, 0, 27, 28, 29, 30, 0, 31, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 0, 0, 0, 0, 0, 0, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 0, 0, 23, 24, 25, 26, 0, 27, 28, 29, 30, 0, 31, 2, 3, 4, 0, 0, 0, 8, 9, 10, 0, 0, 0, 0, 0, 0, 0, 0, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 0, 0, 0, 0, 25, 26, 0, 27, 28, 29, 30, 0, 31, 8, 9, 10, 0, 0, 0, 0, 0, 0, 0, 0, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 0, 0, 0, 0, 25, 26, 0, 27, 28, 29, 30, 231, 232, 8, 9, 10, 0, 0, 0, 0, 0, 0, 0, 0, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 0, 0, 0, 0, 25, 26, 0, 27, 28, 29, 30, 0, 31 }; #define yypact_value_is_default(Yystate) \ (!!((Yystate) == (-261))) #define yytable_value_is_error(Yytable_value) \ YYID (0) static const yytype_int16 yycheck[] = { 0, 25, 89, 88, 96, 57, 162, 73, 153, 128, 40, 0, 0, 256, 59, 39, 276, 37, 54, 55, 81, 108, 88, 73, 42, 45, 45, 46, 72, 260, 80, 72, 72, 51, 78, 65, 296, 78, 52, 53, 40, 36, 42, 67, 275, 137, 46, 77, 291, 94, 78, 51, 295, 89, 90, 85, 75, 46, 46, 73, 84, 73, 73, 77, 59, 65, 72, 72, 80, 45, 46, 78, 78, 78, 81, 162, 161, 77, 3, 79, 172, 75, 201, 8, 9, 85, 83, 78, 85, 176, 81, 3, 33, 34, 35, 161, 8, 9, 128, 37, 130, 78, 194, 78, 81, 73, 81, 71, 33, 34, 35, 36, 37, 71, 206, 73, 261, 4, 5, 6, 88, 33, 34, 35, 36, 37, 94, 95, 128, 75, 130, 218, 219, 61, 62, 63, 45, 46, 223, 86, 87, 297, 70, 111, 81, 56, 57, 72, 71, 173, 183, 184, 80, 153, 78, 79, 72, 223, 185, 186, 187, 188, 58, 189, 190, 250, 71, 60, 260, 71, 74, 201, 71, 81, 81, 81, 71, 74, 76, 73, 267, 71, 73, 275, 250, 40, 75, 71, 74, 74, 78, 74, 284, 161, 74, 71, 16, 72, 76, 81, 72, 201, 294, 255, 81, 191, 80, 173, 192, 59, 297, 193, 212, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 85, 66, 85, 5, 130, 295, 257, 212, 251, 257, 275, 46, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 278, 223, 256, 257, -1, -1, 260, 261, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 275, -1, -1, -1, -1, -1, -1, 250, -1, -1, -1, -1, -1, -1, -1, -1, 291, -1, -1, -1, 295, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, -1, -1, 52, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 71, -1, -1, -1, 75, 76, -1, -1, -1, -1, 81, 82, 83, -1, 85, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, -1, -1, 52, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 71, -1, -1, -1, 75, 76, -1, -1, -1, -1, 81, 82, 83, -1, 85, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, -1, -1, 52, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 71, -1, -1, -1, 75, -1, -1, -1, -1, -1, 81, 82, 83, -1, 85, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, -1, -1, 52, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 71, -1, -1, -1, 75, -1, -1, -1, -1, -1, 81, 82, 83, -1, 85, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, -1, -1, 52, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 71, -1, -1, -1, -1, -1, -1, -1, -1, -1, 81, 82, 83, -1, 85, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, -1, -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, 36, 37, 38, 39, -1, 41, 42, 43, 44, 45, 46, 47, 48, 49, -1, -1, 52, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 71, -1, -1, -1, -1, -1, -1, -1, -1, -1, 81, 82, 83, -1, 85, 3, 4, 5, 6, -1, 8, 9, 10, 11, 12, -1, -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, 36, 37, 38, 39, -1, 41, 42, 43, 44, 45, 46, 47, 48, 49, -1, -1, 52, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 71, -1, -1, -1, 10, 11, 12, -1, -1, -1, -1, 82, 83, -1, 85, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1, 38, 39, -1, 41, 42, 43, 44, 45, 46, 47, 48, 49, -1, -1, 52, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 71, -1, -1, 74, 10, 11, 12, -1, -1, -1, -1, 82, 83, -1, 85, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1, 38, 39, -1, 41, 42, 43, 44, 45, 46, 47, 48, 49, -1, -1, 52, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 71, -1, -1, -1, 10, 11, 12, -1, -1, -1, 81, 82, 83, -1, 85, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1, 38, 39, -1, 41, 42, 43, 44, 45, 46, 47, 48, 49, -1, -1, 52, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 71, -1, -1, 74, 10, 11, 12, -1, -1, -1, -1, 82, 83, -1, 85, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1, 38, 39, -1, 41, 42, 43, 44, 45, 46, 47, 48, 49, -1, -1, 52, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 71, -1, -1, -1, 10, 11, 12, -1, -1, -1, -1, 82, 83, -1, 85, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1, 38, 39, -1, 41, 42, 43, 44, 45, 46, 47, 48, 49, -1, -1, 52, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 71, 4, 5, 6, -1, -1, -1, 10, 11, 12, -1, 82, 83, -1, 85, -1, -1, -1, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1, 38, 39, -1, 41, 42, 43, 44, -1, 46, 4, 5, 6, -1, -1, -1, 10, 11, 12, -1, -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 76, -1, -1, -1, -1, 38, 39, -1, 41, 42, 43, 44, -1, 46, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, -1, -1, -1, -1, -1, -1, -1, 76, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, 36, 37, 38, 39, -1, 41, 42, 43, 44, -1, 46, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, -1, -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, 36, 37, 38, 39, -1, 41, 42, 43, 44, -1, 46, 4, 5, 6, -1, -1, -1, 10, 11, 12, -1, -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1, 38, 39, -1, 41, 42, 43, 44, -1, 46, 10, 11, 12, -1, -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1, 38, 39, -1, 41, 42, 43, 44, 45, 46, 10, 11, 12, -1, -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1, 38, 39, -1, 41, 42, 43, 44, -1, 46 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 36, 37, 38, 39, 41, 42, 43, 44, 46, 126, 127, 128, 129, 130, 135, 136, 137, 138, 139, 140, 141, 142, 143, 175, 176, 177, 37, 45, 140, 45, 46, 75, 96, 81, 178, 72, 78, 3, 33, 34, 35, 132, 133, 138, 78, 81, 45, 96, 139, 141, 73, 0, 176, 141, 145, 75, 75, 161, 132, 131, 134, 139, 133, 96, 71, 73, 80, 45, 47, 48, 49, 52, 53, 71, 82, 83, 85, 97, 98, 99, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 125, 142, 81, 139, 146, 147, 144, 13, 14, 15, 17, 18, 19, 20, 40, 75, 76, 81, 108, 121, 122, 124, 126, 127, 142, 151, 152, 153, 154, 162, 163, 164, 167, 174, 96, 131, 134, 73, 80, 74, 125, 122, 150, 108, 108, 124, 52, 53, 73, 77, 72, 72, 78, 39, 122, 71, 108, 86, 87, 83, 85, 54, 55, 89, 90, 56, 57, 58, 60, 59, 94, 74, 96, 148, 149, 76, 147, 146, 81, 81, 169, 71, 71, 81, 81, 124, 71, 76, 155, 61, 62, 63, 70, 80, 123, 78, 81, 76, 152, 73, 74, 125, 150, 74, 72, 100, 124, 45, 46, 96, 103, 122, 108, 108, 110, 110, 112, 112, 112, 112, 113, 113, 117, 118, 119, 124, 73, 78, 81, 76, 158, 159, 160, 170, 124, 81, 168, 162, 122, 122, 125, 74, 74, 79, 125, 149, 40, 161, 153, 151, 163, 171, 72, 124, 137, 166, 156, 74, 122, 74, 71, 166, 172, 173, 158, 165, 96, 72, 76, 124, 81, 72, 16, 80, 153, 157, 161, 72, 124, 157, 158, 150, 81 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. However, YYFAIL appears to be in use. Nevertheless, it is formally deprecated in Bison 2.4.2's NEWS entry, where a plan to phase it out is discussed. */ #define YYFAIL goto yyerrlab #if defined YYFAIL /* This is here to suppress warnings from the GCC cpp's -Wunused-macros. Normally we don't worry about that warning, but some users do, and we want to make it easy for users to remove YYFAIL uses, which will produce warnings from Bison 2.5. */ #endif #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY) \ { \ yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (yylen); \ yystate = *yyssp; \ goto yybackup; \ } \ else \ { \ yyerror (&yylloc, context, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (YYID (0)) /* Error token number */ #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (YYID (N)) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (YYID (0)) #endif #define YYRHSLOC(Rhs, K) ((Rhs)[K]) /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL /* Print *YYLOCP on YYO. Private, do not rely on its existence. */ __attribute__((__unused__)) #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static unsigned yy_location_print_ (FILE *yyo, YYLTYPE const * const yylocp) #else static unsigned yy_location_print_ (yyo, yylocp) FILE *yyo; YYLTYPE const * const yylocp; #endif { unsigned res = 0; int end_col = 0 != yylocp->last_column ? yylocp->last_column - 1 : 0; if (0 <= yylocp->first_line) { res += fprintf (yyo, "%d", yylocp->first_line); if (0 <= yylocp->first_column) res += fprintf (yyo, ".%d", yylocp->first_column); } if (0 <= yylocp->last_line) { if (yylocp->first_line < yylocp->last_line) { res += fprintf (yyo, "-%d", yylocp->last_line); if (0 <= end_col) res += fprintf (yyo, ".%d", end_col); } else if (0 <= end_col && yylocp->first_column < end_col) res += fprintf (yyo, "-%d", end_col); } return res; } # define YY_LOCATION_PRINT(File, Loc) \ yy_location_print_ (File, &(Loc)) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM # define YYLEX yylex (&yylval, &yylloc, YYLEX_PARAM) #else # define YYLEX yylex (&yylval, &yylloc) #endif /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (YYID (0)) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, Location, context); \ YYFPRINTF (stderr, "\n"); \ } \ } while (YYID (0)) /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, TParseContext* context) #else static void yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp, context) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; YYLTYPE const * const yylocationp; TParseContext* context; #endif { FILE *yyo = yyoutput; YYUSE (yyo); if (!yyvaluep) return; YYUSE (yylocationp); YYUSE (context); # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # else YYUSE (yyoutput); # endif switch (yytype) { default: break; } } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, TParseContext* context) #else static void yy_symbol_print (yyoutput, yytype, yyvaluep, yylocationp, context) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; YYLTYPE const * const yylocationp; TParseContext* context; #endif { if (yytype < YYNTOKENS) YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); else YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); YY_LOCATION_PRINT (yyoutput, *yylocationp); YYFPRINTF (yyoutput, ": "); yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp, context); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) #else static void yy_stack_print (yybottom, yytop) yytype_int16 *yybottom; yytype_int16 *yytop; #endif { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_reduce_print (YYSTYPE *yyvsp, YYLTYPE *yylsp, int yyrule, TParseContext* context) #else static void yy_reduce_print (yyvsp, yylsp, yyrule, context) YYSTYPE *yyvsp; YYLTYPE *yylsp; int yyrule; TParseContext* context; #endif { int yynrhs = yyr2[yyrule]; int yyi; unsigned long int yylno = yyrline[yyrule]; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], &(yyvsp[(yyi + 1) - (yynrhs)]) , &(yylsp[(yyi + 1) - (yynrhs)]) , context); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyvsp, yylsp, Rule, context); \ } while (YYID (0)) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static YYSIZE_T yystrlen (const char *yystr) #else static YYSIZE_T yystrlen (yystr) const char *yystr; #endif { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static char * yystpcpy (char *yydest, const char *yysrc) #else static char * yystpcpy (yydest, yysrc) char *yydest; const char *yysrc; #endif { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message about the unexpected token YYTOKEN for the state stack whose top is YYSSP. Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is not large enough to hold the message. In that case, also set *YYMSG_ALLOC to the required number of bytes. Return 2 if the required number of bytes is too large to store. */ static int yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, yytype_int16 *yyssp, int yytoken) { YYSIZE_T yysize0 = yytnamerr (YY_NULL, yytname[yytoken]); YYSIZE_T yysize = yysize0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; /* Internationalized format string. */ const char *yyformat = YY_NULL; /* Arguments of yyformat. */ char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; /* Number of reported tokens (one for the "unexpected", one per "expected"). */ int yycount = 0; /* There are many possibilities here to consider: - Assume YYFAIL is not used. It's too flawed to consider. See <http://lists.gnu.org/archive/html/bison-patches/2009-12/msg00024.html> for details. YYERROR is fine as it does not invoke this function. - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yychar) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (yytoken != YYEMPTY) { int yyn = yypact[*yyssp]; yyarg[yycount++] = yytname[yytoken]; if (!yypact_value_is_default (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yyx; for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR && !yytable_value_is_error (yytable[yyx + yyn])) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; break; } yyarg[yycount++] = yytname[yyx]; { YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULL, yytname[yyx]); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } } } } switch (yycount) { # define YYCASE_(N, S) \ case N: \ yyformat = S; \ break YYCASE_(0, YY_("syntax error")); YYCASE_(1, YY_("syntax error, unexpected %s")); YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); # undef YYCASE_ } { YYSIZE_T yysize1 = yysize + yystrlen (yyformat); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } if (*yymsg_alloc < yysize) { *yymsg_alloc = 2 * yysize; if (! (yysize <= *yymsg_alloc && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; return 1; } /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ { char *yyp = *yymsg; int yyi = 0; while ((*yyp = *yyformat) != '\0') if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyformat += 2; } else { yyp++; yyformat++; } } return 0; } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, YYLTYPE *yylocationp, TParseContext* context) #else static void yydestruct (yymsg, yytype, yyvaluep, yylocationp, context) const char *yymsg; int yytype; YYSTYPE *yyvaluep; YYLTYPE *yylocationp; TParseContext* context; #endif { YYUSE (yyvaluep); YYUSE (yylocationp); YYUSE (context); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { default: break; } } /*----------. | yyparse. | `----------*/ #ifdef YYPARSE_PARAM #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else /* ! YYPARSE_PARAM */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (TParseContext* context) #else int yyparse (context) TParseContext* context; #endif #endif { /* The lookahead symbol. */ int yychar; #if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ /* Suppress an incorrect diagnostic about yylval being uninitialized. */ # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") # define YY_IGNORE_MAYBE_UNINITIALIZED_END \ _Pragma ("GCC diagnostic pop") #else /* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. */ static YYSTYPE yyval_default; # define YY_INITIAL_VALUE(Value) = Value #endif static YYLTYPE yyloc_default # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL = { 1, 1, 1, 1 } # endif ; #ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_END #endif #ifndef YY_INITIAL_VALUE # define YY_INITIAL_VALUE(Value) /* Nothing. */ #endif /* The semantic value of the lookahead symbol. */ YYSTYPE yylval YY_INITIAL_VALUE(yyval_default); /* Location data for the lookahead symbol. */ YYLTYPE yylloc = yyloc_default; /* Number of syntax errors so far. */ int yynerrs; int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: `yyss': related to states. `yyvs': related to semantic values. `yyls': related to locations. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; /* The location stack. */ YYLTYPE yylsa[YYINITDEPTH]; YYLTYPE *yyls; YYLTYPE *yylsp; /* The locations where the error started and ended. */ YYLTYPE yyerror_range[3]; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; YYLTYPE yyloc; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yylsp = yyls = yylsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ yylsp[0] = yylloc; goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; YYLTYPE *yyls1 = yyls; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yyls1, yysize * sizeof (*yylsp), &yystacksize); yyls = yyls1; yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); YYSTACK_RELOCATE (yyls_alloc, yyls); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; yylsp = yyls + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END *++yylsp = yylloc; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; /* Default location. */ YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen); YY_REDUCE_PRINT (yyn); switch (yyn) { case 4: { // The symbol table search was done in the lexical phase const TSymbol* symbol = (yyvsp[(1) - (1)].lex).symbol; const TVariable* variable; if (symbol == 0) { context->error((yylsp[(1) - (1)]), "undeclared identifier", (yyvsp[(1) - (1)].lex).string->c_str()); context->recover(); TType type(EbtFloat, EbpUndefined); TVariable* fakeVariable = new TVariable((yyvsp[(1) - (1)].lex).string, type); context->symbolTable.insert(*fakeVariable); variable = fakeVariable; } else { // This identifier can only be a variable type symbol if (! symbol->isVariable()) { context->error((yylsp[(1) - (1)]), "variable expected", (yyvsp[(1) - (1)].lex).string->c_str()); context->recover(); } variable = static_cast<const TVariable*>(symbol); if (context->isVariableBuiltIn(variable) && !variable->getExtension().empty() && context->extensionErrorCheck((yylsp[(1) - (1)]), variable->getExtension())) { context->recover(); } } // don't delete $1.string, it's used by error recovery, and the pool // pop will reclaim the memory if (variable->getType().getQualifier() == EvqConst ) { ConstantUnion* constArray = variable->getConstPointer(); TType t(variable->getType()); (yyval.interm.intermTypedNode) = context->intermediate.addConstantUnion(constArray, t, (yylsp[(1) - (1)])); } else (yyval.interm.intermTypedNode) = context->intermediate.addSymbol(variable->getUniqueId(), variable->getName(), variable->getType(), (yylsp[(1) - (1)])); } break; case 5: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 6: { // // INT_TYPE is only 16-bit plus sign bit for vertex/fragment shaders, // check for overflow for constants // if (abs((yyvsp[(1) - (1)].lex).i) >= (1 << 16)) { context->error((yylsp[(1) - (1)]), " integer constant overflow", ""); context->recover(); } ConstantUnion *unionArray = new ConstantUnion[1]; unionArray->setIConst((yyvsp[(1) - (1)].lex).i); (yyval.interm.intermTypedNode) = context->intermediate.addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConst), (yylsp[(1) - (1)])); } break; case 7: { ConstantUnion *unionArray = new ConstantUnion[1]; unionArray->setFConst((yyvsp[(1) - (1)].lex).f); (yyval.interm.intermTypedNode) = context->intermediate.addConstantUnion(unionArray, TType(EbtFloat, EbpUndefined, EvqConst), (yylsp[(1) - (1)])); } break; case 8: { ConstantUnion *unionArray = new ConstantUnion[1]; unionArray->setBConst((yyvsp[(1) - (1)].lex).b); (yyval.interm.intermTypedNode) = context->intermediate.addConstantUnion(unionArray, TType(EbtBool, EbpUndefined, EvqConst), (yylsp[(1) - (1)])); } break; case 9: { (yyval.interm.intermTypedNode) = (yyvsp[(2) - (3)].interm.intermTypedNode); } break; case 10: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 11: { if (!(yyvsp[(1) - (4)].interm.intermTypedNode)->isArray() && !(yyvsp[(1) - (4)].interm.intermTypedNode)->isMatrix() && !(yyvsp[(1) - (4)].interm.intermTypedNode)->isVector()) { if ((yyvsp[(1) - (4)].interm.intermTypedNode)->getAsSymbolNode()) context->error((yylsp[(2) - (4)]), " left of '[' is not of type array, matrix, or vector ", (yyvsp[(1) - (4)].interm.intermTypedNode)->getAsSymbolNode()->getSymbol().c_str()); else context->error((yylsp[(2) - (4)]), " left of '[' is not of type array, matrix, or vector ", "expression"); context->recover(); } if ((yyvsp[(3) - (4)].interm.intermTypedNode)->getQualifier() == EvqConst) { int index = (yyvsp[(3) - (4)].interm.intermTypedNode)->getAsConstantUnion()->getIConst(0); if (index < 0) { std::stringstream infoStream; infoStream << index; std::string info = infoStream.str(); context->error((yylsp[(3) - (4)]), "negative index", info.c_str()); context->recover(); index = 0; } if ((yyvsp[(1) - (4)].interm.intermTypedNode)->getType().getQualifier() == EvqConst) { if ((yyvsp[(1) - (4)].interm.intermTypedNode)->isArray()) { // constant folding for arrays (yyval.interm.intermTypedNode) = context->addConstArrayNode(index, (yyvsp[(1) - (4)].interm.intermTypedNode), (yylsp[(2) - (4)])); } else if ((yyvsp[(1) - (4)].interm.intermTypedNode)->isVector()) { // constant folding for vectors TVectorFields fields; fields.num = 1; fields.offsets[0] = index; // need to do it this way because v.xy sends fields integer array (yyval.interm.intermTypedNode) = context->addConstVectorNode(fields, (yyvsp[(1) - (4)].interm.intermTypedNode), (yylsp[(2) - (4)])); } else if ((yyvsp[(1) - (4)].interm.intermTypedNode)->isMatrix()) { // constant folding for matrices (yyval.interm.intermTypedNode) = context->addConstMatrixNode(index, (yyvsp[(1) - (4)].interm.intermTypedNode), (yylsp[(2) - (4)])); } } else { if ((yyvsp[(1) - (4)].interm.intermTypedNode)->isArray()) { if (index >= (yyvsp[(1) - (4)].interm.intermTypedNode)->getType().getArraySize()) { std::stringstream extraInfoStream; extraInfoStream << "array index out of range '" << index << "'"; std::string extraInfo = extraInfoStream.str(); context->error((yylsp[(2) - (4)]), "", "[", extraInfo.c_str()); context->recover(); index = (yyvsp[(1) - (4)].interm.intermTypedNode)->getType().getArraySize() - 1; } } else if (((yyvsp[(1) - (4)].interm.intermTypedNode)->isVector() || (yyvsp[(1) - (4)].interm.intermTypedNode)->isMatrix()) && (yyvsp[(1) - (4)].interm.intermTypedNode)->getType().getNominalSize() <= index) { std::stringstream extraInfoStream; extraInfoStream << "field selection out of range '" << index << "'"; std::string extraInfo = extraInfoStream.str(); context->error((yylsp[(2) - (4)]), "", "[", extraInfo.c_str()); context->recover(); index = (yyvsp[(1) - (4)].interm.intermTypedNode)->getType().getNominalSize() - 1; } (yyvsp[(3) - (4)].interm.intermTypedNode)->getAsConstantUnion()->getUnionArrayPointer()->setIConst(index); (yyval.interm.intermTypedNode) = context->intermediate.addIndex(EOpIndexDirect, (yyvsp[(1) - (4)].interm.intermTypedNode), (yyvsp[(3) - (4)].interm.intermTypedNode), (yylsp[(2) - (4)])); } } else { (yyval.interm.intermTypedNode) = context->intermediate.addIndex(EOpIndexIndirect, (yyvsp[(1) - (4)].interm.intermTypedNode), (yyvsp[(3) - (4)].interm.intermTypedNode), (yylsp[(2) - (4)])); } if ((yyval.interm.intermTypedNode) == 0) { ConstantUnion *unionArray = new ConstantUnion[1]; unionArray->setFConst(0.0f); (yyval.interm.intermTypedNode) = context->intermediate.addConstantUnion(unionArray, TType(EbtFloat, EbpHigh, EvqConst), (yylsp[(2) - (4)])); } else if ((yyvsp[(1) - (4)].interm.intermTypedNode)->isArray()) { if ((yyvsp[(1) - (4)].interm.intermTypedNode)->getType().getStruct()) (yyval.interm.intermTypedNode)->setType(TType((yyvsp[(1) - (4)].interm.intermTypedNode)->getType().getStruct(), (yyvsp[(1) - (4)].interm.intermTypedNode)->getType().getTypeName())); else (yyval.interm.intermTypedNode)->setType(TType((yyvsp[(1) - (4)].interm.intermTypedNode)->getBasicType(), (yyvsp[(1) - (4)].interm.intermTypedNode)->getPrecision(), EvqTemporary, (yyvsp[(1) - (4)].interm.intermTypedNode)->getNominalSize(), (yyvsp[(1) - (4)].interm.intermTypedNode)->isMatrix())); if ((yyvsp[(1) - (4)].interm.intermTypedNode)->getType().getQualifier() == EvqConst) (yyval.interm.intermTypedNode)->getTypePointer()->setQualifier(EvqConst); } else if ((yyvsp[(1) - (4)].interm.intermTypedNode)->isMatrix()) { TQualifier qualifier = (yyvsp[(1) - (4)].interm.intermTypedNode)->getType().getQualifier() == EvqConst ? EvqConst : EvqTemporary; (yyval.interm.intermTypedNode)->setType(TType((yyvsp[(1) - (4)].interm.intermTypedNode)->getBasicType(), (yyvsp[(1) - (4)].interm.intermTypedNode)->getPrecision(), qualifier, (yyvsp[(1) - (4)].interm.intermTypedNode)->getNominalSize())); } else if ((yyvsp[(1) - (4)].interm.intermTypedNode)->isVector()) { TQualifier qualifier = (yyvsp[(1) - (4)].interm.intermTypedNode)->getType().getQualifier() == EvqConst ? EvqConst : EvqTemporary; (yyval.interm.intermTypedNode)->setType(TType((yyvsp[(1) - (4)].interm.intermTypedNode)->getBasicType(), (yyvsp[(1) - (4)].interm.intermTypedNode)->getPrecision(), qualifier)); } else { (yyval.interm.intermTypedNode)->setType((yyvsp[(1) - (4)].interm.intermTypedNode)->getType()); } } break; case 12: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 13: { if ((yyvsp[(1) - (3)].interm.intermTypedNode)->isArray()) { context->error((yylsp[(3) - (3)]), "cannot apply dot operator to an array", "."); context->recover(); } if ((yyvsp[(1) - (3)].interm.intermTypedNode)->isVector()) { TVectorFields fields; if (! context->parseVectorFields(*(yyvsp[(3) - (3)].lex).string, (yyvsp[(1) - (3)].interm.intermTypedNode)->getNominalSize(), fields, (yylsp[(3) - (3)]))) { fields.num = 1; fields.offsets[0] = 0; context->recover(); } if ((yyvsp[(1) - (3)].interm.intermTypedNode)->getType().getQualifier() == EvqConst) { // constant folding for vector fields (yyval.interm.intermTypedNode) = context->addConstVectorNode(fields, (yyvsp[(1) - (3)].interm.intermTypedNode), (yylsp[(3) - (3)])); if ((yyval.interm.intermTypedNode) == 0) { context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(1) - (3)].interm.intermTypedNode); } else (yyval.interm.intermTypedNode)->setType(TType((yyvsp[(1) - (3)].interm.intermTypedNode)->getBasicType(), (yyvsp[(1) - (3)].interm.intermTypedNode)->getPrecision(), EvqConst, (int) (*(yyvsp[(3) - (3)].lex).string).size())); } else { TString vectorString = *(yyvsp[(3) - (3)].lex).string; TIntermTyped* index = context->intermediate.addSwizzle(fields, (yylsp[(3) - (3)])); (yyval.interm.intermTypedNode) = context->intermediate.addIndex(EOpVectorSwizzle, (yyvsp[(1) - (3)].interm.intermTypedNode), index, (yylsp[(2) - (3)])); (yyval.interm.intermTypedNode)->setType(TType((yyvsp[(1) - (3)].interm.intermTypedNode)->getBasicType(), (yyvsp[(1) - (3)].interm.intermTypedNode)->getPrecision(), EvqTemporary, (int) vectorString.size())); } } else if ((yyvsp[(1) - (3)].interm.intermTypedNode)->isMatrix()) { TMatrixFields fields; if (! context->parseMatrixFields(*(yyvsp[(3) - (3)].lex).string, (yyvsp[(1) - (3)].interm.intermTypedNode)->getNominalSize(), fields, (yylsp[(3) - (3)]))) { fields.wholeRow = false; fields.wholeCol = false; fields.row = 0; fields.col = 0; context->recover(); } if (fields.wholeRow || fields.wholeCol) { context->error((yylsp[(2) - (3)]), " non-scalar fields not implemented yet", "."); context->recover(); ConstantUnion *unionArray = new ConstantUnion[1]; unionArray->setIConst(0); TIntermTyped* index = context->intermediate.addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConst), (yylsp[(3) - (3)])); (yyval.interm.intermTypedNode) = context->intermediate.addIndex(EOpIndexDirect, (yyvsp[(1) - (3)].interm.intermTypedNode), index, (yylsp[(2) - (3)])); (yyval.interm.intermTypedNode)->setType(TType((yyvsp[(1) - (3)].interm.intermTypedNode)->getBasicType(), (yyvsp[(1) - (3)].interm.intermTypedNode)->getPrecision(),EvqTemporary, (yyvsp[(1) - (3)].interm.intermTypedNode)->getNominalSize())); } else { ConstantUnion *unionArray = new ConstantUnion[1]; unionArray->setIConst(fields.col * (yyvsp[(1) - (3)].interm.intermTypedNode)->getNominalSize() + fields.row); TIntermTyped* index = context->intermediate.addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConst), (yylsp[(3) - (3)])); (yyval.interm.intermTypedNode) = context->intermediate.addIndex(EOpIndexDirect, (yyvsp[(1) - (3)].interm.intermTypedNode), index, (yylsp[(2) - (3)])); (yyval.interm.intermTypedNode)->setType(TType((yyvsp[(1) - (3)].interm.intermTypedNode)->getBasicType(), (yyvsp[(1) - (3)].interm.intermTypedNode)->getPrecision())); } } else if ((yyvsp[(1) - (3)].interm.intermTypedNode)->getBasicType() == EbtStruct) { bool fieldFound = false; const TTypeList* fields = (yyvsp[(1) - (3)].interm.intermTypedNode)->getType().getStruct(); if (fields == 0) { context->error((yylsp[(2) - (3)]), "structure has no fields", "Internal Error"); context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(1) - (3)].interm.intermTypedNode); } else { unsigned int i; for (i = 0; i < fields->size(); ++i) { if ((*fields)[i]->getFieldName() == *(yyvsp[(3) - (3)].lex).string) { fieldFound = true; break; } } if (fieldFound) { if ((yyvsp[(1) - (3)].interm.intermTypedNode)->getType().getQualifier() == EvqConst) { (yyval.interm.intermTypedNode) = context->addConstStruct(*(yyvsp[(3) - (3)].lex).string, (yyvsp[(1) - (3)].interm.intermTypedNode), (yylsp[(2) - (3)])); if ((yyval.interm.intermTypedNode) == 0) { context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(1) - (3)].interm.intermTypedNode); } else { (yyval.interm.intermTypedNode)->setType(*(*fields)[i]); // change the qualifier of the return type, not of the structure field // as the structure definition is shared between various structures. (yyval.interm.intermTypedNode)->getTypePointer()->setQualifier(EvqConst); } } else { ConstantUnion *unionArray = new ConstantUnion[1]; unionArray->setIConst(i); TIntermTyped* index = context->intermediate.addConstantUnion(unionArray, *(*fields)[i], (yylsp[(3) - (3)])); (yyval.interm.intermTypedNode) = context->intermediate.addIndex(EOpIndexDirectStruct, (yyvsp[(1) - (3)].interm.intermTypedNode), index, (yylsp[(2) - (3)])); (yyval.interm.intermTypedNode)->setType(*(*fields)[i]); } } else { context->error((yylsp[(2) - (3)]), " no such field in structure", (yyvsp[(3) - (3)].lex).string->c_str()); context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(1) - (3)].interm.intermTypedNode); } } } else { context->error((yylsp[(2) - (3)]), " field selection requires structure, vector, or matrix on left hand side", (yyvsp[(3) - (3)].lex).string->c_str()); context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(1) - (3)].interm.intermTypedNode); } // don't delete $3.string, it's from the pool } break; case 14: { if (context->lValueErrorCheck((yylsp[(2) - (2)]), "++", (yyvsp[(1) - (2)].interm.intermTypedNode))) context->recover(); (yyval.interm.intermTypedNode) = context->intermediate.addUnaryMath(EOpPostIncrement, (yyvsp[(1) - (2)].interm.intermTypedNode), (yylsp[(2) - (2)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { context->unaryOpError((yylsp[(2) - (2)]), "++", (yyvsp[(1) - (2)].interm.intermTypedNode)->getCompleteString()); context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(1) - (2)].interm.intermTypedNode); } } break; case 15: { if (context->lValueErrorCheck((yylsp[(2) - (2)]), "--", (yyvsp[(1) - (2)].interm.intermTypedNode))) context->recover(); (yyval.interm.intermTypedNode) = context->intermediate.addUnaryMath(EOpPostDecrement, (yyvsp[(1) - (2)].interm.intermTypedNode), (yylsp[(2) - (2)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { context->unaryOpError((yylsp[(2) - (2)]), "--", (yyvsp[(1) - (2)].interm.intermTypedNode)->getCompleteString()); context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(1) - (2)].interm.intermTypedNode); } } break; case 16: { if (context->integerErrorCheck((yyvsp[(1) - (1)].interm.intermTypedNode), "[]")) context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 17: { TFunction* fnCall = (yyvsp[(1) - (1)].interm).function; TOperator op = fnCall->getBuiltInOp(); if (op != EOpNull) { // // Then this should be a constructor. // Don't go through the symbol table for constructors. // Their parameters will be verified algorithmically. // TType type(EbtVoid, EbpUndefined); // use this to get the type back if (context->constructorErrorCheck((yylsp[(1) - (1)]), (yyvsp[(1) - (1)].interm).intermNode, *fnCall, op, &type)) { (yyval.interm.intermTypedNode) = 0; } else { // // It's a constructor, of type 'type'. // (yyval.interm.intermTypedNode) = context->addConstructor((yyvsp[(1) - (1)].interm).intermNode, &type, op, fnCall, (yylsp[(1) - (1)])); } if ((yyval.interm.intermTypedNode) == 0) { context->recover(); (yyval.interm.intermTypedNode) = context->intermediate.setAggregateOperator(0, op, (yylsp[(1) - (1)])); } (yyval.interm.intermTypedNode)->setType(type); } else { // // Not a constructor. Find it in the symbol table. // const TFunction* fnCandidate; bool builtIn; fnCandidate = context->findFunction((yylsp[(1) - (1)]), fnCall, &builtIn); if (fnCandidate) { // // A declared function. // if (builtIn && !fnCandidate->getExtension().empty() && context->extensionErrorCheck((yylsp[(1) - (1)]), fnCandidate->getExtension())) { context->recover(); } op = fnCandidate->getBuiltInOp(); if (builtIn && op != EOpNull) { // // A function call mapped to a built-in operation. // if (fnCandidate->getParamCount() == 1) { // // Treat it like a built-in unary operator. // (yyval.interm.intermTypedNode) = context->intermediate.addUnaryMath(op, (yyvsp[(1) - (1)].interm).intermNode, (yylsp[(1) - (1)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { std::stringstream extraInfoStream; extraInfoStream << "built in unary operator function. Type: " << static_cast<TIntermTyped*>((yyvsp[(1) - (1)].interm).intermNode)->getCompleteString(); std::string extraInfo = extraInfoStream.str(); context->error((yyvsp[(1) - (1)].interm).intermNode->getLine(), " wrong operand type", "Internal Error", extraInfo.c_str()); YYERROR; } } else { (yyval.interm.intermTypedNode) = context->intermediate.setAggregateOperator((yyvsp[(1) - (1)].interm).intermAggregate, op, (yylsp[(1) - (1)])); } } else { // This is a real function call (yyval.interm.intermTypedNode) = context->intermediate.setAggregateOperator((yyvsp[(1) - (1)].interm).intermAggregate, EOpFunctionCall, (yylsp[(1) - (1)])); (yyval.interm.intermTypedNode)->setType(fnCandidate->getReturnType()); // this is how we know whether the given function is a builtIn function or a user defined function // if builtIn == false, it's a userDefined -> could be an overloaded builtIn function also // if builtIn == true, it's definitely a builtIn function with EOpNull if (!builtIn) (yyval.interm.intermTypedNode)->getAsAggregate()->setUserDefined(); (yyval.interm.intermTypedNode)->getAsAggregate()->setName(fnCandidate->getMangledName()); TQualifier qual; for (size_t i = 0; i < fnCandidate->getParamCount(); ++i) { qual = fnCandidate->getParam(i).type->getQualifier(); if (qual == EvqOut || qual == EvqInOut) { if (context->lValueErrorCheck((yyval.interm.intermTypedNode)->getLine(), "assign", (yyval.interm.intermTypedNode)->getAsAggregate()->getSequence()[i]->getAsTyped())) { context->error((yyvsp[(1) - (1)].interm).intermNode->getLine(), "Constant value cannot be passed for 'out' or 'inout' parameters.", "Error"); context->recover(); } } } } (yyval.interm.intermTypedNode)->setType(fnCandidate->getReturnType()); } else { // error message was put out by PaFindFunction() // Put on a dummy node for error recovery ConstantUnion *unionArray = new ConstantUnion[1]; unionArray->setFConst(0.0f); (yyval.interm.intermTypedNode) = context->intermediate.addConstantUnion(unionArray, TType(EbtFloat, EbpUndefined, EvqConst), (yylsp[(1) - (1)])); context->recover(); } } delete fnCall; } break; case 18: { (yyval.interm) = (yyvsp[(1) - (1)].interm); } break; case 19: { context->error((yylsp[(3) - (3)]), "methods are not supported", ""); context->recover(); (yyval.interm) = (yyvsp[(3) - (3)].interm); } break; case 20: { (yyval.interm) = (yyvsp[(1) - (2)].interm); } break; case 21: { (yyval.interm) = (yyvsp[(1) - (2)].interm); } break; case 22: { (yyval.interm).function = (yyvsp[(1) - (2)].interm.function); (yyval.interm).intermNode = 0; } break; case 23: { (yyval.interm).function = (yyvsp[(1) - (1)].interm.function); (yyval.interm).intermNode = 0; } break; case 24: { TParameter param = { 0, new TType((yyvsp[(2) - (2)].interm.intermTypedNode)->getType()) }; (yyvsp[(1) - (2)].interm.function)->addParameter(param); (yyval.interm).function = (yyvsp[(1) - (2)].interm.function); (yyval.interm).intermNode = (yyvsp[(2) - (2)].interm.intermTypedNode); } break; case 25: { TParameter param = { 0, new TType((yyvsp[(3) - (3)].interm.intermTypedNode)->getType()) }; (yyvsp[(1) - (3)].interm).function->addParameter(param); (yyval.interm).function = (yyvsp[(1) - (3)].interm).function; (yyval.interm).intermNode = context->intermediate.growAggregate((yyvsp[(1) - (3)].interm).intermNode, (yyvsp[(3) - (3)].interm.intermTypedNode), (yylsp[(2) - (3)])); } break; case 26: { (yyval.interm.function) = (yyvsp[(1) - (2)].interm.function); } break; case 27: { // // Constructor // TOperator op = EOpNull; if ((yyvsp[(1) - (1)].interm.type).userDef) { op = EOpConstructStruct; } else { switch ((yyvsp[(1) - (1)].interm.type).type) { case EbtFloat: if ((yyvsp[(1) - (1)].interm.type).matrix) { switch((yyvsp[(1) - (1)].interm.type).size) { case 2: op = EOpConstructMat2; break; case 3: op = EOpConstructMat3; break; case 4: op = EOpConstructMat4; break; } } else { switch((yyvsp[(1) - (1)].interm.type).size) { case 1: op = EOpConstructFloat; break; case 2: op = EOpConstructVec2; break; case 3: op = EOpConstructVec3; break; case 4: op = EOpConstructVec4; break; } } break; case EbtInt: switch((yyvsp[(1) - (1)].interm.type).size) { case 1: op = EOpConstructInt; break; case 2: op = EOpConstructIVec2; break; case 3: op = EOpConstructIVec3; break; case 4: op = EOpConstructIVec4; break; } break; case EbtBool: switch((yyvsp[(1) - (1)].interm.type).size) { case 1: op = EOpConstructBool; break; case 2: op = EOpConstructBVec2; break; case 3: op = EOpConstructBVec3; break; case 4: op = EOpConstructBVec4; break; } break; default: break; } if (op == EOpNull) { context->error((yylsp[(1) - (1)]), "cannot construct this type", getBasicString((yyvsp[(1) - (1)].interm.type).type)); context->recover(); (yyvsp[(1) - (1)].interm.type).type = EbtFloat; op = EOpConstructFloat; } } TString tempString; TType type((yyvsp[(1) - (1)].interm.type)); TFunction *function = new TFunction(&tempString, type, op); (yyval.interm.function) = function; } break; case 28: { if (context->reservedErrorCheck((yylsp[(1) - (1)]), *(yyvsp[(1) - (1)].lex).string)) context->recover(); TType type(EbtVoid, EbpUndefined); TFunction *function = new TFunction((yyvsp[(1) - (1)].lex).string, type); (yyval.interm.function) = function; } break; case 29: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 30: { if (context->lValueErrorCheck((yylsp[(1) - (2)]), "++", (yyvsp[(2) - (2)].interm.intermTypedNode))) context->recover(); (yyval.interm.intermTypedNode) = context->intermediate.addUnaryMath(EOpPreIncrement, (yyvsp[(2) - (2)].interm.intermTypedNode), (yylsp[(1) - (2)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { context->unaryOpError((yylsp[(1) - (2)]), "++", (yyvsp[(2) - (2)].interm.intermTypedNode)->getCompleteString()); context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(2) - (2)].interm.intermTypedNode); } } break; case 31: { if (context->lValueErrorCheck((yylsp[(1) - (2)]), "--", (yyvsp[(2) - (2)].interm.intermTypedNode))) context->recover(); (yyval.interm.intermTypedNode) = context->intermediate.addUnaryMath(EOpPreDecrement, (yyvsp[(2) - (2)].interm.intermTypedNode), (yylsp[(1) - (2)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { context->unaryOpError((yylsp[(1) - (2)]), "--", (yyvsp[(2) - (2)].interm.intermTypedNode)->getCompleteString()); context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(2) - (2)].interm.intermTypedNode); } } break; case 32: { if ((yyvsp[(1) - (2)].interm).op != EOpNull) { (yyval.interm.intermTypedNode) = context->intermediate.addUnaryMath((yyvsp[(1) - (2)].interm).op, (yyvsp[(2) - (2)].interm.intermTypedNode), (yylsp[(1) - (2)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { const char* errorOp = ""; switch((yyvsp[(1) - (2)].interm).op) { case EOpNegative: errorOp = "-"; break; case EOpLogicalNot: errorOp = "!"; break; default: break; } context->unaryOpError((yylsp[(1) - (2)]), errorOp, (yyvsp[(2) - (2)].interm.intermTypedNode)->getCompleteString()); context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(2) - (2)].interm.intermTypedNode); } } else (yyval.interm.intermTypedNode) = (yyvsp[(2) - (2)].interm.intermTypedNode); } break; case 33: { (yyval.interm).op = EOpNull; } break; case 34: { (yyval.interm).op = EOpNegative; } break; case 35: { (yyval.interm).op = EOpLogicalNot; } break; case 36: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 37: { (yyval.interm.intermTypedNode) = context->intermediate.addBinaryMath(EOpMul, (yyvsp[(1) - (3)].interm.intermTypedNode), (yyvsp[(3) - (3)].interm.intermTypedNode), (yylsp[(2) - (3)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { context->binaryOpError((yylsp[(2) - (3)]), "*", (yyvsp[(1) - (3)].interm.intermTypedNode)->getCompleteString(), (yyvsp[(3) - (3)].interm.intermTypedNode)->getCompleteString()); context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(1) - (3)].interm.intermTypedNode); } } break; case 38: { (yyval.interm.intermTypedNode) = context->intermediate.addBinaryMath(EOpDiv, (yyvsp[(1) - (3)].interm.intermTypedNode), (yyvsp[(3) - (3)].interm.intermTypedNode), (yylsp[(2) - (3)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { context->binaryOpError((yylsp[(2) - (3)]), "/", (yyvsp[(1) - (3)].interm.intermTypedNode)->getCompleteString(), (yyvsp[(3) - (3)].interm.intermTypedNode)->getCompleteString()); context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(1) - (3)].interm.intermTypedNode); } } break; case 39: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 40: { (yyval.interm.intermTypedNode) = context->intermediate.addBinaryMath(EOpAdd, (yyvsp[(1) - (3)].interm.intermTypedNode), (yyvsp[(3) - (3)].interm.intermTypedNode), (yylsp[(2) - (3)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { context->binaryOpError((yylsp[(2) - (3)]), "+", (yyvsp[(1) - (3)].interm.intermTypedNode)->getCompleteString(), (yyvsp[(3) - (3)].interm.intermTypedNode)->getCompleteString()); context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(1) - (3)].interm.intermTypedNode); } } break; case 41: { (yyval.interm.intermTypedNode) = context->intermediate.addBinaryMath(EOpSub, (yyvsp[(1) - (3)].interm.intermTypedNode), (yyvsp[(3) - (3)].interm.intermTypedNode), (yylsp[(2) - (3)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { context->binaryOpError((yylsp[(2) - (3)]), "-", (yyvsp[(1) - (3)].interm.intermTypedNode)->getCompleteString(), (yyvsp[(3) - (3)].interm.intermTypedNode)->getCompleteString()); context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(1) - (3)].interm.intermTypedNode); } } break; case 42: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 43: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 44: { (yyval.interm.intermTypedNode) = context->intermediate.addBinaryMath(EOpLessThan, (yyvsp[(1) - (3)].interm.intermTypedNode), (yyvsp[(3) - (3)].interm.intermTypedNode), (yylsp[(2) - (3)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { context->binaryOpError((yylsp[(2) - (3)]), "<", (yyvsp[(1) - (3)].interm.intermTypedNode)->getCompleteString(), (yyvsp[(3) - (3)].interm.intermTypedNode)->getCompleteString()); context->recover(); ConstantUnion *unionArray = new ConstantUnion[1]; unionArray->setBConst(false); (yyval.interm.intermTypedNode) = context->intermediate.addConstantUnion(unionArray, TType(EbtBool, EbpUndefined, EvqConst), (yylsp[(2) - (3)])); } } break; case 45: { (yyval.interm.intermTypedNode) = context->intermediate.addBinaryMath(EOpGreaterThan, (yyvsp[(1) - (3)].interm.intermTypedNode), (yyvsp[(3) - (3)].interm.intermTypedNode), (yylsp[(2) - (3)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { context->binaryOpError((yylsp[(2) - (3)]), ">", (yyvsp[(1) - (3)].interm.intermTypedNode)->getCompleteString(), (yyvsp[(3) - (3)].interm.intermTypedNode)->getCompleteString()); context->recover(); ConstantUnion *unionArray = new ConstantUnion[1]; unionArray->setBConst(false); (yyval.interm.intermTypedNode) = context->intermediate.addConstantUnion(unionArray, TType(EbtBool, EbpUndefined, EvqConst), (yylsp[(2) - (3)])); } } break; case 46: { (yyval.interm.intermTypedNode) = context->intermediate.addBinaryMath(EOpLessThanEqual, (yyvsp[(1) - (3)].interm.intermTypedNode), (yyvsp[(3) - (3)].interm.intermTypedNode), (yylsp[(2) - (3)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { context->binaryOpError((yylsp[(2) - (3)]), "<=", (yyvsp[(1) - (3)].interm.intermTypedNode)->getCompleteString(), (yyvsp[(3) - (3)].interm.intermTypedNode)->getCompleteString()); context->recover(); ConstantUnion *unionArray = new ConstantUnion[1]; unionArray->setBConst(false); (yyval.interm.intermTypedNode) = context->intermediate.addConstantUnion(unionArray, TType(EbtBool, EbpUndefined, EvqConst), (yylsp[(2) - (3)])); } } break; case 47: { (yyval.interm.intermTypedNode) = context->intermediate.addBinaryMath(EOpGreaterThanEqual, (yyvsp[(1) - (3)].interm.intermTypedNode), (yyvsp[(3) - (3)].interm.intermTypedNode), (yylsp[(2) - (3)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { context->binaryOpError((yylsp[(2) - (3)]), ">=", (yyvsp[(1) - (3)].interm.intermTypedNode)->getCompleteString(), (yyvsp[(3) - (3)].interm.intermTypedNode)->getCompleteString()); context->recover(); ConstantUnion *unionArray = new ConstantUnion[1]; unionArray->setBConst(false); (yyval.interm.intermTypedNode) = context->intermediate.addConstantUnion(unionArray, TType(EbtBool, EbpUndefined, EvqConst), (yylsp[(2) - (3)])); } } break; case 48: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 49: { (yyval.interm.intermTypedNode) = context->intermediate.addBinaryMath(EOpEqual, (yyvsp[(1) - (3)].interm.intermTypedNode), (yyvsp[(3) - (3)].interm.intermTypedNode), (yylsp[(2) - (3)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { context->binaryOpError((yylsp[(2) - (3)]), "==", (yyvsp[(1) - (3)].interm.intermTypedNode)->getCompleteString(), (yyvsp[(3) - (3)].interm.intermTypedNode)->getCompleteString()); context->recover(); ConstantUnion *unionArray = new ConstantUnion[1]; unionArray->setBConst(false); (yyval.interm.intermTypedNode) = context->intermediate.addConstantUnion(unionArray, TType(EbtBool, EbpUndefined, EvqConst), (yylsp[(2) - (3)])); } } break; case 50: { (yyval.interm.intermTypedNode) = context->intermediate.addBinaryMath(EOpNotEqual, (yyvsp[(1) - (3)].interm.intermTypedNode), (yyvsp[(3) - (3)].interm.intermTypedNode), (yylsp[(2) - (3)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { context->binaryOpError((yylsp[(2) - (3)]), "!=", (yyvsp[(1) - (3)].interm.intermTypedNode)->getCompleteString(), (yyvsp[(3) - (3)].interm.intermTypedNode)->getCompleteString()); context->recover(); ConstantUnion *unionArray = new ConstantUnion[1]; unionArray->setBConst(false); (yyval.interm.intermTypedNode) = context->intermediate.addConstantUnion(unionArray, TType(EbtBool, EbpUndefined, EvqConst), (yylsp[(2) - (3)])); } } break; case 51: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 52: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 53: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 54: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 55: { (yyval.interm.intermTypedNode) = context->intermediate.addBinaryMath(EOpLogicalAnd, (yyvsp[(1) - (3)].interm.intermTypedNode), (yyvsp[(3) - (3)].interm.intermTypedNode), (yylsp[(2) - (3)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { context->binaryOpError((yylsp[(2) - (3)]), "&&", (yyvsp[(1) - (3)].interm.intermTypedNode)->getCompleteString(), (yyvsp[(3) - (3)].interm.intermTypedNode)->getCompleteString()); context->recover(); ConstantUnion *unionArray = new ConstantUnion[1]; unionArray->setBConst(false); (yyval.interm.intermTypedNode) = context->intermediate.addConstantUnion(unionArray, TType(EbtBool, EbpUndefined, EvqConst), (yylsp[(2) - (3)])); } } break; case 56: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 57: { (yyval.interm.intermTypedNode) = context->intermediate.addBinaryMath(EOpLogicalXor, (yyvsp[(1) - (3)].interm.intermTypedNode), (yyvsp[(3) - (3)].interm.intermTypedNode), (yylsp[(2) - (3)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { context->binaryOpError((yylsp[(2) - (3)]), "^^", (yyvsp[(1) - (3)].interm.intermTypedNode)->getCompleteString(), (yyvsp[(3) - (3)].interm.intermTypedNode)->getCompleteString()); context->recover(); ConstantUnion *unionArray = new ConstantUnion[1]; unionArray->setBConst(false); (yyval.interm.intermTypedNode) = context->intermediate.addConstantUnion(unionArray, TType(EbtBool, EbpUndefined, EvqConst), (yylsp[(2) - (3)])); } } break; case 58: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 59: { (yyval.interm.intermTypedNode) = context->intermediate.addBinaryMath(EOpLogicalOr, (yyvsp[(1) - (3)].interm.intermTypedNode), (yyvsp[(3) - (3)].interm.intermTypedNode), (yylsp[(2) - (3)]), context->symbolTable); if ((yyval.interm.intermTypedNode) == 0) { context->binaryOpError((yylsp[(2) - (3)]), "||", (yyvsp[(1) - (3)].interm.intermTypedNode)->getCompleteString(), (yyvsp[(3) - (3)].interm.intermTypedNode)->getCompleteString()); context->recover(); ConstantUnion *unionArray = new ConstantUnion[1]; unionArray->setBConst(false); (yyval.interm.intermTypedNode) = context->intermediate.addConstantUnion(unionArray, TType(EbtBool, EbpUndefined, EvqConst), (yylsp[(2) - (3)])); } } break; case 60: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 61: { if (context->boolErrorCheck((yylsp[(2) - (5)]), (yyvsp[(1) - (5)].interm.intermTypedNode))) context->recover(); (yyval.interm.intermTypedNode) = context->intermediate.addSelection((yyvsp[(1) - (5)].interm.intermTypedNode), (yyvsp[(3) - (5)].interm.intermTypedNode), (yyvsp[(5) - (5)].interm.intermTypedNode), (yylsp[(2) - (5)])); if ((yyvsp[(3) - (5)].interm.intermTypedNode)->getType() != (yyvsp[(5) - (5)].interm.intermTypedNode)->getType()) (yyval.interm.intermTypedNode) = 0; if ((yyval.interm.intermTypedNode) == 0) { context->binaryOpError((yylsp[(2) - (5)]), ":", (yyvsp[(3) - (5)].interm.intermTypedNode)->getCompleteString(), (yyvsp[(5) - (5)].interm.intermTypedNode)->getCompleteString()); context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(5) - (5)].interm.intermTypedNode); } } break; case 62: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 63: { if (context->lValueErrorCheck((yylsp[(2) - (3)]), "assign", (yyvsp[(1) - (3)].interm.intermTypedNode))) context->recover(); (yyval.interm.intermTypedNode) = context->intermediate.addAssign((yyvsp[(2) - (3)].interm).op, (yyvsp[(1) - (3)].interm.intermTypedNode), (yyvsp[(3) - (3)].interm.intermTypedNode), (yylsp[(2) - (3)])); if ((yyval.interm.intermTypedNode) == 0) { context->assignError((yylsp[(2) - (3)]), "assign", (yyvsp[(1) - (3)].interm.intermTypedNode)->getCompleteString(), (yyvsp[(3) - (3)].interm.intermTypedNode)->getCompleteString()); context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(1) - (3)].interm.intermTypedNode); } } break; case 64: { (yyval.interm).op = EOpAssign; } break; case 65: { (yyval.interm).op = EOpMulAssign; } break; case 66: { (yyval.interm).op = EOpDivAssign; } break; case 67: { (yyval.interm).op = EOpAddAssign; } break; case 68: { (yyval.interm).op = EOpSubAssign; } break; case 69: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 70: { (yyval.interm.intermTypedNode) = context->intermediate.addComma((yyvsp[(1) - (3)].interm.intermTypedNode), (yyvsp[(3) - (3)].interm.intermTypedNode), (yylsp[(2) - (3)])); if ((yyval.interm.intermTypedNode) == 0) { context->binaryOpError((yylsp[(2) - (3)]), ",", (yyvsp[(1) - (3)].interm.intermTypedNode)->getCompleteString(), (yyvsp[(3) - (3)].interm.intermTypedNode)->getCompleteString()); context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(3) - (3)].interm.intermTypedNode); } } break; case 71: { if (context->constErrorCheck((yyvsp[(1) - (1)].interm.intermTypedNode))) context->recover(); (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 72: { TFunction &function = *((yyvsp[(1) - (2)].interm).function); TIntermAggregate *prototype = new TIntermAggregate; prototype->setType(function.getReturnType()); prototype->setName(function.getName()); for (size_t i = 0; i < function.getParamCount(); i++) { const TParameter &param = function.getParam(i); if (param.name != 0) { TVariable variable(param.name, *param.type); prototype = context->intermediate.growAggregate(prototype, context->intermediate.addSymbol(variable.getUniqueId(), variable.getName(), variable.getType(), (yylsp[(1) - (2)])), (yylsp[(1) - (2)])); } else { prototype = context->intermediate.growAggregate(prototype, context->intermediate.addSymbol(0, "", *param.type, (yylsp[(1) - (2)])), (yylsp[(1) - (2)])); } } prototype->setOp(EOpPrototype); (yyval.interm.intermNode) = prototype; context->symbolTable.pop(); } break; case 73: { if ((yyvsp[(1) - (2)].interm).intermAggregate) (yyvsp[(1) - (2)].interm).intermAggregate->setOp(EOpDeclaration); (yyval.interm.intermNode) = (yyvsp[(1) - (2)].interm).intermAggregate; } break; case 74: { if (((yyvsp[(2) - (4)].interm.precision) == EbpHigh) && (context->shaderType == SH_FRAGMENT_SHADER) && !context->fragmentPrecisionHigh) { context->error((yylsp[(1) - (4)]), "precision is not supported in fragment shader", "highp"); context->recover(); } if (!context->symbolTable.setDefaultPrecision( (yyvsp[(3) - (4)].interm.type), (yyvsp[(2) - (4)].interm.precision) )) { context->error((yylsp[(1) - (4)]), "illegal type argument for default precision qualifier", getBasicString((yyvsp[(3) - (4)].interm.type).type)); context->recover(); } (yyval.interm.intermNode) = 0; } break; case 75: { // // Multiple declarations of the same function are allowed. // // If this is a definition, the definition production code will check for redefinitions // (we don't know at this point if it's a definition or not). // // Redeclarations are allowed. But, return types and parameter qualifiers must match. // TFunction* prevDec = static_cast<TFunction*>(context->symbolTable.find((yyvsp[(1) - (2)].interm.function)->getMangledName())); if (prevDec) { if (prevDec->getReturnType() != (yyvsp[(1) - (2)].interm.function)->getReturnType()) { context->error((yylsp[(2) - (2)]), "overloaded functions must have the same return type", (yyvsp[(1) - (2)].interm.function)->getReturnType().getBasicString()); context->recover(); } for (size_t i = 0; i < prevDec->getParamCount(); ++i) { if (prevDec->getParam(i).type->getQualifier() != (yyvsp[(1) - (2)].interm.function)->getParam(i).type->getQualifier()) { context->error((yylsp[(2) - (2)]), "overloaded functions must have the same parameter qualifiers", (yyvsp[(1) - (2)].interm.function)->getParam(i).type->getQualifierString()); context->recover(); } } } // // If this is a redeclaration, it could also be a definition, // in which case, we want to use the variable names from this one, and not the one that's // being redeclared. So, pass back up this declaration, not the one in the symbol table. // (yyval.interm).function = (yyvsp[(1) - (2)].interm.function); // We're at the inner scope level of the function's arguments and body statement. // Add the function prototype to the surrounding scope instead. context->symbolTable.getOuterLevel()->insert(*(yyval.interm).function); } break; case 76: { (yyval.interm.function) = (yyvsp[(1) - (1)].interm.function); } break; case 77: { (yyval.interm.function) = (yyvsp[(1) - (1)].interm.function); } break; case 78: { // Add the parameter (yyval.interm.function) = (yyvsp[(1) - (2)].interm.function); if ((yyvsp[(2) - (2)].interm).param.type->getBasicType() != EbtVoid) (yyvsp[(1) - (2)].interm.function)->addParameter((yyvsp[(2) - (2)].interm).param); else delete (yyvsp[(2) - (2)].interm).param.type; } break; case 79: { // // Only first parameter of one-parameter functions can be void // The check for named parameters not being void is done in parameter_declarator // if ((yyvsp[(3) - (3)].interm).param.type->getBasicType() == EbtVoid) { // // This parameter > first is void // context->error((yylsp[(2) - (3)]), "cannot be an argument type except for '(void)'", "void"); context->recover(); delete (yyvsp[(3) - (3)].interm).param.type; } else { // Add the parameter (yyval.interm.function) = (yyvsp[(1) - (3)].interm.function); (yyvsp[(1) - (3)].interm.function)->addParameter((yyvsp[(3) - (3)].interm).param); } } break; case 80: { if ((yyvsp[(1) - (3)].interm.type).qualifier != EvqGlobal && (yyvsp[(1) - (3)].interm.type).qualifier != EvqTemporary) { context->error((yylsp[(2) - (3)]), "no qualifiers allowed for function return", getQualifierString((yyvsp[(1) - (3)].interm.type).qualifier)); context->recover(); } // make sure a sampler is not involved as well... if (context->structQualifierErrorCheck((yylsp[(2) - (3)]), (yyvsp[(1) - (3)].interm.type))) context->recover(); // Add the function as a prototype after parsing it (we do not support recursion) TFunction *function; TType type((yyvsp[(1) - (3)].interm.type)); function = new TFunction((yyvsp[(2) - (3)].lex).string, type); (yyval.interm.function) = function; context->symbolTable.push(); } break; case 81: { if ((yyvsp[(1) - (2)].interm.type).type == EbtVoid) { context->error((yylsp[(2) - (2)]), "illegal use of type 'void'", (yyvsp[(2) - (2)].lex).string->c_str()); context->recover(); } if (context->reservedErrorCheck((yylsp[(2) - (2)]), *(yyvsp[(2) - (2)].lex).string)) context->recover(); TParameter param = {(yyvsp[(2) - (2)].lex).string, new TType((yyvsp[(1) - (2)].interm.type))}; (yyval.interm).param = param; } break; case 82: { // Check that we can make an array out of this type if (context->arrayTypeErrorCheck((yylsp[(3) - (5)]), (yyvsp[(1) - (5)].interm.type))) context->recover(); if (context->reservedErrorCheck((yylsp[(2) - (5)]), *(yyvsp[(2) - (5)].lex).string)) context->recover(); int size; if (context->arraySizeErrorCheck((yylsp[(3) - (5)]), (yyvsp[(4) - (5)].interm.intermTypedNode), size)) context->recover(); (yyvsp[(1) - (5)].interm.type).setArray(true, size); TType* type = new TType((yyvsp[(1) - (5)].interm.type)); TParameter param = { (yyvsp[(2) - (5)].lex).string, type }; (yyval.interm).param = param; } break; case 83: { (yyval.interm) = (yyvsp[(3) - (3)].interm); if (context->paramErrorCheck((yylsp[(3) - (3)]), (yyvsp[(1) - (3)].interm.type).qualifier, (yyvsp[(2) - (3)].interm.qualifier), (yyval.interm).param.type)) context->recover(); } break; case 84: { (yyval.interm) = (yyvsp[(2) - (2)].interm); if (context->parameterSamplerErrorCheck((yylsp[(2) - (2)]), (yyvsp[(1) - (2)].interm.qualifier), *(yyvsp[(2) - (2)].interm).param.type)) context->recover(); if (context->paramErrorCheck((yylsp[(2) - (2)]), EvqTemporary, (yyvsp[(1) - (2)].interm.qualifier), (yyval.interm).param.type)) context->recover(); } break; case 85: { (yyval.interm) = (yyvsp[(3) - (3)].interm); if (context->paramErrorCheck((yylsp[(3) - (3)]), (yyvsp[(1) - (3)].interm.type).qualifier, (yyvsp[(2) - (3)].interm.qualifier), (yyval.interm).param.type)) context->recover(); } break; case 86: { (yyval.interm) = (yyvsp[(2) - (2)].interm); if (context->parameterSamplerErrorCheck((yylsp[(2) - (2)]), (yyvsp[(1) - (2)].interm.qualifier), *(yyvsp[(2) - (2)].interm).param.type)) context->recover(); if (context->paramErrorCheck((yylsp[(2) - (2)]), EvqTemporary, (yyvsp[(1) - (2)].interm.qualifier), (yyval.interm).param.type)) context->recover(); } break; case 87: { (yyval.interm.qualifier) = EvqIn; } break; case 88: { (yyval.interm.qualifier) = EvqIn; } break; case 89: { (yyval.interm.qualifier) = EvqOut; } break; case 90: { (yyval.interm.qualifier) = EvqInOut; } break; case 91: { TParameter param = { 0, new TType((yyvsp[(1) - (1)].interm.type)) }; (yyval.interm).param = param; } break; case 92: { (yyval.interm) = (yyvsp[(1) - (1)].interm); } break; case 93: { if ((yyvsp[(1) - (3)].interm).type.type == EbtInvariant && !(yyvsp[(3) - (3)].lex).symbol) { context->error((yylsp[(3) - (3)]), "undeclared identifier declared as invariant", (yyvsp[(3) - (3)].lex).string->c_str()); context->recover(); } TIntermSymbol* symbol = context->intermediate.addSymbol(0, *(yyvsp[(3) - (3)].lex).string, TType((yyvsp[(1) - (3)].interm).type), (yylsp[(3) - (3)])); (yyval.interm).intermAggregate = context->intermediate.growAggregate((yyvsp[(1) - (3)].interm).intermNode, symbol, (yylsp[(3) - (3)])); if (context->structQualifierErrorCheck((yylsp[(3) - (3)]), (yyval.interm).type)) context->recover(); if (context->nonInitConstErrorCheck((yylsp[(3) - (3)]), *(yyvsp[(3) - (3)].lex).string, (yyval.interm).type, false)) context->recover(); TVariable* variable = 0; if (context->nonInitErrorCheck((yylsp[(3) - (3)]), *(yyvsp[(3) - (3)].lex).string, (yyval.interm).type, variable)) context->recover(); if (symbol && variable) symbol->setId(variable->getUniqueId()); } break; case 94: { if (context->structQualifierErrorCheck((yylsp[(3) - (5)]), (yyvsp[(1) - (5)].interm).type)) context->recover(); if (context->nonInitConstErrorCheck((yylsp[(3) - (5)]), *(yyvsp[(3) - (5)].lex).string, (yyvsp[(1) - (5)].interm).type, true)) context->recover(); (yyval.interm) = (yyvsp[(1) - (5)].interm); if (context->arrayTypeErrorCheck((yylsp[(4) - (5)]), (yyvsp[(1) - (5)].interm).type) || context->arrayQualifierErrorCheck((yylsp[(4) - (5)]), (yyvsp[(1) - (5)].interm).type)) context->recover(); else { (yyvsp[(1) - (5)].interm).type.setArray(true); TVariable* variable; if (context->arrayErrorCheck((yylsp[(4) - (5)]), *(yyvsp[(3) - (5)].lex).string, (yyvsp[(1) - (5)].interm).type, variable)) context->recover(); } } break; case 95: { if (context->structQualifierErrorCheck((yylsp[(3) - (6)]), (yyvsp[(1) - (6)].interm).type)) context->recover(); if (context->nonInitConstErrorCheck((yylsp[(3) - (6)]), *(yyvsp[(3) - (6)].lex).string, (yyvsp[(1) - (6)].interm).type, true)) context->recover(); (yyval.interm) = (yyvsp[(1) - (6)].interm); if (context->arrayTypeErrorCheck((yylsp[(4) - (6)]), (yyvsp[(1) - (6)].interm).type) || context->arrayQualifierErrorCheck((yylsp[(4) - (6)]), (yyvsp[(1) - (6)].interm).type)) context->recover(); else { int size; if (context->arraySizeErrorCheck((yylsp[(4) - (6)]), (yyvsp[(5) - (6)].interm.intermTypedNode), size)) context->recover(); (yyvsp[(1) - (6)].interm).type.setArray(true, size); TVariable* variable = 0; if (context->arrayErrorCheck((yylsp[(4) - (6)]), *(yyvsp[(3) - (6)].lex).string, (yyvsp[(1) - (6)].interm).type, variable)) context->recover(); TType type = TType((yyvsp[(1) - (6)].interm).type); type.setArraySize(size); (yyval.interm).intermAggregate = context->intermediate.growAggregate((yyvsp[(1) - (6)].interm).intermNode, context->intermediate.addSymbol(variable ? variable->getUniqueId() : 0, *(yyvsp[(3) - (6)].lex).string, type, (yylsp[(3) - (6)])), (yylsp[(3) - (6)])); } } break; case 96: { if (context->structQualifierErrorCheck((yylsp[(3) - (5)]), (yyvsp[(1) - (5)].interm).type)) context->recover(); (yyval.interm) = (yyvsp[(1) - (5)].interm); TIntermNode* intermNode; if (!context->executeInitializer((yylsp[(3) - (5)]), *(yyvsp[(3) - (5)].lex).string, (yyvsp[(1) - (5)].interm).type, (yyvsp[(5) - (5)].interm.intermTypedNode), intermNode)) { // // build the intermediate representation // if (intermNode) (yyval.interm).intermAggregate = context->intermediate.growAggregate((yyvsp[(1) - (5)].interm).intermNode, intermNode, (yylsp[(4) - (5)])); else (yyval.interm).intermAggregate = (yyvsp[(1) - (5)].interm).intermAggregate; } else { context->recover(); (yyval.interm).intermAggregate = 0; } } break; case 97: { (yyval.interm).type = (yyvsp[(1) - (1)].interm.type); (yyval.interm).intermAggregate = context->intermediate.makeAggregate(context->intermediate.addSymbol(0, "", TType((yyvsp[(1) - (1)].interm.type)), (yylsp[(1) - (1)])), (yylsp[(1) - (1)])); } break; case 98: { TIntermSymbol* symbol = context->intermediate.addSymbol(0, *(yyvsp[(2) - (2)].lex).string, TType((yyvsp[(1) - (2)].interm.type)), (yylsp[(2) - (2)])); (yyval.interm).intermAggregate = context->intermediate.makeAggregate(symbol, (yylsp[(2) - (2)])); if (context->structQualifierErrorCheck((yylsp[(2) - (2)]), (yyval.interm).type)) context->recover(); if (context->nonInitConstErrorCheck((yylsp[(2) - (2)]), *(yyvsp[(2) - (2)].lex).string, (yyval.interm).type, false)) context->recover(); (yyval.interm).type = (yyvsp[(1) - (2)].interm.type); TVariable* variable = 0; if (context->nonInitErrorCheck((yylsp[(2) - (2)]), *(yyvsp[(2) - (2)].lex).string, (yyval.interm).type, variable)) context->recover(); if (variable && symbol) symbol->setId(variable->getUniqueId()); } break; case 99: { context->error((yylsp[(2) - (4)]), "unsized array declarations not supported", (yyvsp[(2) - (4)].lex).string->c_str()); context->recover(); TIntermSymbol* symbol = context->intermediate.addSymbol(0, *(yyvsp[(2) - (4)].lex).string, TType((yyvsp[(1) - (4)].interm.type)), (yylsp[(2) - (4)])); (yyval.interm).intermAggregate = context->intermediate.makeAggregate(symbol, (yylsp[(2) - (4)])); (yyval.interm).type = (yyvsp[(1) - (4)].interm.type); } break; case 100: { TType type = TType((yyvsp[(1) - (5)].interm.type)); int size; if (context->arraySizeErrorCheck((yylsp[(2) - (5)]), (yyvsp[(4) - (5)].interm.intermTypedNode), size)) context->recover(); type.setArraySize(size); TIntermSymbol* symbol = context->intermediate.addSymbol(0, *(yyvsp[(2) - (5)].lex).string, type, (yylsp[(2) - (5)])); (yyval.interm).intermAggregate = context->intermediate.makeAggregate(symbol, (yylsp[(2) - (5)])); if (context->structQualifierErrorCheck((yylsp[(2) - (5)]), (yyvsp[(1) - (5)].interm.type))) context->recover(); if (context->nonInitConstErrorCheck((yylsp[(2) - (5)]), *(yyvsp[(2) - (5)].lex).string, (yyvsp[(1) - (5)].interm.type), true)) context->recover(); (yyval.interm).type = (yyvsp[(1) - (5)].interm.type); if (context->arrayTypeErrorCheck((yylsp[(3) - (5)]), (yyvsp[(1) - (5)].interm.type)) || context->arrayQualifierErrorCheck((yylsp[(3) - (5)]), (yyvsp[(1) - (5)].interm.type))) context->recover(); else { int size; if (context->arraySizeErrorCheck((yylsp[(3) - (5)]), (yyvsp[(4) - (5)].interm.intermTypedNode), size)) context->recover(); (yyvsp[(1) - (5)].interm.type).setArray(true, size); TVariable* variable = 0; if (context->arrayErrorCheck((yylsp[(3) - (5)]), *(yyvsp[(2) - (5)].lex).string, (yyvsp[(1) - (5)].interm.type), variable)) context->recover(); if (variable && symbol) symbol->setId(variable->getUniqueId()); } } break; case 101: { if (context->structQualifierErrorCheck((yylsp[(2) - (4)]), (yyvsp[(1) - (4)].interm.type))) context->recover(); (yyval.interm).type = (yyvsp[(1) - (4)].interm.type); TIntermNode* intermNode; if (!context->executeInitializer((yylsp[(2) - (4)]), *(yyvsp[(2) - (4)].lex).string, (yyvsp[(1) - (4)].interm.type), (yyvsp[(4) - (4)].interm.intermTypedNode), intermNode)) { // // Build intermediate representation // if(intermNode) (yyval.interm).intermAggregate = context->intermediate.makeAggregate(intermNode, (yylsp[(3) - (4)])); else (yyval.interm).intermAggregate = 0; } else { context->recover(); (yyval.interm).intermAggregate = 0; } } break; case 102: { VERTEX_ONLY("invariant declaration", (yylsp[(1) - (2)])); if (context->globalErrorCheck((yylsp[(1) - (2)]), context->symbolTable.atGlobalLevel(), "invariant varying")) context->recover(); (yyval.interm).type.setBasic(EbtInvariant, EvqInvariantVaryingOut, (yylsp[(2) - (2)])); if (!(yyvsp[(2) - (2)].lex).symbol) { context->error((yylsp[(2) - (2)]), "undeclared identifier declared as invariant", (yyvsp[(2) - (2)].lex).string->c_str()); context->recover(); (yyval.interm).intermAggregate = 0; } else { TIntermSymbol *symbol = context->intermediate.addSymbol(0, *(yyvsp[(2) - (2)].lex).string, TType((yyval.interm).type), (yylsp[(2) - (2)])); (yyval.interm).intermAggregate = context->intermediate.makeAggregate(symbol, (yylsp[(2) - (2)])); } } break; case 103: { (yyval.interm.type) = (yyvsp[(1) - (1)].interm.type); if ((yyvsp[(1) - (1)].interm.type).array) { context->error((yylsp[(1) - (1)]), "not supported", "first-class array"); context->recover(); (yyvsp[(1) - (1)].interm.type).setArray(false); } } break; case 104: { if ((yyvsp[(2) - (2)].interm.type).array) { context->error((yylsp[(2) - (2)]), "not supported", "first-class array"); context->recover(); (yyvsp[(2) - (2)].interm.type).setArray(false); } if ((yyvsp[(1) - (2)].interm.type).qualifier == EvqAttribute && ((yyvsp[(2) - (2)].interm.type).type == EbtBool || (yyvsp[(2) - (2)].interm.type).type == EbtInt)) { context->error((yylsp[(2) - (2)]), "cannot be bool or int", getQualifierString((yyvsp[(1) - (2)].interm.type).qualifier)); context->recover(); } if (((yyvsp[(1) - (2)].interm.type).qualifier == EvqVaryingIn || (yyvsp[(1) - (2)].interm.type).qualifier == EvqVaryingOut) && ((yyvsp[(2) - (2)].interm.type).type == EbtBool || (yyvsp[(2) - (2)].interm.type).type == EbtInt)) { context->error((yylsp[(2) - (2)]), "cannot be bool or int", getQualifierString((yyvsp[(1) - (2)].interm.type).qualifier)); context->recover(); } (yyval.interm.type) = (yyvsp[(2) - (2)].interm.type); (yyval.interm.type).qualifier = (yyvsp[(1) - (2)].interm.type).qualifier; } break; case 105: { (yyval.interm.type).setBasic(EbtVoid, EvqConst, (yylsp[(1) - (1)])); } break; case 106: { VERTEX_ONLY("attribute", (yylsp[(1) - (1)])); if (context->globalErrorCheck((yylsp[(1) - (1)]), context->symbolTable.atGlobalLevel(), "attribute")) context->recover(); (yyval.interm.type).setBasic(EbtVoid, EvqAttribute, (yylsp[(1) - (1)])); } break; case 107: { if (context->globalErrorCheck((yylsp[(1) - (1)]), context->symbolTable.atGlobalLevel(), "varying")) context->recover(); if (context->shaderType == SH_VERTEX_SHADER) (yyval.interm.type).setBasic(EbtVoid, EvqVaryingOut, (yylsp[(1) - (1)])); else (yyval.interm.type).setBasic(EbtVoid, EvqVaryingIn, (yylsp[(1) - (1)])); } break; case 108: { if (context->globalErrorCheck((yylsp[(1) - (2)]), context->symbolTable.atGlobalLevel(), "invariant varying")) context->recover(); if (context->shaderType == SH_VERTEX_SHADER) (yyval.interm.type).setBasic(EbtVoid, EvqInvariantVaryingOut, (yylsp[(1) - (2)])); else (yyval.interm.type).setBasic(EbtVoid, EvqInvariantVaryingIn, (yylsp[(1) - (2)])); } break; case 109: { if (context->globalErrorCheck((yylsp[(1) - (1)]), context->symbolTable.atGlobalLevel(), "uniform")) context->recover(); (yyval.interm.type).setBasic(EbtVoid, EvqUniform, (yylsp[(1) - (1)])); } break; case 110: { (yyval.interm.type) = (yyvsp[(1) - (1)].interm.type); if ((yyval.interm.type).precision == EbpUndefined) { (yyval.interm.type).precision = context->symbolTable.getDefaultPrecision((yyvsp[(1) - (1)].interm.type).type); if (context->precisionErrorCheck((yylsp[(1) - (1)]), (yyval.interm.type).precision, (yyvsp[(1) - (1)].interm.type).type)) { context->recover(); } } } break; case 111: { (yyval.interm.type) = (yyvsp[(2) - (2)].interm.type); (yyval.interm.type).precision = (yyvsp[(1) - (2)].interm.precision); } break; case 112: { (yyval.interm.precision) = EbpHigh; } break; case 113: { (yyval.interm.precision) = EbpMedium; } break; case 114: { (yyval.interm.precision) = EbpLow; } break; case 115: { (yyval.interm.type) = (yyvsp[(1) - (1)].interm.type); } break; case 116: { (yyval.interm.type) = (yyvsp[(1) - (4)].interm.type); if (context->arrayTypeErrorCheck((yylsp[(2) - (4)]), (yyvsp[(1) - (4)].interm.type))) context->recover(); else { int size; if (context->arraySizeErrorCheck((yylsp[(2) - (4)]), (yyvsp[(3) - (4)].interm.intermTypedNode), size)) context->recover(); (yyval.interm.type).setArray(true, size); } } break; case 117: { TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtVoid, qual, (yylsp[(1) - (1)])); } break; case 118: { TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtFloat, qual, (yylsp[(1) - (1)])); } break; case 119: { TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtInt, qual, (yylsp[(1) - (1)])); } break; case 120: { TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtBool, qual, (yylsp[(1) - (1)])); } break; case 121: { TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtFloat, qual, (yylsp[(1) - (1)])); (yyval.interm.type).setAggregate(2); } break; case 122: { TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtFloat, qual, (yylsp[(1) - (1)])); (yyval.interm.type).setAggregate(3); } break; case 123: { TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtFloat, qual, (yylsp[(1) - (1)])); (yyval.interm.type).setAggregate(4); } break; case 124: { TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtBool, qual, (yylsp[(1) - (1)])); (yyval.interm.type).setAggregate(2); } break; case 125: { TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtBool, qual, (yylsp[(1) - (1)])); (yyval.interm.type).setAggregate(3); } break; case 126: { TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtBool, qual, (yylsp[(1) - (1)])); (yyval.interm.type).setAggregate(4); } break; case 127: { TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtInt, qual, (yylsp[(1) - (1)])); (yyval.interm.type).setAggregate(2); } break; case 128: { TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtInt, qual, (yylsp[(1) - (1)])); (yyval.interm.type).setAggregate(3); } break; case 129: { TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtInt, qual, (yylsp[(1) - (1)])); (yyval.interm.type).setAggregate(4); } break; case 130: { TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtFloat, qual, (yylsp[(1) - (1)])); (yyval.interm.type).setAggregate(2, true); } break; case 131: { TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtFloat, qual, (yylsp[(1) - (1)])); (yyval.interm.type).setAggregate(3, true); } break; case 132: { TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtFloat, qual, (yylsp[(1) - (1)])); (yyval.interm.type).setAggregate(4, true); } break; case 133: { TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtSampler2D, qual, (yylsp[(1) - (1)])); } break; case 134: { TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtSamplerCube, qual, (yylsp[(1) - (1)])); } break; case 135: { if (!context->supportsExtension("GL_OES_EGL_image_external")) { context->error((yylsp[(1) - (1)]), "unsupported type", "samplerExternalOES"); context->recover(); } TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtSamplerExternalOES, qual, (yylsp[(1) - (1)])); } break; case 136: { if (!context->supportsExtension("GL_ARB_texture_rectangle")) { context->error((yylsp[(1) - (1)]), "unsupported type", "sampler2DRect"); context->recover(); } TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtSampler2DRect, qual, (yylsp[(1) - (1)])); } break; case 137: { (yyval.interm.type) = (yyvsp[(1) - (1)].interm.type); (yyval.interm.type).qualifier = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; } break; case 138: { // // This is for user defined type names. The lexical phase looked up the // type. // TType& structure = static_cast<TVariable*>((yyvsp[(1) - (1)].lex).symbol)->getType(); TQualifier qual = context->symbolTable.atGlobalLevel() ? EvqGlobal : EvqTemporary; (yyval.interm.type).setBasic(EbtStruct, qual, (yylsp[(1) - (1)])); (yyval.interm.type).userDef = &structure; } break; case 139: { if (context->enterStructDeclaration((yylsp[(2) - (3)]), *(yyvsp[(2) - (3)].lex).string)) context->recover(); } break; case 140: { if (context->reservedErrorCheck((yylsp[(2) - (6)]), *(yyvsp[(2) - (6)].lex).string)) context->recover(); TType* structure = new TType((yyvsp[(5) - (6)].interm).structure, *(yyvsp[(2) - (6)].lex).string); TVariable* userTypeDef = new TVariable((yyvsp[(2) - (6)].lex).string, *structure, true); if (! context->symbolTable.insert(*userTypeDef)) { context->error((yylsp[(2) - (6)]), "redefinition", (yyvsp[(2) - (6)].lex).string->c_str(), "struct"); context->recover(); } (yyval.interm.type).setBasic(EbtStruct, EvqTemporary, (yylsp[(1) - (6)])); (yyval.interm.type).userDef = structure; context->exitStructDeclaration(); } break; case 141: { if (context->enterStructDeclaration((yylsp[(2) - (2)]), *(yyvsp[(2) - (2)].lex).string)) context->recover(); } break; case 142: { TType* structure = new TType((yyvsp[(4) - (5)].interm).structure, TString("")); (yyval.interm.type).setBasic(EbtStruct, EvqTemporary, (yylsp[(1) - (5)])); (yyval.interm.type).userDef = structure; context->exitStructDeclaration(); } break; case 143: { (yyval.interm) = (yyvsp[(1) - (1)].interm); } break; case 144: { (yyval.interm) = (yyvsp[(1) - (2)].interm); for (size_t i = 0; i < (yyvsp[(2) - (2)].interm).structure->size(); ++i) { TType* field = (*(yyvsp[(2) - (2)].interm).structure)[i]; for (size_t j = 0; j < (yyval.interm).structure->size(); ++j) { if ((*(yyval.interm).structure)[j]->getFieldName() == field->getFieldName()) { context->error((yylsp[(2) - (2)]), "duplicate field name in structure:", "struct", field->getFieldName().c_str()); context->recover(); } } (yyval.interm).structure->push_back(field); } } break; case 145: { (yyval.interm) = (yyvsp[(2) - (3)].interm); if (context->voidErrorCheck((yylsp[(1) - (3)]), (*(yyvsp[(2) - (3)].interm).structure)[0]->getFieldName(), (yyvsp[(1) - (3)].interm.type))) { context->recover(); } for (unsigned int i = 0; i < (yyval.interm).structure->size(); ++i) { // // Careful not to replace already known aspects of type, like array-ness // TType* type = (*(yyval.interm).structure)[i]; type->setBasicType((yyvsp[(1) - (3)].interm.type).type); type->setNominalSize((yyvsp[(1) - (3)].interm.type).size); type->setMatrix((yyvsp[(1) - (3)].interm.type).matrix); type->setPrecision((yyvsp[(1) - (3)].interm.type).precision); // don't allow arrays of arrays if (type->isArray()) { if (context->arrayTypeErrorCheck((yylsp[(1) - (3)]), (yyvsp[(1) - (3)].interm.type))) context->recover(); } if ((yyvsp[(1) - (3)].interm.type).array) type->setArraySize((yyvsp[(1) - (3)].interm.type).arraySize); if ((yyvsp[(1) - (3)].interm.type).userDef) { type->setStruct((yyvsp[(1) - (3)].interm.type).userDef->getStruct()); type->setTypeName((yyvsp[(1) - (3)].interm.type).userDef->getTypeName()); } if (context->structNestingErrorCheck((yylsp[(1) - (3)]), *type)) { context->recover(); } } } break; case 146: { (yyval.interm).structure = NewPoolTTypeList(); (yyval.interm).structure->push_back((yyvsp[(1) - (1)].interm.field)); } break; case 147: { (yyval.interm).structure->push_back((yyvsp[(3) - (3)].interm.field)); } break; case 148: { if (context->reservedErrorCheck((yylsp[(1) - (1)]), *(yyvsp[(1) - (1)].lex).string)) context->recover(); (yyval.interm.field) = new TType(EbtVoid, EbpUndefined); (yyval.interm.field)->setFieldName(*(yyvsp[(1) - (1)].lex).string); } break; case 149: { if (context->reservedErrorCheck((yylsp[(1) - (4)]), *(yyvsp[(1) - (4)].lex).string)) context->recover(); (yyval.interm.field) = new TType(EbtVoid, EbpUndefined); (yyval.interm.field)->setFieldName(*(yyvsp[(1) - (4)].lex).string); int size; if (context->arraySizeErrorCheck((yylsp[(2) - (4)]), (yyvsp[(3) - (4)].interm.intermTypedNode), size)) context->recover(); (yyval.interm.field)->setArraySize(size); } break; case 150: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 151: { (yyval.interm.intermNode) = (yyvsp[(1) - (1)].interm.intermNode); } break; case 152: { (yyval.interm.intermNode) = (yyvsp[(1) - (1)].interm.intermAggregate); } break; case 153: { (yyval.interm.intermNode) = (yyvsp[(1) - (1)].interm.intermNode); } break; case 154: { (yyval.interm.intermNode) = (yyvsp[(1) - (1)].interm.intermNode); } break; case 155: { (yyval.interm.intermNode) = (yyvsp[(1) - (1)].interm.intermNode); } break; case 156: { (yyval.interm.intermNode) = (yyvsp[(1) - (1)].interm.intermNode); } break; case 157: { (yyval.interm.intermNode) = (yyvsp[(1) - (1)].interm.intermNode); } break; case 158: { (yyval.interm.intermNode) = (yyvsp[(1) - (1)].interm.intermNode); } break; case 159: { (yyval.interm.intermAggregate) = 0; } break; case 160: { context->symbolTable.push(); } break; case 161: { context->symbolTable.pop(); } break; case 162: { if ((yyvsp[(3) - (5)].interm.intermAggregate) != 0) { (yyvsp[(3) - (5)].interm.intermAggregate)->setOp(EOpSequence); (yyvsp[(3) - (5)].interm.intermAggregate)->setLine((yyloc)); } (yyval.interm.intermAggregate) = (yyvsp[(3) - (5)].interm.intermAggregate); } break; case 163: { (yyval.interm.intermNode) = (yyvsp[(1) - (1)].interm.intermNode); } break; case 164: { (yyval.interm.intermNode) = (yyvsp[(1) - (1)].interm.intermNode); } break; case 165: { context->symbolTable.push(); } break; case 166: { context->symbolTable.pop(); (yyval.interm.intermNode) = (yyvsp[(2) - (2)].interm.intermNode); } break; case 167: { context->symbolTable.push(); } break; case 168: { context->symbolTable.pop(); (yyval.interm.intermNode) = (yyvsp[(2) - (2)].interm.intermNode); } break; case 169: { (yyval.interm.intermNode) = 0; } break; case 170: { if ((yyvsp[(2) - (3)].interm.intermAggregate)) { (yyvsp[(2) - (3)].interm.intermAggregate)->setOp(EOpSequence); (yyvsp[(2) - (3)].interm.intermAggregate)->setLine((yyloc)); } (yyval.interm.intermNode) = (yyvsp[(2) - (3)].interm.intermAggregate); } break; case 171: { (yyval.interm.intermAggregate) = context->intermediate.makeAggregate((yyvsp[(1) - (1)].interm.intermNode), (yyloc)); } break; case 172: { (yyval.interm.intermAggregate) = context->intermediate.growAggregate((yyvsp[(1) - (2)].interm.intermAggregate), (yyvsp[(2) - (2)].interm.intermNode), (yyloc)); } break; case 173: { (yyval.interm.intermNode) = 0; } break; case 174: { (yyval.interm.intermNode) = static_cast<TIntermNode*>((yyvsp[(1) - (2)].interm.intermTypedNode)); } break; case 175: { if (context->boolErrorCheck((yylsp[(1) - (5)]), (yyvsp[(3) - (5)].interm.intermTypedNode))) context->recover(); (yyval.interm.intermNode) = context->intermediate.addSelection((yyvsp[(3) - (5)].interm.intermTypedNode), (yyvsp[(5) - (5)].interm.nodePair), (yylsp[(1) - (5)])); } break; case 176: { (yyval.interm.nodePair).node1 = (yyvsp[(1) - (3)].interm.intermNode); (yyval.interm.nodePair).node2 = (yyvsp[(3) - (3)].interm.intermNode); } break; case 177: { (yyval.interm.nodePair).node1 = (yyvsp[(1) - (1)].interm.intermNode); (yyval.interm.nodePair).node2 = 0; } break; case 178: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); if (context->boolErrorCheck((yyvsp[(1) - (1)].interm.intermTypedNode)->getLine(), (yyvsp[(1) - (1)].interm.intermTypedNode))) context->recover(); } break; case 179: { TIntermNode* intermNode; if (context->structQualifierErrorCheck((yylsp[(2) - (4)]), (yyvsp[(1) - (4)].interm.type))) context->recover(); if (context->boolErrorCheck((yylsp[(2) - (4)]), (yyvsp[(1) - (4)].interm.type))) context->recover(); if (!context->executeInitializer((yylsp[(2) - (4)]), *(yyvsp[(2) - (4)].lex).string, (yyvsp[(1) - (4)].interm.type), (yyvsp[(4) - (4)].interm.intermTypedNode), intermNode)) (yyval.interm.intermTypedNode) = (yyvsp[(4) - (4)].interm.intermTypedNode); else { context->recover(); (yyval.interm.intermTypedNode) = 0; } } break; case 180: { context->symbolTable.push(); ++context->loopNestingLevel; } break; case 181: { context->symbolTable.pop(); (yyval.interm.intermNode) = context->intermediate.addLoop(ELoopWhile, 0, (yyvsp[(4) - (6)].interm.intermTypedNode), 0, (yyvsp[(6) - (6)].interm.intermNode), (yylsp[(1) - (6)])); --context->loopNestingLevel; } break; case 182: { ++context->loopNestingLevel; } break; case 183: { if (context->boolErrorCheck((yylsp[(8) - (8)]), (yyvsp[(6) - (8)].interm.intermTypedNode))) context->recover(); (yyval.interm.intermNode) = context->intermediate.addLoop(ELoopDoWhile, 0, (yyvsp[(6) - (8)].interm.intermTypedNode), 0, (yyvsp[(3) - (8)].interm.intermNode), (yylsp[(4) - (8)])); --context->loopNestingLevel; } break; case 184: { context->symbolTable.push(); ++context->loopNestingLevel; } break; case 185: { context->symbolTable.pop(); (yyval.interm.intermNode) = context->intermediate.addLoop(ELoopFor, (yyvsp[(4) - (7)].interm.intermNode), reinterpret_cast<TIntermTyped*>((yyvsp[(5) - (7)].interm.nodePair).node1), reinterpret_cast<TIntermTyped*>((yyvsp[(5) - (7)].interm.nodePair).node2), (yyvsp[(7) - (7)].interm.intermNode), (yylsp[(1) - (7)])); --context->loopNestingLevel; } break; case 186: { (yyval.interm.intermNode) = (yyvsp[(1) - (1)].interm.intermNode); } break; case 187: { (yyval.interm.intermNode) = (yyvsp[(1) - (1)].interm.intermNode); } break; case 188: { (yyval.interm.intermTypedNode) = (yyvsp[(1) - (1)].interm.intermTypedNode); } break; case 189: { (yyval.interm.intermTypedNode) = 0; } break; case 190: { (yyval.interm.nodePair).node1 = (yyvsp[(1) - (2)].interm.intermTypedNode); (yyval.interm.nodePair).node2 = 0; } break; case 191: { (yyval.interm.nodePair).node1 = (yyvsp[(1) - (3)].interm.intermTypedNode); (yyval.interm.nodePair).node2 = (yyvsp[(3) - (3)].interm.intermTypedNode); } break; case 192: { if (context->loopNestingLevel <= 0) { context->error((yylsp[(1) - (2)]), "continue statement only allowed in loops", ""); context->recover(); } (yyval.interm.intermNode) = context->intermediate.addBranch(EOpContinue, (yylsp[(1) - (2)])); } break; case 193: { if (context->loopNestingLevel <= 0) { context->error((yylsp[(1) - (2)]), "break statement only allowed in loops", ""); context->recover(); } (yyval.interm.intermNode) = context->intermediate.addBranch(EOpBreak, (yylsp[(1) - (2)])); } break; case 194: { (yyval.interm.intermNode) = context->intermediate.addBranch(EOpReturn, (yylsp[(1) - (2)])); if (context->currentFunctionType->getBasicType() != EbtVoid) { context->error((yylsp[(1) - (2)]), "non-void function must return a value", "return"); context->recover(); } } break; case 195: { (yyval.interm.intermNode) = context->intermediate.addBranch(EOpReturn, (yyvsp[(2) - (3)].interm.intermTypedNode), (yylsp[(1) - (3)])); context->functionReturnsValue = true; if (context->currentFunctionType->getBasicType() == EbtVoid) { context->error((yylsp[(1) - (3)]), "void function cannot return a value", "return"); context->recover(); } else if (*(context->currentFunctionType) != (yyvsp[(2) - (3)].interm.intermTypedNode)->getType()) { context->error((yylsp[(1) - (3)]), "function return is not matching type:", "return"); context->recover(); } } break; case 196: { FRAG_ONLY("discard", (yylsp[(1) - (2)])); (yyval.interm.intermNode) = context->intermediate.addBranch(EOpKill, (yylsp[(1) - (2)])); } break; case 197: { (yyval.interm.intermNode) = (yyvsp[(1) - (1)].interm.intermNode); context->treeRoot = (yyval.interm.intermNode); } break; case 198: { (yyval.interm.intermNode) = context->intermediate.growAggregate((yyvsp[(1) - (2)].interm.intermNode), (yyvsp[(2) - (2)].interm.intermNode), (yyloc)); context->treeRoot = (yyval.interm.intermNode); } break; case 199: { (yyval.interm.intermNode) = (yyvsp[(1) - (1)].interm.intermNode); } break; case 200: { (yyval.interm.intermNode) = (yyvsp[(1) - (1)].interm.intermNode); } break; case 201: { TFunction* function = (yyvsp[(1) - (1)].interm).function; const TSymbol *builtIn = context->symbolTable.findBuiltIn(function->getMangledName()); if (builtIn) { context->error((yylsp[(1) - (1)]), "built-in functions cannot be redefined", function->getName().c_str()); context->recover(); } TFunction* prevDec = static_cast<TFunction*>(context->symbolTable.find(function->getMangledName())); // // Note: 'prevDec' could be 'function' if this is the first time we've seen function // as it would have just been put in the symbol table. Otherwise, we're looking up // an earlier occurance. // if (prevDec->isDefined()) { // // Then this function already has a body. // context->error((yylsp[(1) - (1)]), "function already has a body", function->getName().c_str()); context->recover(); } prevDec->setDefined(); // // Raise error message if main function takes any parameters or return anything other than void // if (function->getName() == "main") { if (function->getParamCount() > 0) { context->error((yylsp[(1) - (1)]), "function cannot take any parameter(s)", function->getName().c_str()); context->recover(); } if (function->getReturnType().getBasicType() != EbtVoid) { context->error((yylsp[(1) - (1)]), "", function->getReturnType().getBasicString(), "main function cannot return a value"); context->recover(); } } // // Remember the return type for later checking for RETURN statements. // context->currentFunctionType = &(prevDec->getReturnType()); context->functionReturnsValue = false; // // Insert parameters into the symbol table. // If the parameter has no name, it's not an error, just don't insert it // (could be used for unused args). // // Also, accumulate the list of parameters into the HIL, so lower level code // knows where to find parameters. // TIntermAggregate* paramNodes = new TIntermAggregate; for (size_t i = 0; i < function->getParamCount(); i++) { const TParameter& param = function->getParam(i); if (param.name != 0) { TVariable *variable = new TVariable(param.name, *param.type); // // Insert the parameters with name in the symbol table. // if (! context->symbolTable.insert(*variable)) { context->error((yylsp[(1) - (1)]), "redefinition", variable->getName().c_str()); context->recover(); delete variable; } // // Add the parameter to the HIL // paramNodes = context->intermediate.growAggregate( paramNodes, context->intermediate.addSymbol(variable->getUniqueId(), variable->getName(), variable->getType(), (yylsp[(1) - (1)])), (yylsp[(1) - (1)])); } else { paramNodes = context->intermediate.growAggregate(paramNodes, context->intermediate.addSymbol(0, "", *param.type, (yylsp[(1) - (1)])), (yylsp[(1) - (1)])); } } context->intermediate.setAggregateOperator(paramNodes, EOpParameters, (yylsp[(1) - (1)])); (yyvsp[(1) - (1)].interm).intermAggregate = paramNodes; context->loopNestingLevel = 0; } break; case 202: { //?? Check that all paths return a value if return type != void ? // May be best done as post process phase on intermediate code if (context->currentFunctionType->getBasicType() != EbtVoid && ! context->functionReturnsValue) { context->error((yylsp[(1) - (3)]), "function does not return a value:", "", (yyvsp[(1) - (3)].interm).function->getName().c_str()); context->recover(); } (yyval.interm.intermNode) = context->intermediate.growAggregate((yyvsp[(1) - (3)].interm).intermAggregate, (yyvsp[(3) - (3)].interm.intermNode), (yyloc)); context->intermediate.setAggregateOperator((yyval.interm.intermNode), EOpFunction, (yylsp[(1) - (3)])); (yyval.interm.intermNode)->getAsAggregate()->setName((yyvsp[(1) - (3)].interm).function->getMangledName().c_str()); (yyval.interm.intermNode)->getAsAggregate()->setType((yyvsp[(1) - (3)].interm).function->getReturnType()); // store the pragma information for debug and optimize and other vendor specific // information. This information can be queried from the parse tree (yyval.interm.intermNode)->getAsAggregate()->setOptimize(context->pragma().optimize); (yyval.interm.intermNode)->getAsAggregate()->setDebug(context->pragma().debug); context->symbolTable.pop(); } break; default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; *++yylsp = yyloc; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (&yylloc, context, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (&yylloc, context, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } yyerror_range[1] = yylloc; if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, &yylloc, context); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; yyerror_range[1] = yylsp[1-yylen]; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yyerror_range[1] = *yylsp; yydestruct ("Error: popping", yystos[yystate], yyvsp, yylsp, context); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END yyerror_range[2] = yylloc; /* Using YYLLOC is tempting, but would change the location of the lookahead. YYLOC is available though. */ YYLLOC_DEFAULT (yyloc, yyerror_range, 2); *++yylsp = yyloc; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (&yylloc, context, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc, context); } /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yylsp, context); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); } void yyerror(YYLTYPE* yylloc, TParseContext* context, const char* reason) { context->error(*yylloc, reason, ""); context->recover(); } int glslang_parse(TParseContext* context) { return yyparse(context); }
C++
// // Copyright (c) 2002-2011 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/OutputESSL.h" TOutputESSL::TOutputESSL(TInfoSinkBase& objSink, ShArrayIndexClampingStrategy clampingStrategy, ShHashFunction64 hashFunction, NameMap& nameMap, TSymbolTable& symbolTable) : TOutputGLSLBase(objSink, clampingStrategy, hashFunction, nameMap, symbolTable) { } bool TOutputESSL::writeVariablePrecision(TPrecision precision) { if (precision == EbpUndefined) return false; TInfoSinkBase& out = objSink(); out << getPrecisionString(precision); return true; }
C++
// // Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // // Symbol table for parsing. Most functionaliy and main ideas // are documented in the header file. // #if defined(_MSC_VER) #pragma warning(disable: 4718) #endif #include "compiler/SymbolTable.h" #include <stdio.h> #include <algorithm> #include <climits> TType::TType(const TPublicType &p) : type(p.type), precision(p.precision), qualifier(p.qualifier), size(p.size), matrix(p.matrix), array(p.array), arraySize(p.arraySize), structure(0), structureSize(0), deepestStructNesting(0), fieldName(0), mangled(0), typeName(0) { if (p.userDef) { structure = p.userDef->getStruct(); typeName = NewPoolTString(p.userDef->getTypeName().c_str()); computeDeepestStructNesting(); } } // // 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 EbtSampler2D: mangledName += "s2"; break; case EbtSamplerCube: mangledName += "sC"; break; case EbtStruct: mangledName += "struct-"; if (typeName) mangledName += *typeName; {// support MSVC++6.0 for (unsigned int i = 0; i < structure->size(); ++i) { mangledName += '-'; (*structure)[i]->buildMangledName(mangledName); } } default: break; } mangledName += static_cast<char>('0' + getNominalSize()); if (isArray()) { char buf[20]; snprintf(buf, sizeof(buf), "%d", arraySize); mangledName += '['; mangledName += buf; mangledName += ']'; } } size_t TType::getObjectSize() const { size_t totalSize = 0; if (getBasicType() == EbtStruct) totalSize = getStructSize(); else if (matrix) totalSize = size * size; else totalSize = size; if (isArray()) { size_t arraySize = getArraySize(); if (arraySize > INT_MAX / totalSize) totalSize = INT_MAX; else totalSize *= arraySize; } return totalSize; } size_t TType::getStructSize() const { if (!getStruct()) { assert(false && "Not a struct"); return 0; } if (structureSize == 0) { for (TTypeList::const_iterator tl = getStruct()->begin(); tl != getStruct()->end(); tl++) { size_t fieldSize = (*tl)->getObjectSize(); if (fieldSize > INT_MAX - structureSize) structureSize = INT_MAX; else structureSize += fieldSize; } } return structureSize; } void TType::computeDeepestStructNesting() { if (!getStruct()) { return; } int maxNesting = 0; for (TTypeList::const_iterator tl = getStruct()->begin(); tl != getStruct()->end(); ++tl) { maxNesting = std::max(maxNesting, (*tl)->getDeepestStructNesting()); } deepestStructNesting = 1 + maxNesting; } bool TType::isStructureContainingArrays() const { if (!structure) { return false; } for (TTypeList::const_iterator member = structure->begin(); member != structure->end(); member++) { if ((*member)->isArray() || (*member)->isStructureContainingArrays()) { return true; } } return false; } // // Dump functions. // void TVariable::dump(TInfoSink& infoSink) const { infoSink.debug << getName().c_str() << ": " << type.getQualifierString() << " " << type.getPrecisionString() << " " << 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); } } } // // Change all function entries in the table with the non-mangled name // to be related to the provided built-in extension. This is a low // performance operation, and only intended for symbol tables that // live across a large number of compiles. // void TSymbolTableLevel::relateToExtension(const char* name, const TString& ext) { for (tLevel::iterator it = level.begin(); it != level.end(); ++it) { TSymbol* symbol = it->second; if (symbol->getName() == name) symbol->relateToExtension(ext); } }
C++
// // Copyright (c) 2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include <math.h> #include <stdlib.h> #include "util.h" #ifdef _MSC_VER #include <locale.h> #else #include <sstream> #endif double atof_dot(const char *str) { #ifdef _MSC_VER _locale_t l = _create_locale(LC_NUMERIC, "C"); double result = _atof_l(str, l); _free_locale(l); return result; #else double result; std::istringstream s(str); std::locale l("C"); s.imbue(l); s >> result; return result; #endif }
C++
// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef _EXTENSION_BEHAVIOR_INCLUDED_ #define _EXTENSION_BEHAVIOR_INCLUDED_ #include <map> #include <string> typedef enum { EBhRequire, EBhEnable, EBhWarn, EBhDisable, EBhUndefined } TBehavior; inline const char* getBehaviorString(TBehavior b) { switch(b) { case EBhRequire: return "require"; case EBhEnable: return "enable"; case EBhWarn: return "warn"; case EBhDisable: return "disable"; default: return NULL; } } // Mapping between extension name and behavior. typedef std::map<std::string, TBehavior> TExtensionBehavior; #endif // _EXTENSION_TABLE_INCLUDED_
C++
// // Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_TRANSLATORHLSL_H_ #define COMPILER_TRANSLATORHLSL_H_ #include "compiler/ShHandle.h" #include "compiler/Uniform.h" class TranslatorHLSL : public TCompiler { public: TranslatorHLSL(ShShaderType type, ShShaderSpec spec, ShShaderOutput output); virtual TranslatorHLSL *getAsTranslatorHLSL() { return this; } const sh::ActiveUniforms &getUniforms() { return mActiveUniforms; } protected: virtual void translate(TIntermNode* root); sh::ActiveUniforms mActiveUniforms; ShShaderOutput mOutputType; }; #endif // COMPILER_TRANSLATORHLSL_H_
C++
// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef _INITIALIZE_INCLUDED_ #define _INITIALIZE_INCLUDED_ #include "compiler/Common.h" #include "compiler/ShHandle.h" #include "compiler/SymbolTable.h" typedef TVector<TString> TBuiltInStrings; class TBuiltIns { public: POOL_ALLOCATOR_NEW_DELETE(GlobalPoolAllocator) void initialize(ShShaderType type, ShShaderSpec spec, const ShBuiltInResources& resources, const TExtensionBehavior& extensionBehavior); const TBuiltInStrings& getBuiltInStrings() { return builtInStrings; } protected: TBuiltInStrings builtInStrings; }; void IdentifyBuiltIns(ShShaderType type, ShShaderSpec spec, const ShBuiltInResources& resources, TSymbolTable& symbolTable); void InitExtensionBehavior(const ShBuiltInResources& resources, TExtensionBehavior& extensionBehavior); #endif // _INITIALIZE_INCLUDED_
C++
// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_VERSIONGLSL_H_ #define COMPILER_VERSIONGLSL_H_ #include "GLSLANG/ShaderLang.h" #include "compiler/intermediate.h" // Traverses the intermediate tree to return the minimum GLSL version // required to legally access all built-in features used in the shader. // GLSL 1.1 which is mandated by OpenGL 2.0 provides: // - #version and #extension to declare version and extensions. // - built-in functions refract, exp, and log. // - updated step() to compare x < edge instead of x <= edge. // GLSL 1.2 which is mandated by OpenGL 2.1 provides: // - many changes to reduce differences when compared to the ES specification. // - invariant keyword and its support. // - c++ style name hiding rules. // - built-in variable gl_PointCoord for fragment shaders. // - matrix constructors taking matrix as argument. // - array as "out" function parameters // class TVersionGLSL : public TIntermTraverser { public: TVersionGLSL(ShShaderType type); // Returns 120 if the following is used the shader: // - "invariant", // - "gl_PointCoord", // - matrix/matrix constructors // - array "out" parameters // Else 110 is returned. int getVersion() { return mVersion; } virtual void visitSymbol(TIntermSymbol*); virtual void visitConstantUnion(TIntermConstantUnion*); virtual bool visitBinary(Visit, TIntermBinary*); virtual bool visitUnary(Visit, TIntermUnary*); virtual bool visitSelection(Visit, TIntermSelection*); virtual bool visitAggregate(Visit, TIntermAggregate*); virtual bool visitLoop(Visit, TIntermLoop*); virtual bool visitBranch(Visit, TIntermBranch*); protected: void updateVersion(int version); private: ShShaderType mShaderType; int mVersion; }; #endif // COMPILER_VERSIONGLSL_H_
C++
// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/TranslatorGLSL.h" #include "compiler/TranslatorESSL.h" // // This function must be provided to create the actual // compile object used by higher level code. It returns // a subclass of TCompiler. // TCompiler* ConstructCompiler( ShShaderType type, ShShaderSpec spec, ShShaderOutput output) { switch (output) { case SH_GLSL_OUTPUT: return new TranslatorGLSL(type, spec); case SH_ESSL_OUTPUT: return new TranslatorESSL(type, spec); default: return NULL; } } // // Delete the compiler made by ConstructCompiler // void DeleteCompiler(TCompiler* compiler) { delete compiler; }
C++
// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // // This file contains the posix specific functions // #include "compiler/osinclude.h" #if !defined(ANGLE_OS_POSIX) #error Trying to build a posix specific file in a non-posix build. #endif // // Thread Local Storage Operations // OS_TLSIndex OS_AllocTLSIndex() { pthread_key_t pPoolIndex; // // Create global pool key. // if ((pthread_key_create(&pPoolIndex, NULL)) != 0) { assert(0 && "OS_AllocTLSIndex(): Unable to allocate Thread Local Storage"); return false; } else { return pPoolIndex; } } bool OS_SetTLSValue(OS_TLSIndex nIndex, void *lpvValue) { if (nIndex == OS_INVALID_TLS_INDEX) { assert(0 && "OS_SetTLSValue(): Invalid TLS Index"); return false; } if (pthread_setspecific(nIndex, lpvValue) == 0) return true; else return false; } bool OS_FreeTLSIndex(OS_TLSIndex nIndex) { if (nIndex == OS_INVALID_TLS_INDEX) { assert(0 && "OS_SetTLSValue(): Invalid TLS Index"); return false; } // // Delete the global pool key. // if (pthread_key_delete(nIndex) == 0) return true; else return false; }
C++
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Contains analysis utilities for dealing with HLSL's lack of support for // the use of intrinsic functions which (implicitly or explicitly) compute // gradients of functions with discontinuities. // #ifndef COMPILER_DETECTDISCONTINUITY_H_ #define COMPILER_DETECTDISCONTINUITY_H_ #include "compiler/intermediate.h" namespace sh { // Checks whether a loop can run for a variable number of iterations class DetectLoopDiscontinuity : public TIntermTraverser { public: bool traverse(TIntermNode *node); protected: bool visitBranch(Visit visit, TIntermBranch *node); bool visitLoop(Visit visit, TIntermLoop *loop); bool visitAggregate(Visit visit, TIntermAggregate *node); int mLoopDepth; bool mLoopDiscontinuity; }; bool containsLoopDiscontinuity(TIntermNode *node); // Checks for intrinsic functions which compute gradients class DetectGradientOperation : public TIntermTraverser { public: bool traverse(TIntermNode *node); protected: bool visitUnary(Visit visit, TIntermUnary *node); bool visitAggregate(Visit visit, TIntermAggregate *node); bool mGradientOperation; }; bool containsGradientOperation(TIntermNode *node); } #endif // COMPILER_DETECTDISCONTINUITY_H_
C++
// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef _LOCAL_INTERMEDIATE_INCLUDED_ #define _LOCAL_INTERMEDIATE_INCLUDED_ #include "GLSLANG/ShaderLang.h" #include "compiler/intermediate.h" #include "compiler/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&, const TSourceLoc&); TIntermTyped* addConversion(TOperator, const TType&, TIntermTyped*); TIntermTyped* addBinaryMath(TOperator op, TIntermTyped* left, TIntermTyped* right, const TSourceLoc&, TSymbolTable&); TIntermTyped* addAssign(TOperator op, TIntermTyped* left, TIntermTyped* right, const TSourceLoc&); TIntermTyped* addIndex(TOperator op, TIntermTyped* base, TIntermTyped* index, const TSourceLoc&); TIntermTyped* addUnaryMath(TOperator op, TIntermNode* child, const TSourceLoc&, TSymbolTable&); TIntermAggregate* growAggregate(TIntermNode* left, TIntermNode* right, const TSourceLoc&); TIntermAggregate* makeAggregate(TIntermNode* node, const TSourceLoc&); TIntermAggregate* setAggregateOperator(TIntermNode*, TOperator, const TSourceLoc&); TIntermNode* addSelection(TIntermTyped* cond, TIntermNodePair code, const TSourceLoc&); TIntermTyped* addSelection(TIntermTyped* cond, TIntermTyped* trueBlock, TIntermTyped* falseBlock, const TSourceLoc&); TIntermTyped* addComma(TIntermTyped* left, TIntermTyped* right, const TSourceLoc&); TIntermConstantUnion* addConstantUnion(ConstantUnion*, const TType&, const TSourceLoc&); TIntermTyped* promoteConstantUnion(TBasicType, TIntermConstantUnion*) ; bool parseConstTree(const TSourceLoc&, TIntermNode*, ConstantUnion*, TOperator, TSymbolTable&, TType, bool singleConstantParam = false); TIntermNode* addLoop(TLoopType, TIntermNode*, TIntermTyped*, TIntermTyped*, TIntermNode*, const TSourceLoc&); TIntermBranch* addBranch(TOperator, const TSourceLoc&); TIntermBranch* addBranch(TOperator, TIntermTyped*, const TSourceLoc&); TIntermTyped* addSwizzle(TVectorFields&, const TSourceLoc&); bool postProcess(TIntermNode*); void remove(TIntermNode*); void outputTree(TIntermNode*); private: void operator=(TIntermediate&); // prevent assignments TInfoSink& infoSink; }; #endif // _LOCAL_INTERMEDIATE_INCLUDED_
C++