Beispiel #1
0
        public Assigment(ASTNode?node, IMnemonicsCompiler runtime) : base(node)
        {
            var variableNameNode = node.GetChildAndAddError(0, "variable_name", runtime, true);
            var varValueTable    = node.GetChildAndAddError(0, "var_value_table", runtime, true);

            if (variableNameNode.HasValue)
            {
                LeftSide = new VariableName(variableNameNode, runtime);
            }
            else if (varValueTable.HasValue)
            {
                LeftSide = new ValueTable(varValueTable, runtime);
            }
            else
            {
                runtime.AddError(new CompilationError(
                                     "Failed to find variable name in left side of assigment."));
            }

            var expression =
                runtime.Get(node.Value.Children[2]);

            RightSide =
                expression;
        }
Beispiel #2
0
        public MethodCall(ASTNode?node, IMnemonicsCompiler runtime) : base(node)
        {
            var namespaceName = node.GetChildAndAddError(0, "namespace", runtime)
                                .GetChildAndAddError(0, "LITERAL", runtime, false);

            var methodName = node.GetChildAndAddError(2, "method_name", runtime)
                             .GetChildAndAddError(0, "LITERAL", runtime, false);
            var methodArguments = node.GetChildAndAddError(4, "method_arguments", runtime, true);

            if (namespaceName.HasValue && methodName.HasValue)
            {
                Pointer = new MethodPointer
                {
                    NameSpace = namespaceName.Value.Value,
                    Name      = methodName.Value.Value
                };

                Arguments = new Arguments();

                if (methodArguments.HasValue)
                {
                    for (var k = 0; k < methodArguments.Value.Children.Count; k += 2)
                    {
                        var element = methodArguments.Value.Children.ElementAt(k);
                        var value   = runtime.Get(element);
                        Arguments.Args.Add(value);
                    }
                }
            }
        }
Beispiel #3
0
        public MethodDeclaration(ASTNode?node, IMnemonicsCompiler compiler) : base(node)
        {
            var nameSpace = node.GetChildAndAddError(0, "namespace", compiler)
                            .GetChildAndAddError(0, "LITERAL", compiler)?.Value;
            var method_name = node.GetChildAndAddError(2, "method_name", compiler)
                              .GetChildAndAddError(0, "LITERAL", compiler)?.Value;
            var body = node.GetChildAndAddError(node.Value.Children.Count - 1, "block_of_lopla", compiler);
            var code = compiler.Get(body);

            var method_parameters = node.GetChildAndAddError(4, "method_parameters", compiler, true);

            var methodArguments = new List <string>();

            if (method_parameters != null && method_parameters.Value.Children.Any())
            {
                foreach (var valueChild in method_parameters.Value.Children)
                {
                    var name = valueChild.GetChildAndAddError(0, "LITERAL", compiler).Value.Value;
                    methodArguments.Add(name);
                }
            }

            Pointer = new MethodPointer {
                Name = method_name, NameSpace = nameSpace
            };
            Code = new Method
            {
                ArgumentList = methodArguments,
                Code         = new List <Mnemonic>
                {
                    code
                }
            };
        }
Beispiel #4
0
        internal bool TryParse(ILookaroundEnumerator <Token> enumerator, [NotNullWhen(true)] out ASTNode?parsedNode, AssignmentOperatorBehavior assignmentOperatorBehavior, int currentPrecedence = 0)
        {
            if (currentPrecedence == 0 && CustomParseDelegates != default)
            {
                var customResult = CustomParseDelegates.Select(del =>
                {
                    var Success = del(enumerator, out var Result, assignmentOperatorBehavior);
                    return(new { Success, Result });
                }).FirstOrDefault(res => res.Success)?.Result;
                if (customResult != default)
                {
                    enumerator.MoveNext(); // TODO: Is this right?
                    parsedNode = customResult;
                    return(true);
                }
            }

            if (currentPrecedence >= _PrecedenceGroups.Length)
            {
                return(TryParseBraces(enumerator, out parsedNode, assignmentOperatorBehavior));
            }

            return(_PrecedenceGroups[currentPrecedence].First().OperandCount switch
            {
                OperandCount.Binary => TryParseBinary(enumerator, currentPrecedence, out parsedNode, assignmentOperatorBehavior),
                OperandCount.Unary => TryParseUnary(enumerator, currentPrecedence, out parsedNode),
                _ => throw new NotImplementedException(),
            });
Beispiel #5
0
        internal bool TryParseDictionary(ILookaroundEnumerator <Token> enumerator, [NotNullWhen(true)] out ASTNode?parsedNode, AssignmentOperatorBehavior assignmentOperatorBehavior)
        {
            parsedNode = default;
            if (enumerator.Current.TokenType != TokenType.CurlyBraceOpen)
            {
                return(false);
            }

            var dictionaryItems = new Queue <DictionaryItemNode>();

            while (enumerator.MoveNext() && TryParseDictionaryItem(enumerator, out var dictionaryItem, assignmentOperatorBehavior))
            {
                dictionaryItems.Enqueue(dictionaryItem);
                if (enumerator.MoveNext() == false)
                {
                    throw new NotImplementedException();
                }
                if (enumerator.Current.TokenType != TokenType.Comma)
                {
                    break;
                }
            }

            if (enumerator.State == EnumeratorState.Complete || enumerator.Current.TokenType != TokenType.CurlyBraceClose)
            {
                throw new NotImplementedException();
            }
            parsedNode = new DictionaryNode(dictionaryItems);
            return(true);
        }
Beispiel #6
0
 public VariableName(ASTNode?node, IMnemonicsCompiler runtime) : base(node)
 {
     Pointer = new VariablePointer
     {
         Name = node.GetChildAndAddError(0, "LITERAL", runtime)?.Value
     };
 }
Beispiel #7
0
 public ValueString(ASTNode?node) : base(node)
 {
     Value = new String
     {
         Value = node.Value.Value?.Trim('\"')
     };
 }
Beispiel #8
0
        public ExpressionCommon(ASTNode?node, IMnemonicsCompiler runtime) : base(node)
        {
            Arguments = new Arguments();

            if (node?.Children.Count == 3)
            {
                var left   = node?.Children[0];
                var middle = node?.Children[1];
                var right  = node?.Children[2];

                var leftExpression  = runtime.Get(left);
                var operatorKind    = middle.Value.Value;
                var rightExpression = runtime.Get(right);

                var o = new Operator();

                if (Expression.Operators.ContainsKey(operatorKind))
                {
                    o.Kind = Expression.Operators[operatorKind];
                }
                else
                {
                    runtime.AddError(
                        new CompilationError($"Operator {operatorKind} is not discovered by compiler."));
                }
                Arguments.Args.Add(leftExpression);
                Arguments.Args.Add(o);
                Arguments.Args.Add(rightExpression);
            }
            else if (node?.Children.Count == 1)
            {
                Arguments.Args.Add(runtime.Get(node.Value.Children[0]));
            }
        }
        public override AASTNode Annotate(ASTNode astNode, AASTNode?parent)
        {
            AASTNode returnNode = new AASTNode(astNode, parent, SemanticAnalyzer.no_type);
            // Check if "return" is in right place - inside the routine body
            ASTNode?parentCopy = returnNode.Parent;

            while (parentCopy != null)
            {
                if (parentCopy.ASTType.Equals("Routine body"))
                {
                    // Perform the rest of checks
                    if (astNode.Children[1].Children[0].Children.Count > 0) // If it has something to return
                    {
                        if (astNode.Children[1].Children[0].Children[0].Children[0].ASTType.Equals("Call"))
                        {
                            returnNode.Children.Add(base.Annotate(astNode.Children[1].Children[0].Children[0], returnNode));
                        }
                        else
                        {
                            returnNode.Children.Add(base.Annotate(astNode.Children[1].Children[0].Children[0].Children[0], returnNode));
                        }
                    }
                    return(returnNode);
                }
                parentCopy = parentCopy.Parent;
            }
            throw new SemanticErrorException(
                      "Return is not in place!!!\r\n" +
                      "  At (Line: " + astNode.Children[0].Token.Position.Line.ToString() + ", " +
                      "Char: " + astNode.Children[0].Token.Position.Char.ToString() + ")."
                      );
        }
 public AuthorizationError(ASTNode?node, ValidationContext context, string message, AuthorizationResult result, OperationType?operationType = null)
     : base(context.Document.Source, "6.1.1", message, node == null ? Array.Empty <ASTNode>() : new ASTNode[] { node })
 {
     Code = "authorization";
     AuthorizationResult = result;
     OperationType       = operationType;
 }
Beispiel #11
0
        public static ASTNode?GetChildAndAddError(this ASTNode?node, int i, string tokenName, IMnemonicsCompiler runtime,
                                                  bool optional = false)
        {
            if (node != null)
            {
                if (node.Value.Children.Count >= i + 1)
                {
                    var element = node.Value.Children.ElementAt(i);
                    if (element.Symbol.Name != tokenName)
                    {
                        if (!optional)
                        {
                            runtime.AddError(new CompilationError($"Expected: {tokenName} but found: {element.Symbol.Name}."));
                        }
                    }
                    else
                    {
                        return(element);
                    }
                }
                else if (!optional)
                {
                    runtime.AddError(new CompilationError($"Expected: {i} tokens but found: {node.Value.Children.Count} when looking for: {tokenName}."));
                }
            }
            else
            {
                if (!optional)
                {
                    runtime.AddError(new CompilationError($"Parent node for: {tokenName} not found."));
                }
            }

            return(null);
        }
Beispiel #12
0
 public VariableName(ASTNode?node, string name) : base(node)
 {
     this.Pointer = new VariablePointer()
     {
         Name = name
     };
 }
Beispiel #13
0
 public Block(ASTNode?node, IMnemonicsCompiler runtime) : base(node)
 {
     foreach (var valueChild in node.Value.Children)
     {
         var mnemonic = runtime.Get(valueChild);
         Lines.Add(mnemonic);
     }
 }
Beispiel #14
0
        public ExpressionBracket(ASTNode?node, IMnemonicsCompiler runtime) : base(node)
        {
            if (node?.Children.Count == 1)
            {
                var expresionToken = node?.Children[0];

                SubExpresion = runtime.Get(expresionToken);
            }
        }
Beispiel #15
0
 internal bool TryParseList(ILookaroundEnumerator <Token> enumerator, [NotNullWhen(true)] out ASTNode?parsedNode, AssignmentOperatorBehavior assignmentOperatorBehavior)
 {
     if (TryParseCommaSeperatedSet(enumerator, TokenType.Operator, _OPERATOR_SQUARE_BRACE_OPEN, SquareBraceClose, out var parsedListItems, minimumItems: 0, assignmentOperatorBehavior))
     {
         parsedNode = new ListNode(parsedListItems);
         return(true);
     }
     parsedNode = default;
     return(false);
 }
Beispiel #16
0
        public If(ASTNode?node, IMnemonicsCompiler runtime) : base(node)
        {
            var logicalTest = node.GetChildAndAddError(1, "expression", runtime, false);

            Condition = runtime.Get(logicalTest);

            var blockOfLopla = node.GetChildAndAddError(2, "block_of_lopla", runtime, false);

            BlockOfCode = runtime.Get(blockOfLopla);
        }
Beispiel #17
0
 internal bool TryParseTuple(ILookaroundEnumerator <Token> enumerator, [NotNullWhen(true)] out ASTNode?parsedNode, AssignmentOperatorBehavior assignmentOperatorBehavior)
 {
     if (TryParseCommaSeperatedSet(enumerator, TokenType.Operator, _OPERATOR_PAREN_OPEN, ParenClose, out var parsedListItems, minimumItems: 2, assignmentOperatorBehavior))
     {
         parsedNode = new TupleNode(parsedListItems);
         return(true);
     }
     parsedNode = default;
     return(false);
 }
Beispiel #18
0
 public ValueTable(ASTNode?node, IMnemonicsCompiler runtime) : base(node)
 {
     TablePointer = new VariablePointer
     {
         Name = node
                .GetChildAndAddError(0, "variable_name", runtime)?
                .GetChildAndAddError(0, "LITERAL", runtime)?.Value
     };
     ElementPositionInTable = runtime.Get(node.Value.Children[1]);
 }
Beispiel #19
0
        /// <summary>
        /// Adds a location to an <see cref="ExecutionError"/> based on a <see cref="ASTNode"/> within a <see cref="GraphQLDocument"/>.
        /// </summary>
        public static TError AddLocation <TError>(this TError error, ASTNode?abstractNode, GraphQLDocument?document)
            where TError : ExecutionError
        {
            if (abstractNode == null || abstractNode.Location == default || document == null || document.Source.IsEmpty)
            {
                return(error);
            }

            error.AddLocation(Location.FromLinearPosition(document.Source, abstractNode.Location.Start));
            return(error);
        }
Beispiel #20
0
 public ExpressionPrefix(ASTNode?node, IMnemonicsCompiler runtime) : base(node)
 {
     if (node?.Children.Count == 2)
     {
         var right = node?.Children[1];
         this.MultByMinus1 = runtime.Get(right);
     }
     else
     {
         this.ExpressionToPrefix = runtime.Get(node.Value.Children[0]);
     }
 }
Beispiel #21
0
        /// <summary>
        /// Creates an AST node.
        /// </summary>
        /// <param name="parent">Ref to the parent AST node.</param>
        /// <param name="children">Ref to the list of AST children nodes.</param>
        /// <param name="token">Corresponding token from the lexical analyzer.</param>
        /// <param name="type">The type of the AST node (basically syntax rule).</param>
        public ASTNode(ASTNode?parent, List <ASTNode> children, Token token, string type)
        {
            Parent   = parent;
            Children = children;
            Token    = token;
            ASTType  = type;

            if (parent != null)
            {
                level = parent.level + 2;
            }
        }
Beispiel #22
0
        public int Visualize(ASTNode?ast)
        {
            if (ast is null)
            {
                return(1);
            }

            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new VisualizeForm(ast));
            return(0);
        }
Beispiel #23
0
            public override async ValueTask VisitAsync(ASTNode?node, GetVariablesVisitorContext context)
            {
                if (node == null)
                {
                    return;
                }

                context.Info.Enter(node, context.ValidationContext);

                await base.VisitAsync(node, context).ConfigureAwait(false);

                context.Info.Leave(node, context.ValidationContext);
            }
Beispiel #24
0
        public DeclareTable(ASTNode?node, IMnemonicsCompiler runtime) : base(node)
        {
            Values = new List <Mnemonic>();

            var kids = node.GetChildAndAddError(0, "declare_table_values", runtime, true);

            if (kids.HasValue && kids.Value.Children.Count > 0)
            {
                foreach (var valueChild in kids.Value.Children)
                {
                    Values.Add(runtime.Get(valueChild));
                }
            }
        }
Beispiel #25
0
        public Return(ASTNode?node, IMnemonicsCompiler runtime) : base(node)
        {
            var returnValue =
                node.GetChildAndAddError(1, "expression", runtime, true);

            if (returnValue == null)
            {
                ReturnExpression = new Nop(node);
            }
            else
            {
                ReturnExpression = runtime.Get(returnValue);
            }
        }
Beispiel #26
0
        protected Mnemonic(ASTNode?node)
        {
            if (node.HasValue)
            {
                Symbol = node?.Symbol.Name;

                var n = node;
                do
                {
                    Line   = n?.Position.Line;
                    Column = n?.Position.Column;

                    n = n.Value.Children.Count > 0 ? (ASTNode?)n.Value.Children[0] : null;
                } while (Line == 0 && n != null);
            }
        }
        /// <summary>
        /// Walks the specified <see cref="ASTNode"/>, executing <see cref="INodeVisitor.Enter(ASTNode, ValidationContext)"/> and
        /// <see cref="INodeVisitor.Leave(ASTNode, ValidationContext)"/> methods for each node.
        /// </summary>
        public override async ValueTask VisitAsync(ASTNode?node, State context)
        {
            if (node != null)
            {
                for (int i = 0; i < _visitors.Count; ++i)
                {
                    _visitors[i].Enter(node, context.Context);
                }

                await base.VisitAsync(node, context).ConfigureAwait(false);

                for (int i = _visitors.Count - 1; i >= 0; --i)
                {
                    _visitors[i].Leave(node, context.Context);
                }
            }
        }
Beispiel #28
0
        private static bool TryBuildFromFile(string path, out ASTNode?ast)
        {
            Log.Information("Creating AST for file: {Path}", path);

            ast = null;
            try {
                ast = new ImperativeASTFactory().BuildFromFile(path);
                return(true);
            } catch (SyntaxErrorException e) {
                Log.Fatal(e, "[{Path}] Syntax error: {Details}", path, e.Message ?? "unknown");
            } catch (NotImplementedException e) {
                Log.Fatal(e, "[{Path}] Not supported: {Details}", path, e.Message ?? "unknown");
            } catch (UnsupportedLanguageException e) {
                Log.Fatal(e, "[{Path}] Not supported language", path);
            } catch (Exception e) {
                Log.Fatal(e, "[{Path}] Exception occured", path);
            }

            return(false);
        }
        public override AASTNode Annotate(ASTNode astNode, AASTNode?parent)
        {
            AASTNode breakNode = new AASTNode(astNode, parent, SemanticAnalyzer.no_type);
            // Check if "break" is in the right place - inside the loop body
            ASTNode?parentCopy = breakNode.Parent;

            while (parentCopy != null)
            {
                if (parentCopy.ASTType.Equals("Loop body"))
                {
                    return(breakNode);
                }
                parentCopy = parentCopy.Parent;
            }
            throw new SemanticErrorException(
                      "Break is not in place!!!\r\n" +
                      "  At (Line: " + astNode.Children[0].Token.Position.Line.ToString() + ", " +
                      "Char: " + astNode.Children[0].Token.Position.Char.ToString() + ")."
                      );
        }
Beispiel #30
0
        /// <summary>
        /// Executes the test as a parsing test with a non-matching condition
        /// </summary>
        /// <param name="parser">The parser to use</param>
        /// <returns>The test result</returns>
        private int TestNoMatches(Hime.Redist.Parsers.BaseLRParser parser)
        {
            ASTNode?expected = GetExpectedAST();

            if (!expected.HasValue)
            {
                Console.WriteLine("Failed to parse the expected AST");
                return(RESULT_FAILURE_PARSING);
            }
            ParseResult result = parser.Parse();

            foreach (ParseError error in result.Errors)
            {
                Console.WriteLine(error);
                TextContext context = result.Input.GetContext(error.Position);
                Console.WriteLine(context.Content);
                Console.WriteLine(context.Pointer);
            }
            if (!result.IsSuccess)
            {
                Console.WriteLine("Failed to parse the input");
                return(RESULT_FAILURE_PARSING);
            }
            if (result.Errors.Count != 0)
            {
                Console.WriteLine("Some errors while parsing the input");
                return(RESULT_FAILURE_PARSING);
            }
            if (Compare(expected.Value, result.Root))
            {
                Console.WriteLine("Produced AST incorrectly matches the specified expectation");
                return(RESULT_FAILURE_VERB);
            }
            else
            {
                return(RESULT_SUCCESS);
            }
        }