Ejemplo n.º 1
0
        ConstantDeclaration ParseConstantDeclaration()
        {
            ReadNextToken();              //skip constant

            string identifier = fCurrentToken.Value;

            ReadNextToken();              //skip identifier
            fCurrentToken = fLexicalAnalyser.SkipExpected(TokenType.Symbol, ":");

            string subtypeIndication = fCurrentToken.Value;

            ReadNextToken();



            //FIX 25.06.19: This is a fix to allow for constants of record type. This issue was realised when parsing intea_pif_p.vhd
            //Need to make class for record type constant
            if (RecordTypeList.Any(x => x.Identifier == subtypeIndication))
            {
                RecordTypeDeclaration recordConstant = RecordTypeList.Find(x => x.Identifier == subtypeIndication);
                ConstantRecordTypeList.Add(recordConstant);
                ConstantDeclaration ParsedConstant = new ConstantDeclaration(identifier, null, 0);
                fCurrentToken = fLexicalAnalyser.SkipOver(TokenType.Symbol, ";");
                return(ParsedConstant);
            }
            else
            {
                // In a package, a constant may be deferred. This means its value is defined in the package body. the value may be changed by re-analysing only the package body. we do not want this
                if (!fCurrentToken.Equals(TokenType.Symbol, ":="))
                {
                    throw new ParserException("Constants value definition must not be deferred to body");
                }

                ReadNextToken();

                Node result = ParseExpression();
                ConstantDeclaration ParsedConstant = new ConstantDeclaration(identifier, subtypeIndication, result.Eval());
                ConstantList.Add(ParsedConstant);
                ReadNextToken();
                return(ParsedConstant);
            }
        }
Ejemplo n.º 2
0
        //-----------------------------------------------------------
        private string Visit(ConstantDeclaration node, Table table)
        {
            string retString = "";

            if (table is GlobalSymbolTable)
            {
                retString += Visit((dynamic)node[0], table);
                retString += "\t\tstsfld " + CILTypes[GSTable[node.AnchorToken.Lexeme].TheType] + " 'ChimeraProgram'::" + "'" + node.AnchorToken.Lexeme + "'\n";
            }
            else
            {
                LocalSymbolTable lstable = table as LocalSymbolTable;
                var consName             = node.AnchorToken.Lexeme;
                retString += "\t\t.locals init (" + CILTypes[lstable[consName].LocalType] + " '" + consName + "')\n";
                retString += Visit((dynamic)node[0], table);
                retString += "\t\tstloc '" + consName + "'\n";
            }

            return(retString);
        }
Ejemplo n.º 3
0
        public Node ConstantDeclaration()
        {
            var result = new ConstantDeclaration()
            {
                AnchorToken = Expect(TokenCategory.IDENTIFIER)
            };

            Expect(TokenCategory.ASSIGN);
            if (CurrentToken != TokenCategory.BRACE_OPEN)
            {
                result.Add(SimpleLiteral());
            }
            else if (CurrentToken == TokenCategory.BRACE_OPEN)
            {
                result.Add(List());
            }


            Expect(TokenCategory.SEMICOLON);
            return(result);
        }
Ejemplo n.º 4
0
        private HlslTreeNode[] TryGetMatrixRow(DotProductContext firstDotProductNode)
        {
            if (firstDotProductNode.Value1[0] is RegisterInputNode value1)
            {
                ConstantDeclaration constant = _registers.FindConstant(value1);
                if (constant != null && constant.Rows > 1)
                {
                    return(firstDotProductNode.Value1);
                }
            }

            if (firstDotProductNode.Value2[0] is RegisterInputNode value2)
            {
                ConstantDeclaration constant = _registers.FindConstant(value2);
                if (constant != null && constant.Rows > 1)
                {
                    return(firstDotProductNode.Value2);
                }
            }

            return(null);
        }
Ejemplo n.º 5
0
        public string GetRegisterName(RegisterKey registerKey)
        {
            var decl = _registerDeclarations[registerKey];

            switch (registerKey.Type)
            {
            case RegisterType.Texture:
            case RegisterType.Input:
                return((MethodInputRegisters.Count == 1) ? decl.Name : ("i." + decl.Name));

            case RegisterType.RastOut:
            case RegisterType.Output:
            case RegisterType.AttrOut:
            case RegisterType.ColorOut:
                return((MethodOutputRegisters.Count == 1) ? decl.Name : ("o." + decl.Name));

            case RegisterType.Const:
                var constDecl      = FindConstant(registerKey.Number);
                var relativeOffset = registerKey.Number - constDecl.RegisterIndex;
                var name           = constDecl.GetMemberNameByOffset(relativeOffset);
                var data           = constDecl.GetRegisterTypeByOffset(relativeOffset);

                // sanity check
                var registersOccupied = data.Type.ParameterClass == ParameterClass.MatrixColumns
                                                ? data.Type.Columns
                                                : data.Type.Rows;
                if (registersOccupied == 1 && data.RegisterIndex != registerKey.Number)
                {
                    throw new InvalidOperationException();
                }

                switch (data.Type.ParameterType)
                {
                case ParameterType.Float:
                    if (registersOccupied == 1)
                    {
                        return(name);
                    }
                    var subElement = (registerKey.Number - data.RegisterIndex).ToString();
                    return(ColumnMajorOrder
                                                                ? $"transpose({name})[{subElement}]" // subElement = col
                                                                : $"{name}[{subElement}]");          // subElement = row;

                default:
                    throw new NotImplementedException();
                }

            case RegisterType.Sampler:
                ConstantDeclaration samplerDecl = FindConstant(RegisterSet.Sampler, registerKey.Number);
                if (samplerDecl != null)
                {
                    var offset = registerKey.Number - samplerDecl.RegisterIndex;
                    return(samplerDecl.GetMemberNameByOffset(offset));
                }
                else
                {
                    throw new NotImplementedException();
                }

            case RegisterType.MiscType:
                switch (registerKey.Number)
                {
                case 0:
                    return("vFace");

                case 1:
                    return("vPos");

                default:
                    throw new NotImplementedException();
                }

            case RegisterType.Temp:
                return(registerKey.ToString());

            default:
                throw new NotImplementedException();
            }
        }
Ejemplo n.º 6
0
        public string GetSourceName(InstructionToken instruction, int srcIndex)
        {
            string      sourceRegisterName;
            RegisterKey registerKey  = instruction.GetParamRegisterKey(srcIndex);
            var         registerType = instruction.GetParamRegisterType(srcIndex);

            switch (registerType)
            {
            case RegisterType.Const:
            case RegisterType.Const2:
            case RegisterType.Const3:
            case RegisterType.Const4:
            case RegisterType.ConstBool:
            case RegisterType.ConstInt:
                sourceRegisterName = GetSourceConstantName(instruction, srcIndex);
                if (sourceRegisterName != null)
                {
                    return(sourceRegisterName);
                }

                ParameterType parameterType;
                switch (registerType)
                {
                case RegisterType.Const:
                case RegisterType.Const2:
                case RegisterType.Const3:
                case RegisterType.Const4:
                    parameterType = ParameterType.Float;
                    break;

                case RegisterType.ConstBool:
                    parameterType = ParameterType.Bool;
                    break;

                case RegisterType.ConstInt:
                    parameterType = ParameterType.Int;
                    break;

                default:
                    throw new NotImplementedException();
                }
                var registerNumber       = instruction.GetParamRegisterNumber(srcIndex);
                ConstantDeclaration decl = FindConstant(registerNumber);
                if (decl == null)
                {
                    // Constant register not found in def statements nor the constant table
                    //TODO:
                    return($"Error {registerType}{registerNumber}");
                    //throw new NotImplementedException();
                }
                var totalOffset      = registerNumber - decl.RegisterIndex;
                var data             = decl.GetRegisterTypeByOffset(totalOffset);
                var offsetFromMember = registerNumber - data.RegisterIndex;
                sourceRegisterName = decl.GetMemberNameByOffset(totalOffset);
                if (data.Type.ParameterClass == ParameterClass.MatrixRows)
                {
                    sourceRegisterName = string.Format("{0}[{1}]", decl.Name, offsetFromMember);
                }
                else if (data.Type.ParameterClass == ParameterClass.MatrixColumns)
                {
                    sourceRegisterName = string.Format("transpose({0})[{1}]", decl.Name, offsetFromMember);
                }
                break;

            default:
                sourceRegisterName = GetRegisterName(registerKey);
                break;
            }

            sourceRegisterName = sourceRegisterName ?? instruction.GetParamRegisterName(srcIndex);

            sourceRegisterName += instruction.GetSourceSwizzleName(srcIndex, true);
            return(ApplyModifier(instruction.GetSourceModifier(srcIndex), sourceRegisterName));
        }
Ejemplo n.º 7
0
            public List <object> GetLocalListOfObjects()
            {
                List <object> res = new List <object>();

                foreach (E declaration in this)
                {
                    if (declaration is EnumerationType)
                    {
                        EnumerationType type = declaration as EnumerationType;
                        res.Add(type);


                        //TODO: support overloading
                        foreach (EnumerationLiteral literal in type.Literals)
                        {
                            res.Add(literal);
                        }
                    }
                    else if (declaration is RecordType)
                    {
                        RecordType type = declaration as RecordType;
                        res.Add(type);
                        foreach (VHDL.type.RecordType.ElementDeclaration el in type.Elements)
                        {
                            foreach (string name in el.Identifiers)
                            {
                                res.Add(name);
                            }
                        }
                    }
                    else if (declaration is PhysicalType)
                    {
                        PhysicalType type = declaration as PhysicalType;
                        res.Add(type);
                        res.Add(new PhysicalLiteral(null, type.PrimaryUnit, declaration as PhysicalType));

                        foreach (PhysicalType.Unit unit in type.Units)
                        {
                            res.Add(unit.Identifier);
                        }
                    }
                    else if (declaration is NamedEntity)
                    {
                        INamedEntity identElement = (NamedEntity)declaration;
                        res.Add(declaration);
                    }
                    else if (declaration is SignalDeclaration)
                    {
                        SignalDeclaration objDecl = declaration as SignalDeclaration;
                        foreach (var o in objDecl.Objects)
                        {
                            res.Add(o);
                        }
                    }
                    else if (declaration is ConstantDeclaration)
                    {
                        ConstantDeclaration objDecl = declaration as ConstantDeclaration;
                        foreach (var o in objDecl.Objects)
                        {
                            res.Add(o);
                        }
                    }
                    else if (declaration is VariableDeclaration)
                    {
                        VariableDeclaration objDecl = declaration as VariableDeclaration;
                        foreach (var o in objDecl.Objects)
                        {
                            res.Add(o);
                        }
                    }
                    else if (declaration is FileDeclaration)
                    {
                        FileDeclaration objDecl = declaration as FileDeclaration;
                        foreach (var o in objDecl.Objects)
                        {
                            res.Add(o);
                        }
                    }
                    else if (declaration is Alias)
                    {
                        res.Add(declaration);
                    }
                    else if (declaration is Subtype)
                    {
                        res.Add(declaration);
                    }
                    else if (declaration is UseClause)
                    {
                        UseClause use = declaration as UseClause;
                        res.AddRange(use.Scope.GetLocalListOfObjects());
                    }
                    else if (declaration.GetType().BaseType == typeof(ObjectDeclaration <>))
                    {
                        ObjectDeclaration <VhdlObject> objDecl = declaration as ObjectDeclaration <VhdlObject>;
                        foreach (VhdlObject o in objDecl.Objects)
                        {
                            res.Add(o);
                        }
                    }
                }
                return(res);
            }
Ejemplo n.º 8
0
            public object Resolve(string identifier)
            {
                foreach (E declaration in this)
                {
                    if (declaration is EnumerationType)
                    {
                        EnumerationType type = declaration as EnumerationType;
                        if (identifier.EqualsIdentifier(type.Identifier))
                        {
                            return(type);
                        }

                        //TODO: support overloading
                        foreach (EnumerationLiteral literal in type.Literals)
                        {
                            if (identifier.EqualsIdentifier(literal.ToString()))
                            {
                                return(literal);
                            }
                        }
                    }
                    else if (declaration is RecordType)
                    {
                        RecordType type = declaration as RecordType;
                        if (identifier.EqualsIdentifier(type.Identifier))
                        {
                            return(type);
                        }
                        foreach (VHDL.type.RecordType.ElementDeclaration el in type.Elements)
                        {
                            foreach (string name in el.Identifiers)
                            {
                                if (identifier.EqualsIdentifier(name))
                                {
                                    return(new Variable(name, el.Type));
                                }
                            }
                        }
                    }
                    else if (declaration is PhysicalType)
                    {
                        PhysicalType type = declaration as PhysicalType;
                        if (identifier.EqualsIdentifier(type.Identifier))
                        {
                            return(type);
                        }

                        //TODO: don't use strings for the physical literals
                        if (identifier.EqualsIdentifier(type.PrimaryUnit))
                        {
                            return(new PhysicalLiteral(null, type.PrimaryUnit, declaration as PhysicalType));
                        }

                        foreach (PhysicalType.Unit unit in type.Units)
                        {
                            if (identifier.EqualsIdentifier(unit.Identifier))
                            {
                                return(new PhysicalLiteral(null, unit.Identifier, declaration as PhysicalType));
                            }
                        }
                    }
                    else if (declaration is NamedEntity)
                    {
                        INamedEntity identElement = (NamedEntity)declaration;
                        if (identifier.EqualsIdentifier(identElement.Identifier))
                        {
                            return(declaration);
                        }
                    }
                    else if (declaration is SignalDeclaration)
                    {
                        SignalDeclaration objDecl = declaration as SignalDeclaration;
                        foreach (var o in objDecl.Objects)
                        {
                            if (o.Identifier.EqualsIdentifier(identifier))
                            {
                                return(o);
                            }
                        }
                    }
                    else if (declaration is ConstantDeclaration)
                    {
                        ConstantDeclaration objDecl = declaration as ConstantDeclaration;
                        foreach (var o in objDecl.Objects)
                        {
                            if (o.Identifier.EqualsIdentifier(identifier))
                            {
                                return(o);
                            }
                        }
                    }
                    else if (declaration is VariableDeclaration)
                    {
                        VariableDeclaration objDecl = declaration as VariableDeclaration;
                        foreach (var o in objDecl.Objects)
                        {
                            if (o.Identifier.EqualsIdentifier(identifier))
                            {
                                return(o);
                            }
                        }
                    }
                    else if (declaration is FileDeclaration)
                    {
                        FileDeclaration objDecl = declaration as FileDeclaration;
                        foreach (var o in objDecl.Objects)
                        {
                            if (o.Identifier.EqualsIdentifier(identifier))
                            {
                                return(o);
                            }
                        }
                    }
                    else if (declaration is Alias)
                    {
                        Alias objDecl = declaration as Alias;
                        if (objDecl.Designator.EqualsIdentifier(identifier))
                        {
                            return(objDecl.Aliased);//new Variable(objDecl.Aliased, objDecl.SubtypeIndication);
                        }
                    }
                    else if (declaration is Subtype)
                    {
                        Subtype objDecl = declaration as Subtype;
                        if (objDecl.Identifier.EqualsIdentifier(identifier))
                        {
                            return(objDecl);
                        }
                    }
                    else if (declaration is UseClause)
                    {
                        UseClause use = declaration as UseClause;
                        object    res = use.Scope.resolve(identifier);
                        if (res != null)
                        {
                            return(res);
                        }
                    }
                    else if (declaration.GetType().BaseType == typeof(ObjectDeclaration <>))
                    {
                        ObjectDeclaration <VhdlObject> objDecl = declaration as ObjectDeclaration <VhdlObject>;
                        foreach (VhdlObject o in objDecl.Objects)
                        {
                            if (o.Identifier.EqualsIdentifier(identifier))
                            {
                                return(o);
                            }
                        }
                    }
                }

                return(null);
            }
 /// <summary>
 /// Adds an element with the specified key and value to this StringConstantDeclaration.
 /// </summary>
 /// <param name="key">
 /// The String key of the element to add.
 /// </param>
 /// <param name="value">
 /// The ConstantDeclaration value of the element to add.
 /// </param>
 public virtual void Add(ConstantDeclaration value)
 {
     this.Dictionary.Add(value.Name, value);
 }
Ejemplo n.º 10
0
 public virtual void VisitConstantDeclaration(ConstantDeclaration constantDeclaration)
 {
     DefaultVisit(constantDeclaration);
 }
Ejemplo n.º 11
0
        public MatrixMultiplicationContext TryGetMultiplicationGroup(IList <HlslTreeNode> components)
        {
            const bool allowMatrix = true;

            var first = components[0];
            var firstDotProductNode = _nodeGrouper.DotProductGrouper.TryGetDotProductGroup(first, allowMatrix);

            if (firstDotProductNode == null)
            {
                return(null);
            }

            int dimension = firstDotProductNode.Dimension;

            if (components.Count < dimension)
            {
                return(null);
            }

            HlslTreeNode[] firstMatrixRow = TryGetMatrixRow(firstDotProductNode);
            if (firstMatrixRow == null)
            {
                return(null);
            }

            HlslTreeNode[] vector = firstDotProductNode.Value1 == firstMatrixRow
                                        ? firstDotProductNode.Value2
                                        : firstDotProductNode.Value1;

            var matrixRows = new HlslTreeNode[dimension][];

            matrixRows[0] = firstMatrixRow;
            for (int i = 1; i < dimension; i++)
            {
                var next           = components[i];
                var dotProductNode = _nodeGrouper.DotProductGrouper.TryGetDotProductGroup(next, dimension, allowMatrix);
                if (dotProductNode == null)
                {
                    return(null);
                }

                HlslTreeNode[] matrixRow = TryGetMatrixRow(dotProductNode);
                if (matrixRow == null)
                {
                    return(null);
                }
                matrixRows[i] = matrixRow;

                HlslTreeNode[] nextVector = dotProductNode.Value1 == matrixRow
                                        ? dotProductNode.Value2
                                        : dotProductNode.Value1;
                if (NodeGrouper.IsVectorEquivalent(vector, nextVector) == false)
                {
                    return(null);
                }
            }

            ConstantDeclaration matrix = TryGetMatrixDeclaration(matrixRows);

            if (matrix == null)
            {
                return(null);
            }

            bool matrixByVector = firstMatrixRow
                                  .Cast <RegisterInputNode>()
                                  .All(row => row.ComponentIndex == 0);

            SwizzleVector(vector, firstMatrixRow, matrixByVector);

            return(new MatrixMultiplicationContext(vector, matrix, matrixByVector));
        }
        //-----------------------------------------------------------
        private Type Visit(ConstantDeclaration node, Table table)
        {
            GlobalSymbolTable gstable = table as GlobalSymbolTable;
            LocalSymbolTable  lstable = table as LocalSymbolTable;

            var symbolName = node.AnchorToken.Lexeme;

            if (table is GlobalSymbolTable)
            {
                if (GSTable.Contains(symbolName))
                {
                    throw new SemanticError("Duplicated symbol: " + symbolName, node[0].AnchorToken);
                }
            }
            else if (table is LocalSymbolTable)
            {
                if (lstable.Contains(symbolName))
                {
                    throw new SemanticError("Duplicated symbol: " + symbolName, node[0].AnchorToken);
                }
            }
            else
            {
                throw new TypeAccessException("Expecting either a GlobalSymbolTable or a LocalSymboltable");
            }

            Type nodeType = Visit((dynamic)node[0], table);

            if (node[0] is Lst)
            {
                if (node[0].Count() == 0)
                {
                    throw new SemanticError("Constant lists cannot be empty: " + symbolName, node.AnchorToken);
                }

                dynamic lst;
                if (nodeType == Type.LIST_OF_BOOLEAN)
                {
                    lst = new Boolean[node[0].Count()];
                }
                else if (nodeType == Type.LIST_OF_INTEGER)
                {
                    lst = new Int32[node[0].Count()];
                }
                else if (nodeType == Type.LIST_OF_STRING)
                {
                    lst = new String[node[0].Count()];
                }
                else
                {
                    throw new TypeAccessException("Expecting one of the following node types: LIST_OF_BOOLEAN, LIST_OF_INTEGER, LIST_OF_STRING");
                }

                int i = 0;
                foreach (var n in node[0])
                {
                    lst[i++] = n.ExtractValue();
                }
                if (table is GlobalSymbolTable)
                {
                    gstable[symbolName] = new GlobalSymbol(nodeType, lst);
                }
                else if (table is LocalSymbolTable)
                {
                    lstable[symbolName] = new LocalSymbol(nodeType, lst);
                }
                else
                {
                    throw new TypeAccessException("Expecting either a GlobalSymbolTable or a LocalSymboltable");
                }
            }
            else
            {
                if (table is GlobalSymbolTable)
                {
                    gstable[symbolName] = new GlobalSymbol(nodeType, node[0].ExtractValue());
                }
                else if (table is LocalSymbolTable)
                {
                    lstable[symbolName] = new LocalSymbol(nodeType, node[0].ExtractValue());
                }
                else
                {
                    throw new TypeAccessException("Expecting either a GlobalSymbolTable or a LocalSymboltable");
                }
            }

            return(Type.VOID);
        }
Ejemplo n.º 13
0
        // ParseLeaf is the lowest level of the expression parsers.
        // It is used to extract the fundamental elements of an expression.
        // These elements are numbers, function calls and arrays.
        Node ParseLeaf()
        {
            // NodeNumber:
            // If current token is a number we simply extract it as a NodeNumber.
            if (fCurrentToken.Type == TokenType.Integer)
            {
                var node = new NodeNumber(fCurrentToken.IntValue());
                ReadNextToken();
                return(node);
            }

            // Parenthesis:
            // If an open parenthesis is read, it must be skipped and the expression
            // it encloses must be parsed. We must also check again at the end of the
            // expression if the parenthesis is correctly closed otherwise an exception
            // is thrown.
            if (fCurrentToken.Equals(TokenType.Symbol, "("))
            {
                // Skip '('
                ReadNextToken();

                // Check for "others" statement that is commonly used in VHDL.
                if (fCurrentToken.Equals(TokenType.Word, "others"))
                {
                    fCurrentToken = fLexicalAnalyser.SkipOver(TokenType.Symbol, "'");
                    var node = new NodeNumber(fCurrentToken.IntValue());
                    fCurrentToken = fLexicalAnalyser.SkipOver(TokenType.Symbol, ")");
                    return(node);
                }
                // Else we have an expression inside of parenthesis.
                else
                {
                    // Parse a top-level expression
                    var arguments = new List <Node> ();
                    while (true)
                    {
                        // Parse argument and add to list
                        arguments.Add(ParseAddSubtract());

                        // Is there another argument?
                        if (fCurrentToken.Equals(TokenType.Symbol, ","))
                        {
                            ReadNextToken();
                            continue;
                        }

                        // Get out
                        break;
                    }

                    // Check and skip ')'
                    if (!fCurrentToken.Equals(TokenType.Symbol, ")"))
                    {
                        throw new ParserException("Missing close parenthesis");
                    }
                    ReadNextToken();

                    // Return
                    return(new NodeArray(arguments.ToArray()));
                }
            }

            // Single/Double Quote Literals:
            // In vhdl we can have single digit values enclosed in signle quote literals and longer values
            // enclosed in double quote literals. We must therefore extract the number from within these quotation literals.
            if (fCurrentToken.Equals(TokenType.Symbol, "\"") || fCurrentToken.Equals(TokenType.Symbol, "\'"))
            {
                // Skip '"'
                ReadNextToken();                  //Read the number

                var node = new NodeNumber(fCurrentToken.IntValue());

                ReadNextToken();                  //Skip the number

                // Check and skip ')'
                if (!(fCurrentToken.Equals(TokenType.Symbol, "\"") || fCurrentToken.Equals(TokenType.Symbol, "\'")))
                {
                    throw new ParserException("Missing closing quote literals");
                }
                ReadNextToken();

                // Return
                return(node);
            }

            if (fCurrentToken.Type == TokenType.Word)
            {
                // Parse a top-level expression
                var name = fCurrentToken.Value;
                ReadNextToken();
                if (fCurrentToken.Equals(TokenType.Symbol, "\'"))
                {
                    //Type Attribute has been requested
                    ReadNextToken();
                    var attribute = DetermineAttribute(fCurrentToken.Value, name);
                    var node      = new NodeNumber(attribute);
                    ReadNextToken();                      //Skip the found attribute
                    return(node);
                }
                else if (!fCurrentToken.Equals(TokenType.Symbol, "("))
                {
                    if (ConstantList.Any(x => x.Identifier == name))
                    {
                        ConstantDeclaration result = ConstantList.Find(x => x.Identifier == name);
                        var node = new NodeNumber(result.Value);
                        return(node);
                    }
                    else if (ConstantList.Any(x => x.Identifier == name.ToUpper()))
                    {
                        ConstantDeclaration result = ConstantList.Find(x => x.Identifier == name.ToUpper());
                        var node = new NodeNumber(result.Value);
                        return(node);
                    }
                    else if (ConstantList.Any(x => x.Identifier == name.ToLower()))
                    {
                        ConstantDeclaration result = ConstantList.Find(x => x.Identifier.ToUpper() == name.ToLower());
                        var node = new NodeNumber(result.Value);
                        return(node);
                    }
                    else
                    {
                        throw new ParserException("Constant value is unknown.");
                    }
                }
                else
                {
                    // Function call
                    // Skip parens
                    ReadNextToken();

                    // Parse arguments
                    var arguments = new List <Node> ();
                    while (true)
                    {
                        // Parse argument and add to list
                        arguments.Add(ParseAddSubtract());

                        // Is there another argument?
                        if (fCurrentToken.Equals(TokenType.Symbol, ","))
                        {
                            ReadNextToken();
                            continue;
                        }

                        // Get out
                        break;
                    }
                    // Check and skip ')'
                    if (!fCurrentToken.Equals(TokenType.Symbol, ")"))
                    {
                        throw new ParserException("Missing Closing Parenthesis");
                    }

                    ReadNextToken();

                    // Create the function call node
                    return(new NodeFunctionCall(name, arguments.ToArray()));
                }
            }
            // Don't Understand
            throw new ParserException("Expected ; and end of line but instead got: " + fCurrentToken.Value);
        }
Ejemplo n.º 14
0
        public string GetSourceName(D3D9Instruction instruction, int srcIndex)
        {
            string sourceRegisterName;

            var registerType = instruction.GetParamRegisterType(srcIndex);

            switch (registerType)
            {
            case RegisterType.Const:
            case RegisterType.Const2:
            case RegisterType.Const3:
            case RegisterType.Const4:
            case RegisterType.ConstBool:
            case RegisterType.ConstInt:
                sourceRegisterName = GetSourceConstantName(instruction, srcIndex);
                if (sourceRegisterName != null)
                {
                    return(sourceRegisterName);
                }

                ParameterType parameterType;
                switch (registerType)
                {
                case RegisterType.Const:
                case RegisterType.Const2:
                case RegisterType.Const3:
                case RegisterType.Const4:
                    parameterType = ParameterType.Float;
                    break;

                case RegisterType.ConstBool:
                    parameterType = ParameterType.Bool;
                    break;

                case RegisterType.ConstInt:
                    parameterType = ParameterType.Int;
                    break;

                default:
                    throw new NotImplementedException();
                }
                int registerNumber       = instruction.GetParamRegisterNumber(srcIndex);
                ConstantDeclaration decl = FindConstant(parameterType, registerNumber);
                if (decl == null)
                {
                    // Constant register not found in def statements nor the constant table
                    throw new NotImplementedException();
                }

                if ((decl.ParameterClass == ParameterClass.MatrixRows && ColumnMajorOrder) ||
                    (decl.ParameterClass == ParameterClass.MatrixColumns && !ColumnMajorOrder))
                {
                    int row = registerNumber - decl.RegisterIndex;
                    sourceRegisterName = $"{decl.Name}[{row}]";
                }
                else if ((decl.ParameterClass == ParameterClass.MatrixColumns && ColumnMajorOrder) ||
                         (decl.ParameterClass == ParameterClass.MatrixRows && !ColumnMajorOrder))
                {
                    int column = registerNumber - decl.RegisterIndex;
                    sourceRegisterName = $"transpose({decl.Name})[{column}]";
                }
                else
                {
                    sourceRegisterName = decl.Name;
                }
                break;

            default:
                RegisterKey registerKey = instruction.GetParamRegisterKey(srcIndex);
                sourceRegisterName = GetRegisterName(registerKey);
                break;
            }

            sourceRegisterName = sourceRegisterName ?? instruction.GetParamRegisterName(srcIndex);

            sourceRegisterName += GetRelativeAddressingName(instruction, srcIndex);
            sourceRegisterName += instruction.GetSourceSwizzleName(srcIndex);
            return(ApplyModifier(instruction.GetSourceModifier(srcIndex), sourceRegisterName));
        }
        // Vector by matrix multiplication has a pattern of:
        // float2(dot(m_row1, v), dot(m_row2, v))
        // float3(dot(m_row1, v), dot(m_row2, v), dot(m_row3, v))
        // float4(dot(m_row1, v), dot(m_row2, v), dot(m_row3, v), dot(m_row4, v))
        public MatrixMultiplicationContext TryGetMultiplicationGroup(IList <HlslTreeNode> components)
        {
            const bool allowMatrix = true;

            if (!(components[0] is DotProductOperation firstDot))
            {
                return(null);
            }

            int dimension = firstDot.X.Length;

            if (components.Count < dimension)
            {
                return(null);
            }

            GroupNode firstMatrixRow = TryGetMatrixRow(firstDot, firstDot, 0);

            if (firstMatrixRow == null)
            {
                return(null);
            }

            GroupNode vector = firstDot.X == firstMatrixRow
                    ? firstDot.Y
                    : firstDot.X;

            var matrixRows = new List <GroupNode>();

            matrixRows.Add(firstMatrixRow);
            for (int i = 1; i < components.Count; i++)
            {
                if (!(components[i] is DotProductOperation nextDot))
                {
                    break;
                }

                GroupNode matrixRow = TryGetMatrixRow(nextDot, firstDot, i);
                if (matrixRow == null)
                {
                    break;
                }

                GroupNode nextVector = nextDot.X == matrixRow
                    ? nextDot.Y
                    : nextDot.X;
                if (!NodeGrouper.AreNodesEquivalent(vector, nextVector))
                {
                    break;
                }

                matrixRows.Add(matrixRow);
            }

            if (matrixRows.Count < 2)
            {
                return(null);
            }

            ConstantDeclaration matrix = TryGetMatrixDeclaration(matrixRows);

            if (matrix == null)
            {
                return(null);
            }

            bool matrixByVector = firstMatrixRow.Inputs
                                  .Cast <RegisterInputNode>()
                                  .All(row => row.ComponentIndex == 0);

            vector = SwizzleVector(vector, firstMatrixRow, matrixByVector);

            return(new MatrixMultiplicationContext(vector, matrix, matrixByVector, matrixRows.Count));
        }
Ejemplo n.º 16
0
 public Constant VisitConstantDeclaration(ConstantDeclaration cd)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 17
0
        public string GetRegisterName(RegisterKey registerKey)
        {
            var decl = _registerDeclarations[registerKey];

            switch (registerKey.Type)
            {
            case RegisterType.Texture:
                return(decl.Name);

            case RegisterType.Input:
                return((MethodInputRegisters.Count == 1) ? decl.Name : ("i." + decl.Name));

            case RegisterType.Output:
                return((MethodOutputRegisters.Count == 1) ? "o" : ("o." + decl.Name));

            case RegisterType.Const:
                var constDecl = FindConstant(ParameterType.Float, registerKey.Number);
                if (ColumnMajorOrder)
                {
                    if (constDecl.Rows == 1)
                    {
                        return(constDecl.Name);
                    }
                    string col = (registerKey.Number - constDecl.RegisterIndex).ToString();
                    return($"transpose({constDecl.Name})[{col}]");
                }
                if (constDecl.Rows == 1)
                {
                    return(constDecl.Name);
                }
                string row = (registerKey.Number - constDecl.RegisterIndex).ToString();
                return(constDecl.Name + $"[{row}]");

            case RegisterType.Sampler:
                ConstantDeclaration samplerDecl = FindConstant(RegisterSet.Sampler, registerKey.Number);
                if (samplerDecl != null)
                {
                    return(samplerDecl.Name);
                }
                else
                {
                    throw new NotImplementedException();
                }

            case RegisterType.MiscType:
                switch (registerKey.Number)
                {
                case 0:
                    return("vFace");

                case 1:
                    return("vPos");

                default:
                    throw new NotImplementedException();
                }

            default:
                throw new NotImplementedException();
            }
        }
Ejemplo n.º 18
0
        public string GetSourceName(Instruction instruction, int srcIndex)
        {
            string sourceRegisterName;

            var registerType = instruction.GetParamRegisterType(srcIndex);

            switch (registerType)
            {
            case RegisterType.Const:
            case RegisterType.Const2:
            case RegisterType.Const3:
            case RegisterType.Const4:
            case RegisterType.ConstBool:
            case RegisterType.ConstInt:
                sourceRegisterName = GetSourceConstantName(instruction, srcIndex);
                if (sourceRegisterName != null)
                {
                    return(sourceRegisterName);
                }

                ParameterType parameterType;
                switch (registerType)
                {
                case RegisterType.Const:
                case RegisterType.Const2:
                case RegisterType.Const3:
                case RegisterType.Const4:
                    parameterType = ParameterType.Float;
                    break;

                case RegisterType.ConstBool:
                    parameterType = ParameterType.Bool;
                    break;

                case RegisterType.ConstInt:
                    parameterType = ParameterType.Int;
                    break;

                default:
                    throw new NotImplementedException();
                }
                int registerNumber       = instruction.GetParamRegisterNumber(srcIndex);
                ConstantDeclaration decl = FindConstant(parameterType, registerNumber);
                if (decl == null)
                {
                    // Constant register not found in def statements nor the constant table
                    throw new NotImplementedException();
                }

                if (decl.ParameterClass == ParameterClass.MatrixRows)
                {
                    sourceRegisterName = string.Format("{0}[{1}]", decl.Name, registerNumber - decl.RegisterIndex);
                }
                else
                {
                    sourceRegisterName = decl.Name;
                }
                break;

            default:
                RegisterKey registerKey = instruction.GetParamRegisterKey(srcIndex);
                sourceRegisterName = GetRegisterName(registerKey);
                break;
            }

            sourceRegisterName = sourceRegisterName ?? instruction.GetParamRegisterName(srcIndex);

            sourceRegisterName += instruction.GetSourceSwizzleName(srcIndex);
            return(ApplyModifier(instruction.GetSourceModifier(srcIndex), sourceRegisterName));
        }
Ejemplo n.º 19
0
 public SerializedType VisitConstantDeclaration(ConstantDeclaration cd)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 20
0
        private Declaration[] CreateStandardEnvironment(bool insert = false)
        {
            List <Declaration> result = new List <Declaration>();

            // signal that the following symbols are part of the standard library
            Position    position = new Position("(library)", 0, 0);
            Declaration declaration;
            Expression  expression;

            // enter the predefined constant 'maxint' into the symbol table
            expression  = new IntegerExpression(position, int.MaxValue);
            declaration = new ConstantDeclaration(position, "maxint", new IntegerType(position), expression);
            result.Add(declaration);

            // enter the predefined constants 'false' and 'true' into the symbol table
            expression  = new BooleanExpression(position, false);
            declaration = new ConstantDeclaration(position, "false", new BooleanType(position), expression);
            result.Add(declaration);

            expression  = new BooleanExpression(position, true);
            declaration = new ConstantDeclaration(position, "true", new BooleanType(position), expression);
            result.Add(declaration);

            // enter the predefined operators into the symbol table
            // ... the \ operator
            declaration = new FunctionDeclaration(
                position,
                "\\",
                new BooleanType(position),
                new ParameterDeclaration[] { new ParameterDeclaration(position, "value", new BooleanType(position)) },
                null        // note: the code generator must handle these predefined functions so no body is defined
                );
            result.Add(declaration);

            // ... all Triangle operators of the form Boolean x Boolean -> Boolean
            string[] boolean_and_boolean_to_boolean_operators = { "/\\", "\\/", "=", "\\=" };
            foreach (string @operator in boolean_and_boolean_to_boolean_operators)
            {
                declaration = new FunctionDeclaration(
                    position,
                    @operator,
                    new BooleanType(position),
                    new ParameterDeclaration[]
                {
                    new ParameterDeclaration(position, "first", new BooleanType(position)),
                    new ParameterDeclaration(position, "other", new BooleanType(position))
                },
                    null    // note: the code generator must handle these predefined functions so no body is defined
                    );
                result.Add(declaration);
            }

            // ... all Triangle operators of the form Integer x Integer -> Integer
            string[] integer_and_integer_to_integer_operators = { "+", "-", "*", "/", "//" };
            foreach (string @operator in integer_and_integer_to_integer_operators)
            {
                declaration = new FunctionDeclaration(
                    position,
                    @operator,
                    new IntegerType(position),
                    new ParameterDeclaration[]
                {
                    new ParameterDeclaration(position, "first", new IntegerType(position)),
                    new ParameterDeclaration(position, "other", new IntegerType(position))
                },
                    null    // note: the code generator must handle these predefined functions so no body is defined
                    );
                result.Add(declaration);
            }

            // ... all Triangle operators of the form Integer x Integer -> Boolean
            string[] integer_and_integer_to_boolean_operators = { "<", "<=", ">", ">=", "=", "\\=" };
            foreach (string @operator in integer_and_integer_to_boolean_operators)
            {
                declaration = new FunctionDeclaration(
                    position,
                    @operator,
                    new BooleanType(position),
                    new ParameterDeclaration[]
                {
                    new ParameterDeclaration(position, "first", new IntegerType(position)),
                    new ParameterDeclaration(position, "other", new IntegerType(position))
                },
                    null    // note: the code generator must handle these predefined functions so no body is defined
                    );
                result.Add(declaration);
            }

            // enter the predefined functions (getint and putint) into the symbol table
            declaration = new FunctionDeclaration(
                position,
                "getint",
                new IntegerType(position),
#if false
                new ParameterDeclaration[] { new ParameterDeclaration(position, "value", new IntegerType(position)) },
#else
                new ParameterDeclaration[0],
#endif
                null        // note: the code generator must handle these predefined functions so no body is defined
                );
            result.Add(declaration);

            declaration = new FunctionDeclaration(
                position,
                "putint",
                new IntegerType(position),
                new ParameterDeclaration[] { new ParameterDeclaration(position, "value", new IntegerType(position)) },
                null        // note: the code generator must handle these predefined functions so no body is defined
                );
            result.Add(declaration);

            return(result.ToArray());
        }