Ejemplo n.º 1
0
        private void TraverseNodes(Reduction root)
        {
            while (true)
            {
                var globalStatement = (Reduction)root[0].Data;
                var declaration     = (Reduction)globalStatement[0].Data;

                switch (declaration.Parent.Head().Name())
                {
                case "StructureDeclaration":
                    this.TraverseStructureDeclaration(declaration);
                    break;

                case "FunctionDeclaration":
                    this.TraverseFunctionDeclaration(declaration);
                    break;
                }

                if (root.Count() == 1)
                {
                    return;
                }

                root = (Reduction)root[1].Data;
            }
        }
Ejemplo n.º 2
0
        public void ReadXml(XmlReader reader)
        {
            reader.ReadStartElement();
            while (reader.NodeType != XmlNodeType.EndElement)
            {
                EnumPair <Damage.DmgType, int> temp = new EnumPair <Damage.DmgType, int>();
                Debug.WriteLine(reader.Name);
                temp.Type  = (Damage.DmgType)Enum.Parse(typeof(Damage.DmgType), reader.GetAttribute("Type"));
                temp.Value = Int32.Parse(reader.GetAttribute("Value"));
                switch (reader.Name)
                {
                case "Resitance":
                {
                    Resistance.Add(temp);
                    break;
                }

                case "Reduction":
                {
                    Reduction.Add(temp);
                    break;
                }

                default:
                {
                    break;
                }
                }
                reader.Read();
            }
            reader.ReadEndElement();
        }
Ejemplo n.º 3
0
            /// <summary>
            /// Computes the mean squared error between two tensors.
            /// </summary>
            /// <param name="labels">The ground truth output tensor, same dimensions as
            /// 'predictions'.</param>
            /// <param name="predictions"> The predicted outputs.</param>
            /// <param name="weights">Tensor whose rank is either 0, or the same rank as
            /// `labels`, and must be broadcastable to `labels` (i.e., all dimensions
            /// must be either `1`, or the same as the corresponding `losses`
            /// dimension).</param>
            /// <param name="reduction">Type of reduction to apply to loss. Should be of type
            /// `Reduction`</param>
            /// <returns></returns>
            public static Tensor meanSquaredError(Tensor labels, Tensor predictions,
                                                  Tensor weights = null, Reduction reduction = Reduction.SUM_BY_NONZERO_WEIGHTS)
            {
                var losses = labels.squaredDifference(predictions);

                return(computeWeightedLoss(losses, weights, reduction));
            }
Ejemplo n.º 4
0
            /// <summary>
            ///  Computes the absolute difference loss between two tensors.
            /// </summary>
            /// <param name="labels">The ground truth output tensor, same dimensions as
            ///'predictions'.</param>
            /// <param name="predictions"> The predicted outputs.</param>
            /// <param name="weights">Tensor whose rank is either 0, or the same rank as
            ///   `labels`, and must be broadcastable to `labels` (i.e., all dimensions
            ///   must be either `1`, or the same as the corresponding `losses`
            ///   dimension).</param>
            /// <param name="reduction">Type of reduction to apply to loss. Should be of type
            /// `Reduction`</param>
            /// <returns></returns>
            public static Tensor absoluteDifference(Tensor labels, Tensor predictions,
                                                    Tensor weights = null, Reduction reduction = Reduction.SUM_BY_NONZERO_WEIGHTS)
            {
                var losses = labels.sub(predictions).abs();

                return(computeWeightedLoss(losses, weights, reduction));
            }
Ejemplo n.º 5
0
        private LogicStatement ParseStatement(Reduction statement)
        {
            if (statement.Parent.Head().Name() == "TerminatedStatement")
            {
                statement = (Reduction)statement[0].Data;
            }

            if (statement.Parent.Head().Name() == "Statement")
            {
                statement = (Reduction)statement[0].Data;
            }

            switch (statement.Parent.Head().Name())
            {
            case "WhileStatement":
                return(this.ParseWhileStatement(statement));

            case "IfStatement":
                return(this.ParseIfStatement(statement));

            case "AssignStatement":
                return(this.ParseAssignStatement(statement));

            case "ReturnStatement":
                return(this.ParseReturnStatement(statement));

            case "BlockStatement":
                return(this.ParseBlockStatement(statement));
            }

            throw new InvalidOperationException();
        }
        public async Task <IActionResult> PutReduction(int id, Reduction reduction)
        {
            if (id != reduction.Id)
            {
                return(BadRequest());
            }

            _context.Entry(reduction).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ReductionExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Ejemplo n.º 7
0
        private CommonProperties GetProperties(Reduction r)
        {
            CommonProperties prop = new CommonProperties();

            Stack <Reduction> listred = new Stack <Reduction>();

            listred.Push(r);

            while (listred.Count > 0)
            {
                Reduction red = listred.Pop();

                for (int i = 0; i < red.Count(); i++)
                {
                    if (red[i].Parent.TableIndex() == (short)SymbolIndex.Property)
                    {
                        prop += (CommonProperties)red[i].Data;
                    }
                    else
                    {
                        listred.Push((Reduction)red[i].Data);
                    }
                }
            }

            return(prop);
        }
Ejemplo n.º 8
0
        public Reduction CreateRULE_QUERY_SELECT_WHERE2(Reduction reduction)
        {
            //selectType can be one of the following depending on the query text: -
            // AggregateFunctionPredicate that has IsOfTypePredicate set as its ChildPredicate

            object selectType = ((Reduction)reduction.GetToken(1).Data).Tag;

            Predicate lhs = null;
            Predicate rhs = (Predicate)((Reduction)reduction.GetToken(3).Data).Tag;
            Predicate selectTypePredicate = selectType as Predicate;
            Predicate result = null;

            AggregateFunctionPredicate parentPredicate = selectTypePredicate as AggregateFunctionPredicate;

            lhs = parentPredicate.ChildPredicate;
            parentPredicate.ChildPredicate = ExpressionBuilder.CreateLogicalAndPredicate(lhs, rhs);
            result = parentPredicate;

            reduction.Tag = result;
            if (NCacheLog.IsInfoEnabled)
            {
                NCacheLog.Info("CreateRULE_QUERY_SELECT_WHERE2");
            }
            return(null);
        }
Ejemplo n.º 9
0
        private static List <PercentChanceSyntax> ReadPercentStatements(Reduction reduction)
        {
            var ret = new List <PercentChanceSyntax>();

            AddPercentStatement(reduction);
            return(ret);

            void AddPercentStatement(Reduction red)
            {
                switch ((ProductionIndex)red.Parent.TableIndex())
                {
                case ProductionIndex.PercentStatement1:
                    ret.Add((PercentChanceSyntax)ReadNode(reduction));
                    break;

                case ProductionIndex.PercentStatement2:
                    var red0 = (Reduction)red[0].Data;
                    switch ((ProductionIndex)red0.Parent.TableIndex())
                    {
                    case ProductionIndex.PercentStatement2:
                        AddPercentStatement(red0);
                        break;

                    default:
                        ret.Add((PercentChanceSyntax)ReadNode(red0));
                        break;
                    }
                    break;
                }
            }
        }
Ejemplo n.º 10
0
            /// <summary>
            /// Computes the weighted loss between two tensors.
            /// </summary>
            /// <param name="losses">Tensor of shape `[batch_size, d1, ... dN]`.</param>
            /// <param name="weights"> Tensor whose rank is either 0, or the same rank as
            ///  `losses`, and must be broadcastable to `losses` (i.e., all
            ///  dimensions must be either `1`, or the same as the corresponding
            ///  `losses` dimension).</param>
            /// <param name="reduction">Type of reduction to apply to loss. Should be of type
            /// `Reduction`</param>
            /// <returns></returns>
            public static Tensor computeWeightedLoss(Tensor losses, Tensor weights = null,
                                                     Reduction reduction           = Reduction.SUM_BY_NONZERO_WEIGHTS)
            {
                var weightedLoss = (weights == null) ? losses : losses.mul(weights);

                if (reduction == Reduction.SUM)
                {
                    return(weightedLoss.sum());
                }
                else
                if (reduction == Reduction.MEAN)
                {
                    return((weights == null) ? weightedLoss.mean() :
                           weightedLoss.sum().div(weights.sum()));
                }
                else

                if (reduction == Reduction.SUM_BY_NONZERO_WEIGHTS)
                {
                    if (weights == null)
                    {
                        return(weightedLoss.sum().div(Ops.scalar(losses.Size)));
                    }
                    else
                    {
                        var numNonZeros = weights.notEqual(Ops.scalar(0)).sum();
                        return(weightedLoss.sum().div(numNonZeros));
                    }
                }
                else         //Reduction.NONE
                {
                    return(weightedLoss);
                }
            }
Ejemplo n.º 11
0
        public object Execute(Reduction node)
        {
            List <string> container      = null;
            string        whereClosure   = null;
            string        orderByClosure = null;


            for (int i = 2; i < node.Count(); i++)
            {
                string type             = Regex.Replace(node[i].Parent.ToString(), "[^0-9a-zA-Z]+", "");
                Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type);

                if (container == null)
                {
                    // egyelőre használaton kívül van, valamint ezt lehet, hogy projekt specifikusan át kell írni nyelvtan szinten is
                    container = (List <string>)Context.NonTerminalContext.Execute(ntt, (Reduction)node[i].Data);
                }
                else if (whereClosure == null)
                {
                    whereClosure = Context.NonTerminalContext.Execute(ntt, (Reduction)node[i].Data).ToString();
                }
                else if (orderByClosure == null)
                {
                    orderByClosure = Context.NonTerminalContext.Execute(ntt, (Reduction)node[i].Data).ToString();
                }
            }

            var retVal = Operation(whereClosure, orderByClosure, null);

            string DEBUG = "DEBUG";

            return(DEBUG);
        }
Ejemplo n.º 12
0
        private static List <ElseIfSyntax> ReadElseIfs(Reduction reduction)
        {
            var ret = new List <ElseIfSyntax>();

            AddElseIf(reduction);
            return(ret);

            void AddElseIf(Reduction red)
            {
                switch ((ProductionIndex)reduction.Parent.TableIndex())
                {
                case ProductionIndex.ElseIfClause0:
                    break;

                case ProductionIndex.ElseIfClause1:
                    ret.Add(new ElseIfSyntax(ReadStatements((Reduction)red[1].Data)));
                    break;

                case ProductionIndex.ElseIfClause2:
                    AddElseIf((Reduction)red[0].Data);
                    AddElseIf((Reduction)red[1].Data);
                    break;
                }
            }
        }
        public async Task <ActionResult <Reduction> > PostReduction(Reduction reduction)
        {
            _context.Reduction.Add(reduction);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetReduction", new { id = reduction.Id }, reduction));
        }
Ejemplo n.º 14
0
        private LogicExpression ParseValueExpression(Reduction expression)
        {
            if (expression.Count() == 1)
            {
                switch (expression[0].Parent.Name())
                {
                case "Id":
                    return(new IdentifierLogicExpression(
                               (string)expression[0].Data));

                case "StringLiteral":
                    return(new ConstantLogicExpression(
                               this.ParseString((string)expression[0].Data)));

                case "NumberLiteral":
                    return(new ConstantLogicExpression(
                               float.Parse((string)expression[0].Data)));
                }
            }

            if (expression.Count() == 3)
            {
                return(this.ParseExpression((Reduction)expression[1].Data));
            }

            if (expression.Count() == 4)
            {
                return(new FunctionCallLogicExpression(
                           (string)((Reduction)expression[0].Data)[0].Data,
                           this.ParseArguments((Reduction)expression[2].Data)));
            }

            throw new InvalidOperationException();
        }
Ejemplo n.º 15
0
        public object Execute(Reduction node)
        {
            string        DEBUG    = "DEBUG - Container";
            List <string> _operand = null;

            // lehet List, Set vagy ID
            switch (node[0].Type())
            {
            case SymbolType.Nonterminal:     // Nemterminálisok vizsgálata

                string type             = Regex.Replace(node[0].Parent.ToString(), "[^0-9a-zA-Z]+", "");
                Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type);

                _operand = (List <string>)Context.NonTerminalContext.Execute(ntt, (Reduction)node[0].Data);

                return(_operand);

            case SymbolType.Error:
                Console.WriteLine("ERROR in Logical_Engine.Classes.Processor.ProcessTree");
                break;

            default:
                // Terminálisok vizsgálata - itt egy ID
                List <string> retVal = new List <string>();
                retVal.Add(node[0].Data as string);
                return(retVal);
            }

            return(DEBUG);
        }
Ejemplo n.º 16
0
        private List <LogicParameter> ParseParameters(Reduction parameterDeclarations)
        {
            var parameters = new List <LogicParameter>();

            if (parameterDeclarations.Count() == 0)
            {
                return(parameters);
            }

            while (true)
            {
                var parameter = (Reduction)parameterDeclarations[0].Data;

                var type             = (string)((Reduction)parameter[0].Data)[0].Data;
                var name             = (string)parameter[1].Data;
                var optionalSemantic = this.ParseOptionalSemantic((Reduction)parameter[2].Data);

                parameters.Add(new LogicParameter
                {
                    Index    = parameters.Count,
                    Type     = type,
                    Name     = name,
                    Semantic = optionalSemantic
                });

                if (parameterDeclarations.Count() == 1)
                {
                    return(parameters);
                }

                parameterDeclarations = (Reduction)parameterDeclarations[2].Data;
            }
        }
Ejemplo n.º 17
0
 private LogicStatement ParseAssignStatement(Reduction statement)
 {
     return(new AssignLogicStatement(
                this.ParseAssignTarget((Reduction)statement[0].Data),
                (string)statement[1].Data,
                this.ParseExpression((Reduction)statement[2].Data)));
 }
Ejemplo n.º 18
0
        public object Execute(Reduction node)
        {
            string DEBUG = "DEBUG";

            if (node.Count() == 3)
            {
                // van operátor és két operandus, először a két nem terminálist bontom, majd a terminálisként adott operátorral
                // elvégzem a megfelelő műveletet és értéket adok/másolom

                if (node[1].Data.ToString().Contains("\""))
                {
                    string returnValue = Regex.Replace(node[1].Data.ToString(), "\"", "");
                    return(returnValue);
                }
                else
                {
                    int tmp;
                    if (int.TryParse(node[1].Data.ToString(), out tmp))
                    {
                        return(tmp);
                    }
                    return(node[1].Data.ToString());
                }
            }

            return(DEBUG);
        }
Ejemplo n.º 19
0
        public object Execute(Reduction node)
        {
            if (node.Count() == 2)
            {
                // ID [szóköz] Indexer
                string _operator = null;
                object _operand  = null;

                for (int i = 0; i < node.Count(); i++)
                {
                    switch (node[i].Type())
                    {
                    case SymbolType.Nonterminal:     // Nemterminálisok vizsgálata

                        string type             = Regex.Replace(node[i].Parent.ToString(), "[^0-9a-zA-Z]+", "");
                        Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type);

                        _operand = Context.NonTerminalContext.Execute(ntt, (Reduction)node[i].Data);
                        break;

                    case SymbolType.Error:
                        Console.WriteLine("ERROR in Logical_Engine.Classes.Processor.ProcessTree");
                        break;

                    default:
                        // Terminálisok vizsgálata - itt maga az ID
                        _operator = node[i].Data as string;
                        break;
                    }
                }

                string _path = _operator + ":" + _operand.ToString();

                if (_operator != null)
                {
                    _operand = Operation(_operand, _operator, null);
                }
                Console.WriteLine("Element value: " + _operand + "\ttype: " + _operand.GetType());
                return(_path);
            }
            else
            {
                // egy nem terminális van, azt kell lebontani, majd
                // értékadás/másolás
                try
                {
                    return(node[0].Data.ToString());
                }
                catch (InvalidCastException ice)
                {
                    Console.WriteLine(ice.Message);
                }
                catch (Exception exc)
                {
                    Console.WriteLine(exc.Message);
                }
            }
            return(null);
        }
Ejemplo n.º 20
0
	public static Reduction operator + (Reduction x, Reduction y)
	{
		Reduction result = new Reduction();
		result.flat = x.flat + y.flat;
		result.percent = 1f - (x.PercentMultiplier * y.PercentMultiplier);
		result.isFlatFirst = x.isFlatFirst && y.isFlatFirst;
		return result;
	}
Ejemplo n.º 21
0
 public static Loss MSE(Reduction reduction = Reduction.Mean)
 {
     return((TorchTensor src, TorchTensor target) => {
         var res = THSNN_mse_loss(src.Handle, target.Handle, (long)reduction);
         Torch.CheckForErrors();
         return new TorchTensor(res);
     });
 }
Ejemplo n.º 22
0
        public object Execute(Reduction node)
        {
            string returnValue = node[1].Data.ToString();

            returnValue = Regex.Replace(returnValue, "\"", "");
            Console.WriteLine(returnValue);
            return(returnValue);
        }
Ejemplo n.º 23
0
 internal static string GetRuleSymbolName(Reduction ruleDeclaration)
 {
     if (ruleDeclaration == null)
     {
         throw new ArgumentNullException("ruleDeclaration");
     }
     return(ruleDeclaration.Children[0].ToString());
 }
Ejemplo n.º 24
0
 public static Loss NLL(TorchTensor?weigths = null, Reduction reduction = Reduction.Mean)
 {
     return((TorchTensor src, TorchTensor target) => {
         var res = THSNN_nll_loss(src.Handle, target.Handle, weigths?.Handle ?? IntPtr.Zero, (long)reduction);
         Torch.CheckForErrors();
         return new TorchTensor(res);
     });
 }
Ejemplo n.º 25
0
            /// <summary>
            /// Computes the cosine distance loss between two tensors.
            /// </summary>
            /// <param name="labels">The ground truth output tensor, same dimensions as
            /// 'predictions'.</param>
            /// <param name="predictions"> The predicted outputs.</param>
            /// <param name="axis">The dimension along which the cosine distance is computed.</param>
            /// <param name="weights"> Tensor whose rank is either 0, or the same rank as
            /// `labels`, and must be broadcastable to `labels` (i.e., all dimensions
            /// must be either `1`, or the same as the corresponding `losses`
            /// dimension).</param>
            /// <param name="reduction">Type of reduction to apply to loss. Should be of type
            /// `Reduction`</param>
            /// <returns></returns>
            public static Tensor cosineDistance(Tensor labels, Tensor predictions, int axis,
                                                Tensor weights = null, Reduction reduction = Reduction.SUM_BY_NONZERO_WEIGHTS)
            {
                var one    = Ops.scalar(1);
                var losses = one.sub(labels.mul(predictions).sum(new int[] { axis }, true));

                return(computeWeightedLoss(losses, weights, reduction));
            }
Ejemplo n.º 26
0
        private LogicStatement ParseBlockStatement(Reduction statement)
        {
            if (statement.Count() != 3)
            {
                return(new BlockLogicStatement(new List <LogicStatement>()));
            }

            return(new BlockLogicStatement(this.ParseStatements((Reduction)statement[1].Data)));
        }
Ejemplo n.º 27
0
 private int ComputeHashCode()
 {
     return(HashCode.Compute(
                DottedRule.GetHashCode(),
                Origin.GetHashCode(),
                Recognized.GetHashCode(),
                Reduction.GetHashCode(),
                Index.GetHashCode()));
 }
Ejemplo n.º 28
0
 /// Implements <Property> ::= <Identifier>
 public Reduction CreateRULE_PROPERTY(Reduction reduction)
 {
     if (NCacheLog.IsInfoEnabled)
     {
         NCacheLog.Info("CreateRULE_PROPERTY");
     }
     reduction.Tag = ((Token)reduction.GetToken(0)).Data;
     return(null);
 }
Ejemplo n.º 29
0
 /// Implements <Identifier> ::= Keyword
 public Reduction CreateRULE_IDENTIFIER_KEYWORD(Reduction reduction)
 {
     reduction.Tag = ((Token)reduction.GetToken(0)).Data;
     if (NCacheLog.IsInfoEnabled)
     {
         NCacheLog.Info("RULE_IDENTIFIER_KEYWORD -> " + reduction.Tag);
     }
     return(null);
 }
Ejemplo n.º 30
0
 public Reduction CreateRULE_DELETEPARAMS_DOLLARTEXTDOLLAR(Reduction reduction)
 {
     reduction.Tag = "System.String";
     if (NCacheLog.IsInfoEnabled)
     {
         NCacheLog.Info("CreateRULE_OBJECTTYPE_DOLLARTEXTDOLLAR");
     }
     return(null);
 }
Ejemplo n.º 31
0
 //self create
 //=========================
 public Reduction CreateRULE_ATRRIB(Reduction reduction)
 {
     if (NCacheLog.IsInfoEnabled)
     {
         NCacheLog.Info("CreateRULE_ATRRIB");
     }
     reduction.Tag = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
     return(null);
 }
Ejemplo n.º 32
0
	internal Reduction GetPenetration(EDamageType a_type)
	{
		Reduction result;
		
		switch(a_type)
		{
			case EDamageType.Slashing :
			case EDamageType.Crushing :
			case EDamageType.Piercing : 
				result = PhysicalPenetration;
			break;
			
			default : result = new Reduction();
			break;
		}
		
		return result;
	}
Ejemplo n.º 33
0
	internal Reduction GetResistance(EDamageType type, Reduction a_arpen)
	{
		Resistance reduc;
		
		switch(type)
		{
		case EDamageType.Slashing :
			reduc = general + slashing;
			break;
			
		case EDamageType.Crushing :
			reduc = general + crushing;
			break;
			
		case EDamageType.Piercing :
			reduc = general + piercing;
			break;
			
		case EDamageType.Magic :
			reduc = general + magic;
			break;
			
		case EDamageType.True :
			reduc = new Resistance();
			break;
			
		default: 
			reduc = new Resistance();
			break;
		}
		
		Reduction result = new Reduction();
		result.percent = ComputePercentReduction(reduc.armor, a_arpen);
		result.flat = ComputeFlatReduction(reduc.flat, a_arpen);
		return result;
	}
Ejemplo n.º 34
0
	internal float ComputePercentReduction(int armor, Reduction a_arpen)
	{
		int effectiveArmor = a_arpen.Compute(armor);
		float reduction = 1f + (- 1f / Mathf.Exp(effectiveArmor/50f));
		return reduction;
	}
Ejemplo n.º 35
0
	internal float ComputeFlatReduction(int flat, Reduction a_arpen)
	{
		return flat;
	}
Ejemplo n.º 36
0
	public bool Parse(TextReader reader)
	{
		//This procedure starts the GOLD Parser Engine and handles each of the
		//messages it returns. Each time a reduction is made, you can create new
		//custom object and reassign the .CurrentReduction property. Otherwise,
		//the system will use the Reduction object that was returned.
		//
		//The resulting tree will be a pure representation of the language
		//and will be ready to implement.

		Errors = new List<ParserError>();

		ArgsCount = new List<int>();
		Nodes = new Stack<MathFuncNode>();
		ArgsFuncTypes = new List<KnownFuncType?>();
		Parameters = new Dictionary<string, ConstNode>();
		Funcs = new Stack<MathFunc>();

		Statements = new List<MathFunc>();

		bool done;//Controls when we leave the loop
		bool accepted = false;          //Was the parse successful?

		parser.Open(reader);
		parser.TrimReductions = false;  //Please read about this feature before enabling

		done = false;
		while (!done)
		{
			var response = parser.Parse();

			switch (response)
			{
				case ParseMessage.LexicalError:
					//Cannot recognize token
					Errors.Add(new ParserError(parser.CurrentToken().Position(), string.Format("Lexical Error. Token {1} was not expected.", parser.CurrentToken().Data)));
					done = true;
					break;

				case ParseMessage.SyntaxError:
					//Expecting a different token
					Errors.Add(new ParserError(parser.CurrentPosition(), string.Format("Syntax Error. Expecting: {0}.", parser.ExpectedSymbols().Text())));
					done = true;
					break;

				case ParseMessage.Reduction:
					//Create a customized object to store the reduction
					CreateNewObject((Reduction)parser.CurrentReduction);
					break;

				case ParseMessage.Accept:
					//Accepted!
					Root = (Reduction)parser.CurrentReduction;
					done = true;
					accepted = true;
					break;

				case ParseMessage.TokenRead:
					//You don't have to do anything here.
					break;

				case ParseMessage.InternalError:
					//INTERNAL ERROR! Something is horribly wrong.
					Errors.Add(new ParserError("Internal Error. Something is horribly wrong."));
					done = true;
					break;

				case ParseMessage.NotLoadedError:
					//This error occurs if the CGT was not loaded.
					Errors.Add(new ParserError("Grammar Table is not loaded."));
					done = true;
					break;

				case ParseMessage.GroupError:
					//GROUP ERROR! Unexpected end of file
					Errors.Add(new ParserError(parser.CurrentPosition(), "GROUP ERROR! Unexpected end of file."));
					done = true;
					break;
			}
		} //while

		while (Funcs.Count != 0)
			Statements.Add(Funcs.Pop());

		return accepted;
	}
Ejemplo n.º 37
0
	private void CreateNewObject(Reduction r)
	{
		MathFuncNode arg1, arg2;

		var tableIndex = (ProductionIndex)r.Parent.TableIndex();
		switch (tableIndex)
		{
			case ProductionIndex.Statements:
				// <Statements> ::= <Statements> <Devider> <Statement>
				break;

			case ProductionIndex.Statements2:
				// <Statements> ::= <Statements> <Devider>
				break;

			case ProductionIndex.Statements3:
				// <Statements> ::= <Statement>
				//Funcs.Push(new MathFunc(Args.Pop()));
				break;

			case ProductionIndex.Devider_Semi:
				// <Devider> ::= ';'
				break;

			case ProductionIndex.Devider_Dot:
				// <Devider> ::= '.'
				break;

			case ProductionIndex.Statement_Eq:
				// <Statement> ::= <Expression> '=' <Expression>
				arg2 = Nodes.Pop();
				arg1 = Nodes.Pop();
				Funcs.Push(new MathFunc(arg1, arg2, null, Parameters.Select(p => p.Value)));
				Parameters.Clear();
				break;

			case ProductionIndex.Statement:
				// <Statement> ::= <Expression>
				Funcs.Push(new MathFunc(Nodes.Pop(), null, Parameters.Select(p => p.Value)));
				break;

			case ProductionIndex.Expression:
				// <Expression> ::= <FuncDef>
				break;

			case ProductionIndex.Funcdef_Id_Lparan_Rparan:
				// <FuncDef> ::= Id '(' <ExpressionList> ')'

				PushFunction(r[0].Data.ToString());
				break;

			case ProductionIndex.Funcdef_Id_Apost_Lparan_Rparan:
			// <FuncDef> ::= Id '' '(' <ExpressionList> ')'

			case ProductionIndex.Funcdef_Id_Lparan_Rparan_Apost:

				// <FuncDef> ::= Id '(' <ExpressionList> ')' ''

				PushFunction(r[0].Data.ToString());
				Nodes.Push(new FuncNode(KnownFuncType.Diff, new MathFuncNode[] { Nodes.Pop(), null }));

				break;

			case ProductionIndex.Expressionlist_Comma:
				ArgsCount[ArgsCount.Count - 1]++;
				break;

			case ProductionIndex.Expressionlist:
				ArgsCount.Add(1);
				ArgsFuncTypes.Add(null);
				break;

			case ProductionIndex.Expression2:

				// <Expression> ::= <Addition>
				if (AdditionMultiChilds)
					PushOrRemoveFunc(KnownFuncType.Add);

				break;

			case ProductionIndex.Addition_Addliteral:

				// <Addition> ::= <Addition> AddLiteral <Multiplication>
				if (MultiplicationMultiChilds)
					PushOrRemoveFunc(KnownFuncType.Mult);

				if (AdditionMultiChilds)
				{
					ArgsCount[ArgsCount.Count - 1]++;
					if (KnownFunc.BinaryNamesFuncs[r[1].Data.ToString()] == KnownFuncType.Sub)
						Nodes.Push(new FuncNode(KnownFuncType.Neg, new MathFuncNode[] { Nodes.Pop() }));
				}
				else
					PushBinaryFunction(r[1].Data.ToString());
				break;

			case ProductionIndex.Addition_Addliteral2:

				// <Addition> ::= <Addition> AddLiteral <FuncDef>

				if (AdditionMultiChilds)
				{
					ArgsCount[ArgsCount.Count - 1]++;
					if (KnownFunc.BinaryNamesFuncs[r[1].Data.ToString()] == KnownFuncType.Sub)
						Nodes.Push(new FuncNode(KnownFuncType.Neg, new MathFuncNode[] { Nodes.Pop() }));
				}
				else
					PushBinaryFunction(r[1].Data.ToString());
				break;

			case ProductionIndex.Addition_Addliteral3:

				// <Addition> ::= <FuncDef> AddLiteral <Multiplication>
				if (MultiplicationMultiChilds)
					PushOrRemoveFunc(KnownFuncType.Mult);

				if (AdditionMultiChilds)
				{
					PushFunc(KnownFuncType.Add, 2);
					if (KnownFunc.BinaryNamesFuncs[r[1].Data.ToString()] == KnownFuncType.Sub)

						Nodes.Push(new FuncNode(KnownFuncType.Neg, new MathFuncNode[] { Nodes.Pop() }));
				}
				else
					PushBinaryFunction(r[1].Data.ToString());
				break;

			case ProductionIndex.Addition_Addliteral4:

				// <Addition> ::= <FuncDef> AddLiteral <FuncDef>

				if (AdditionMultiChilds)
				{
					PushFunc(KnownFuncType.Add, 2);
					if (KnownFunc.BinaryNamesFuncs[r[1].Data.ToString()] == KnownFuncType.Sub)
						Nodes.Push(new FuncNode(KnownFuncType.Neg, new MathFuncNode[] { Nodes.Pop() }));
				}
				else
					PushBinaryFunction(r[1].Data.ToString());
				break;

			case ProductionIndex.Addition:

				// <Addition> ::= <Multiplication>

				if (MultiplicationMultiChilds)
					PushOrRemoveFunc(KnownFuncType.Mult);

				if (AdditionMultiChilds)
					PushFunc(KnownFuncType.Add);

				break;

			case ProductionIndex.Multiplication_Multliteral:

			// <Multiplication> ::= <Multiplication> MultLiteral <Exponentiation>
			case ProductionIndex.Multiplication_Multliteral2:
				// <Multiplication> ::= <Multiplication> MultLiteral <FuncDef>

				if (MultiplicationMultiChilds)
				{
					if (KnownFunc.BinaryNamesFuncs[r[1].Data.ToString()] == KnownFuncType.Div)
						Nodes.Push(new FuncNode(KnownFuncType.Exp, new MathFuncNode[] { Nodes.Pop(), new ValueNode(-1) }));
					ArgsCount[ArgsCount.Count - 1]++;
				}
				else
					PushBinaryFunction(r[1].Data.ToString());
				break;

			case ProductionIndex.Multiplication:

				// <Multiplication> ::= <Exponentiation>

				if (MultiplicationMultiChilds)
					PushFunc(KnownFuncType.Mult);
				break;

			case ProductionIndex.Multiplication_Multliteral3:
			// <Multiplication> ::= <FuncDef> MultLiteral <Exponentiation>
			case ProductionIndex.Multiplication_Multliteral4:
				// <Multiplication> ::= <FuncDef> MultLiteral <FuncDef>

				if (MultiplicationMultiChilds)
				{
					PushFunc(KnownFuncType.Mult, 2);

					if (KnownFunc.BinaryNamesFuncs[r[1].Data.ToString()] == KnownFuncType.Div)
						Nodes.Push(new FuncNode(KnownFuncType.Exp, new MathFuncNode[] { Nodes.Pop(), new ValueNode(-1) }));
				}
				else
					PushBinaryFunction(r[1].Data.ToString());
				break;

			case ProductionIndex.Exponentiation_Caret:
				// <Exponentiation> ::= <Exponentiation> '^' <Negation>
			case ProductionIndex.Exponentiation_Caret2:
				// <Exponentiation> ::= <Exponentiation> '^' <FuncDef>
			case ProductionIndex.Exponentiation_Caret3:
				// <Exponentiation> ::= <FuncDef> '^' <Negation>
			case ProductionIndex.Exponentiation_Caret4:
				// <Exponentiation> ::= <FuncDef> '^' <FuncDef>

				PushBinaryFunction(r[1].Data.ToString());
				break;

			case ProductionIndex.Exponentiation:
				// <Exponentiation> ::= <Negation>
				break;

			case ProductionIndex.Negation_Addliteral:
				// <Negation> ::= AddLiteral <Value>
			case ProductionIndex.Negation_Addliteral2:
				// <Negation> ::= AddLiteral <FuncDef>
				if (Nodes.Peek().Type == MathNodeType.Value)
				{
					if (r[0].Data.ToString() == "-")
						Nodes.Push(new ValueNode(-((ValueNode)Nodes.Pop()).Value));
				}
				else
					Nodes.Push(new FuncNode(r[0].Data.ToString(), new MathFuncNode[] { Nodes.Pop() }));
				break;

			case ProductionIndex.Negation:

				// <Negation> ::= <Value>
				break;

			case ProductionIndex.Value_Id:

				// <Value> ::= Id
				var id = r[0].Data.ToString();
				ConstNode idValue;
				if (Parameters.TryGetValue(id, out idValue))
					Nodes.Push(idValue);
				else
				{
					var newConst = new ConstNode(id);
					Nodes.Push(newConst);
					Parameters.Add(id, newConst);
				}
				break;

			case ProductionIndex.Value_Number1:
				// <Value> ::= 'Number1'
			case ProductionIndex.Value_Number2:
				// <Value> ::= 'Number2'

				try
				{
					var str = r[0].Data.ToString();
					var dotInd = str.IndexOf('.');
					string intPart = dotInd == 0 ? "0" : str.Substring(0, dotInd == -1 ? str.Length : dotInd);
					string fracPart = null;
					string periodPart = null;
					if (dotInd != -1)
					{
						int braceInd = str.IndexOf('(', dotInd + 1);
						if (braceInd == -1)
							fracPart = str.Substring(dotInd + 1, str.Length - dotInd - 1);
						else
						{
							fracPart = str.Substring(dotInd + 1, braceInd - dotInd - 1);
							periodPart = str.Substring(braceInd + 1, str.Length - braceInd - 2);
						}
					}
					var result = Rational<long>.FromDecimal(intPart, fracPart, periodPart);
					Nodes.Push(new ValueNode(result));
				}
				catch
				{
					throw new ArgumentException();
				}
				break;

			case ProductionIndex.Value_Lparan_Rparan:

				// <Value> ::= '(' <Expression> ')'
				break;

			case ProductionIndex.Value_Pipe_Pipe:

				// <Value> ::= '|' <Expression> '|'
				Nodes.Push(new FuncNode(KnownFuncType.Abs, new MathFuncNode[] { Nodes.Pop() }));
				break;

			case ProductionIndex.Value_Lparan_Rparan_Apost:

				// <Value> ::= '(' <Expression> ')' ''
				Nodes.Push(new FuncNode(KnownFuncType.Diff, new MathFuncNode[] { Nodes.Pop(), null }));
				break;

			case ProductionIndex.Value_Pipe_Pipe_Apost:

				// <Value> ::= '|' <Expression> '|' ''
				Nodes.Push(new FuncNode(KnownFuncType.Diff, new MathFuncNode[] {
						new FuncNode(KnownFuncType.Abs, new MathFuncNode[] { Nodes.Pop() }), null }));
				break;

			/*case ProductionIndex.Value_Id_Apost:

				// <Value> ::= Id ''
				Args.Push(new FuncNode(KnownMathFunctionType.Diff, null,
					new MathFunctionNode[] {
						new FuncNode(r[0].Data.ToString(), null, new MathFunctionNode[] { null }), null }));
				break;*/
		}  //switch
	}