Пример #1
0
        private static SemanticNode FindNode(IEnumerable <SemanticCluster> semanticClusters, string name)
        {
            if (semanticClusters == null)
            {
                return(null);
            }

            SemanticNode match = null;

            foreach (var semanticClaster in semanticClusters)
            {
                match = FindNode(semanticClaster.SemanticNodes, name);
                if (match != null)
                {
                    break;
                }

                match = FindNode(semanticClaster.SemanticClusters, name);
                if (match != null)
                {
                    break;
                }
            }

            return(match);
        }
        private static bool ReportError(IRuntimeCodeValidationErrorSink errorSink, SemanticNode node, string errorMessage)
        {
            if (errorSink == null)
            {
                return(false);
            }

            SourceLocation start = SourceLocation.Invalid;
            SourceLocation end   = SourceLocation.Invalid;

            if (node != null)
            {
                var tokens = node.GetTokens();
                if ((tokens != null) && tokens.Any())
                {
                    start = tokens.Min(t => t.StartPosition);
                    end   = tokens.Max(t => t.StopPosition);
                }
                foreach (var sn in node.GetChildNodes())
                {
                    tokens = sn.GetTokens();
                    if ((tokens != null) && tokens.Any())
                    {
                        start = start.Min(tokens.Min(t => t.StartPosition));
                        end   = end.Max(tokens.Max(t => t.StopPosition));
                    }
                }
            }

            return(RuntimeCompiledMethod.ReportError(errorSink, start, end, errorMessage));
        }
Пример #3
0
        public void Evaluate(IEvolutionState state,
                             Individual ind,
                             int subpopulation,
                             int threadnum)
        {
            if (!ind.Evaluated) // don't bother reevaluating
            {
                // trees[0].Child is the root

                ArrayList output = GetSemanticOutput(((GPIndividual)ind).Trees[0]);

                double score = 0.0;
                for (int i = 0; i < output.Count; i++)
                {
                    SemanticNode n = (SemanticNode)output[i];
                    if (n.Value == 'X')
                    {
                        score += 1;
                    }
                }

                SimpleFitness f = (SimpleFitness)ind.Fitness;
                f.SetFitness(state, score, false);
                ind.Evaluated = true;
            }
        }
Пример #4
0
        public static XmlNode XmlNode(this SemanticNode semanticNode, XmlDocument xmlDoc)
        {
            if (semanticNode.XmlGenerated())
            {
                return(semanticNode.XmlNode);
            }

            var nodeName = semanticNode.NodeNameIsNodeValue
                ? semanticNode.Value
                : semanticNode.Name;

            if (semanticNode.Type == MediatorNodeType.attribute ||
                string.IsNullOrWhiteSpace(nodeName))
            {
                return(null);
            }

            semanticNode.XmlNode = xmlDoc.CreateElement(nodeName);

            foreach (var childSemanticNode in semanticNode.SemanticNodes)
            {
                if (childSemanticNode.Type == MediatorNodeType.attribute)
                {
                    semanticNode.XmlNode.Attributes?.Append(childSemanticNode.XmlAttribute(xmlDoc));
                }
                else
                {
                    semanticNode.XmlNode.AppendChild(childSemanticNode.XmlNode(xmlDoc));
                }
            }

            return(semanticNode.XmlNode);
        }
Пример #5
0
        /**
         * @param t Tree to be "executed"
         * @return expressed output
         */
        ArrayList GetSemanticOutput(GPTree t)
        {
            ArrayList p     = new ArrayList();
            ArrayList nodes = new ArrayList();

            // Is there a better way to get all the nodes in a depth-first
            // traversal? Note that the paper specifies inorder traversal,
            // but since we're only getting the terminals, preorder,
            // inorder, and postorder are equivalent.
            int nterminals = t.Child.NumNodes(GPNode.NODESEARCH_TERMINALS);

            for (int i = 0; i < nterminals; i++)
            {
                GPNodeGatherer g = new GPNodeGatherer();
                t.Child.NodeInPosition(i, g, GPNode.NODESEARCH_TERMINALS);
                nodes.Add(g.Node);
            }

            if (_problemName.Equals(P_ORDER))
            {
                // Order: first occurence counts
                for (int i = 0; i < nodes.Count; i++)
                {
                    SemanticNode node = (SemanticNode)nodes[i];
                    if (!NodeSameIndexExists(p, node.Index))
                    {
                        p.Add(node);
                    }
                }
            }
            else
            {
                // Majority: most common counts
                for (int n = 0; n < _problemSize; n++)
                {
                    int xCount    = 0;
                    int nCount    = 0;
                    int lastXNode = -1;
                    for (int i = 0; i < nodes.Count; i++)
                    {
                        SemanticNode node = (SemanticNode)nodes[i];
                        if (node.Value == 'X' && node.Index == n)
                        {
                            xCount   += 1;
                            lastXNode = i;
                        }
                        else if (node.Value == 'N' && node.Index == n)
                        {
                            nCount += 1;
                        }
                    }
                    if (xCount >= nCount && xCount > 0)
                    {
                        p.Add((SemanticNode)nodes[lastXNode]);
                    }
                }
            }
            return(p);
        }
Пример #6
0
        public static void SetRealParent(this SemanticNode semanticNode,
                                         SemanticGraph semanticGraph,
                                         XmlDocument xmlDoc)
        {
            var realParentNode = semanticGraph.FindCluster(semanticNode.MediatorNodeParent);

            var mediatorNodeParent = realParentNode.XmlNode ?? realParentNode.XmlNode(semanticGraph, xmlDoc);

            mediatorNodeParent.AppendChild(semanticNode.XmlNode ?? semanticNode.XmlNode(xmlDoc));
        }
Пример #7
0
 /// <summary>
 /// Create and initialize a new assignment expression.
 /// </summary>
 /// <param name="parent">Parent node that defines this expression.</param>
 /// <param name="identifier">Identifier token of the assignment target.</param>
 /// <param name="token">Token representing the assignment operator.</param>
 protected internal AssignmentNode(SemanticNode parent, IdentifierToken identifier, AssignmentOperatorToken token)
     : base(parent)
 {
     #if DEBUG
     if (identifier == null)
         throw new ArgumentNullException("identifier");
     if (token == null)
         throw new ArgumentNullException("token");
     #endif
     this.Target = new AssignmentTargetNode(this, identifier);
     this.AssignmentOperator = token;
 }
Пример #8
0
        /// <summary>
        /// Visits the Semantic Node. This is the default visit, in case no other implementation.
        /// </summary>
        /// <param name="node">The node to visit.</param>
        public virtual TResult VisitSemanticNode(SemanticNode node)
        {
            // Naive brute force implementation
            foreach (IParseNode child in node.GetChildNodes())
            {
                if (child is SemanticNode)
                {
                    ((SemanticNode)child).Accept(this);
                }
            }

            return(default(TResult));            // The default naive implementation
        }
Пример #9
0
        public static XmlAttribute XmlAttribute(this SemanticNode semanticNode, XmlDocument xmlDoc)
        {
            if (semanticNode.XmlGenerated() ||
                semanticNode.Type != MediatorNodeType.attribute ||
                string.IsNullOrWhiteSpace(semanticNode.Name))
            {
                return(null);
            }

            var xmlAttribute = xmlDoc.CreateAttribute(semanticNode.Name);

            xmlAttribute.Value = semanticNode.Value;

            return(xmlAttribute);
        }
Пример #10
0
        /// <summary>
        /// Visits the Semantic Node. This is the default visit, in case no other implementation.
        /// </summary>
        /// <param name="node">The node to visit.</param>
        public override bool VisitSemanticNode(SemanticNode node)
        {
            // Naive brute force implementation
            foreach (IParseNode child in node.GetChildNodes())
            {
                if (child is SemanticNode)
                {
                    if (!((SemanticNode)child).Accept(this))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Пример #11
0
        protected virtual BasicExpressionNode ParseBasicExpression(SemanticNode parent, Token token)
        {
            // PARSE: <basic expression> ::= <primary> [<messages> <cascaded messages>]
            BasicExpressionNode result = new BasicExpressionNode(parent);

            IPrimaryNode primary = this.ParsePrimary(result, token);

            if (primary == null)
            {
                this.ReportParserError(result, SemanticErrors.MissingPrimary, token);
                return(result);
            }

            token = this.GetNextTokenxx(Preference.Default);
            this.ParseBaseicExpressionMessages(result, primary, token);
            return(result);
        }
Пример #12
0
        public IHasValue ConvertToCalculationModel(SemanticNode semanticTreeRoot)
        {
            var nodeType = semanticTreeRoot.Type;

            switch (nodeType)
            {
            case SemanticNodeTypes.Number:
            {
                return(_calculationObjectFactory.Create(semanticTreeRoot.Value));
            }

            case SemanticNodeTypes.BinaryFunction:
            {
                var binaryFunctionNode = (BinaryFunctionSemanticNode)semanticTreeRoot;

                var firstValue  = ConvertToCalculationModel(binaryFunctionNode.LeftChild);
                var secondValue = ConvertToCalculationModel(binaryFunctionNode.RightChild);

                var func = (Function)_calculationObjectFactory.Create(binaryFunctionNode.Value);

                func.SetArguments(firstValue, secondValue);

                return(func);
            }

            case SemanticNodeTypes.UnaryFunction:
            {
                var unaryFunctionNode = (UnaryFunctionSemanticNode)semanticTreeRoot;

                var value = ConvertToCalculationModel(unaryFunctionNode.Child);

                var func = (Function)_calculationObjectFactory.Create(unaryFunctionNode.Value);

                func.SetArguments(value);

                return(func);
            }

            default:
                throw new NotSupportedException(
                          _resourceStore.GetExceptionMessage("UnknownSemanticNodeType", semanticTreeRoot.Type));
            }
        }
Пример #13
0
        protected virtual AssignmentNode ParseAssignment(SemanticNode parent, IdentifierToken identifier, AssignmentOperatorToken assignmentOperator)
        {
            // PARSE: <assignment> ::= <assignment target> assignmentOperator <expression>
            //      <assignment target> := identifier
            AssignmentNode result = new AssignmentNode(parent, identifier, assignmentOperator);

            Token          token      = this.GetNextTokenxx(Preference.NegativeSign);
            ExpressionNode expression = this.ParseExpression(result, token);

            if (expression == null)
            {
                this.ReportParserError(result, SemanticErrors.MissingExpression, token);
            }
            else
            {
                result.SetContents(expression);
            }

            return(result);
        }
        internal static bool Validate <TResult>(SemanticNode rootNode, IRuntimeCodeValidationErrorSink errorSink, Func <TResult> compileFunc)
        {
            if (rootNode == null)
            {
                throw new ArgumentNullException("rootNode");
            }
            if (compileFunc == null)
            {
                throw new ArgumentNullException("compileFunc");
            }

            try
            {
                TResult result = compileFunc();
                if (result == null)
                {
                    return(RuntimeCompiledMethod.ReportError(errorSink, rootNode, "Could not compile method"));
                }
                return(true);
            }
            catch (IronSmalltalk.ExpressionCompiler.Primitives.Exceptions.PrimitiveInvalidTypeException ex)
            {
                return(RuntimeCompiledMethod.ReportError(errorSink, ex.GetErrorLocation(), ex.Message));
            }
            catch (SemanticCodeGenerationException ex)
            {
                return(RuntimeCompiledMethod.ReportError(errorSink, ex.GetErrorLocation(), ex.Message));
            }
            catch (IronSmalltalk.Runtime.Internal.SmalltalkDefinitionException ex)
            {
                return(RuntimeCompiledMethod.ReportError(errorSink, rootNode, ex.Message));
            }
            catch (IronSmalltalk.Runtime.Internal.SmalltalkRuntimeException ex)
            {
                return(RuntimeCompiledMethod.ReportError(errorSink, rootNode, ex.Message));
            }
            //catch (Exception ex)
            //{
            //    return RuntimeCompiledMethod.ReportError(errorSink, rootNode, ex.Message);
            //}
        }
Пример #15
0
        private static SemanticNode FindNode(IEnumerable <SemanticNode> semanticNodes, string name)
        {
            if (semanticNodes == null)
            {
                return(null);
            }

            SemanticNode match = null;

            foreach (var semanticNode in semanticNodes)
            {
                match = semanticNode.Find(name)
                    ? semanticNode
                    : FindNode(semanticNode.SemanticNodes, name);

                if (match != null)
                {
                    break;
                }
            }

            return(match);
        }
Пример #16
0
        private void ConvertAllChildBracesToTrees(SemanticNode semanticNode)
        {
            void Analyze(SemanticNode nodeToAnalyze, Action <SemanticNode> swapChilds)
            {
                if (nodeToAnalyze.Type == SemanticNodeTypes.Braces)
                {
                    var braces   = (BracesSemanticNode)nodeToAnalyze;
                    var newChild = BuildSemanticTree(braces.ChildNodes);

                    swapChilds(newChild);
                }
                else if (nodeToAnalyze.Type != SemanticNodeTypes.Number)
                {
                    ConvertAllChildBracesToTrees(nodeToAnalyze);
                }
            }

            switch (semanticNode.Type)
            {
            case SemanticNodeTypes.UnaryFunction:
            {
                var funcNode = (UnaryFunctionSemanticNode)semanticNode;

                Analyze(funcNode.Child, (nc) => funcNode.Child = nc);
            }
            break;

            case SemanticNodeTypes.BinaryFunction:
            {
                var funcNode = (BinaryFunctionSemanticNode)semanticNode;

                Analyze(funcNode.LeftChild, (nc) => funcNode.LeftChild   = nc);
                Analyze(funcNode.RightChild, (nc) => funcNode.RightChild = nc);
            }
            break;
            }
        }
Пример #17
0
        // <expression> ::=
        //      <assignment> |
        //      <basic expression>
        // <assignment> ::= <assignment target> assignmentOperator <expression>
        // <basic expression> ::= <primary> [<messages> <cascaded messages>]
        // <assignment target> := identifier
        // <primary> ::=
        //      identifier |
        //      <literal> |
        //      <block constructor> |
        //      ( '(' <expression> ')' )

        protected virtual ExpressionNode ParseExpression(SemanticNode parent, Token token)
        {
            // Tricky ... first try for <assignment>
            if (token is IdentifierToken)
            {
                // In here, we either have an <assignment target> or <primary> of a <basic expression>
                IdentifierToken identifier = (IdentifierToken)token;

                // Try to check for assignmentOperator
                token = this.GetNextTokenxx(Preference.Default);
                if (token is AssignmentOperatorToken)
                {
                    // OK, it's <assignment>
                    return(this.ParseAssignment(parent, identifier, (AssignmentOperatorToken)token));
                }

                // Must recover ... it is a <basic expression> anyway.
                // PARSE: identifier [<messages> <cascaded messages>]
                BasicExpressionNode result = new BasicExpressionNode(parent);
                this.ParseBaseicExpressionMessages(result, new VariableReferenceleNode(result, identifier), token);
                return(result);
            }
            return(this.ParseBasicExpression(parent, token));
        }
Пример #18
0
        protected virtual AssignmentNode ParseAssignment(SemanticNode parent, IdentifierToken identifier, AssignmentOperatorToken assignmentOperator)
        {
            // PARSE: <assignment> ::= <assignment target> assignmentOperator <expression>
            //      <assignment target> := identifier
            AssignmentNode result = new AssignmentNode(parent, identifier, assignmentOperator);

            Token token = this.GetNextTokenxx(Preference.NegativeSign);
            ExpressionNode expression = this.ParseExpression(result, token);

            if (expression == null)
                this.ReportParserError(result, SemanticErrors.MissingExpression, token);
            else
                result.SetContents(expression);

            return result;
        }
Пример #19
0
        protected virtual BasicExpressionNode ParseBasicExpression(SemanticNode parent, Token token)
        {
            // PARSE: <basic expression> ::= <primary> [<messages> <cascaded messages>]
            BasicExpressionNode result = new BasicExpressionNode(parent);

            IPrimaryNode primary = this.ParsePrimary(result, token);
            if (primary == null)
            {
                this.ReportParserError(result, SemanticErrors.MissingPrimary, token);
                return result;
            }

            token = this.GetNextTokenxx(Preference.Default);
            this.ParseBaseicExpressionMessages(result, primary, token);
            return result;
        }
Пример #20
0
 /// <summary>
 /// Create a new expression node.
 /// </summary>
 /// <param name="parent">Parent node that defines this expression.</param>
 protected ExpressionNode(SemanticNode parent)
 {
     #if DEBUG
     if (parent == null)
         throw new ArgumentNullException("parent");
     #endif
     this.Parent = parent;
 }
Пример #21
0
 /// <summary>
 /// Create a new basic expression parse node.
 /// </summary>
 /// <param name="parent">Parent node that defines this expression.</param>
 protected internal BasicExpressionNode(SemanticNode parent)
     : base(parent)
 {
 }
Пример #22
0
 public static bool Find(this SemanticNode semanticNode, string name)
 {
     return(!string.IsNullOrWhiteSpace(semanticNode.Name) &&
            semanticNode.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));
 }
Пример #23
0
        // <expression> ::=
        //      <assignment> |
        //      <basic expression>
        // <assignment> ::= <assignment target> assignmentOperator <expression>
        // <basic expression> ::= <primary> [<messages> <cascaded messages>]
        // <assignment target> := identifier
        // <primary> ::=
        //      identifier |
        //      <literal> |
        //      <block constructor> |
        //      ( '(' <expression> ')' )
        protected virtual ExpressionNode ParseExpression(SemanticNode parent, Token token)
        {
            // Tricky ... first try for <assignment>
            if (token is IdentifierToken)
            {
                // In here, we either have an <assignment target> or <primary> of a <basic expression>
                IdentifierToken identifier = (IdentifierToken)token;

                // Try to check for assignmentOperator
                token = this.GetNextTokenxx(Preference.Default);
                if (token is AssignmentOperatorToken)
                    // OK, it's <assignment>
                    return this.ParseAssignment(parent, identifier, (AssignmentOperatorToken)token);

                // Must recover ... it is a <basic expression> anyway.
                // PARSE: identifier [<messages> <cascaded messages>]
                BasicExpressionNode result = new BasicExpressionNode(parent);
                this.ParseBaseicExpressionMessages(result, new VariableReferenceleNode(result, identifier), token);
                return result;
            };
            return this.ParseBasicExpression(parent, token);
        }
 public BindingCodeGeneraionException(NameBinding binding, SemanticNode node)
     : base((binding is IErrorBinding) ? ((IErrorBinding)binding).ErrorDescription : CodeGenerationErrors.UndefinedBinding, node)
 {
 }
Пример #25
0
 public BindingCodeGeneraionException(NameBinding binding, SemanticNode node)
     : this(BindingCodeGeneraionException.GetErrorDescription(binding), node)
 {
 }
Пример #26
0
 public static bool Match(this SemanticNode semanticNode, string semanticKey)
 {
     return(!string.IsNullOrWhiteSpace(semanticNode.SemanticKey) &&
            semanticNode.SemanticKey.Equals(semanticKey, StringComparison.InvariantCultureIgnoreCase));
 }
 public SemanticCodeGenerationException(string message, SemanticNode node)
     : base(message)
 {
     this.Node = node;
 }
 public PrimitiveInvalidTypeException(string message, SemanticNode node)
     : base(message)
 {
     this.Node = node;
 }
 public PrimitiveSemanticException(string message, SemanticNode node)
     : base(message, node)
 {
 }
 public BindingCodeGeneraionException(string message, SemanticNode node)
     : base(message, node)
 {
 }
 public UnaryFunctionSemanticNode(string value, BracesSemanticNode bracesNode)
     : base(SemanticNodeTypes.UnaryFunction, value)
 {
     Child = bracesNode;
 }
Пример #32
0
 public BindingCodeGeneraionException(string message, SemanticNode node)
     : this(message)
 {
     this.SetErrorLocation(node);
 }
Пример #33
0
 /// <summary>
 /// Visits the Semantic Node. This is the default visit, in case no other implementation.
 /// </summary>
 /// <param name="node">The node to visit.</param>
 public virtual TResult VisitSemanticNode(SemanticNode node)
 {
     throw new NotImplementedException();
 }
Пример #34
0
        public static TException SetErrorLocation <TException>(this TException exception, SemanticNode node)
            where TException : IronSmalltalk.Runtime.Execution.Internals.CodeGenerationException
        {
            if (exception == null)
            {
                return(null);
            }

            ErrorLocation errorLocation = null;

            if (node != null)
            {
                SourceLocation start = SourceLocation.Invalid;
                SourceLocation end   = SourceLocation.Invalid;

                List <Compiler.LexicalTokens.IToken> allTokens = new List <Compiler.LexicalTokens.IToken>();
                var tokens = node.GetTokens();
                if (tokens != null)
                {
                    allTokens.AddRange(tokens);
                }
                foreach (var sn in node.GetChildNodes())
                {
                    tokens = sn.GetTokens();
                    if (tokens != null)
                    {
                        allTokens.AddRange(tokens);
                    }
                }


                if (allTokens.Count != 0)
                {
                    start = allTokens.Min(t => t.StartPosition);
                    end   = allTokens.Max(t => t.StopPosition);
                }

                errorLocation = new ErrorLocation(start, end);
            }


            exception.Data[ExceptionHelper.ErrorLocationKey] = errorLocation;
            return(exception);
        }