Ejemplo n.º 1
0
 public void Accept(IVisitor visitor)
 {
     visitor.VisitEnter(this);
     Left.Accept(visitor);
     Right.Accept(visitor);
     visitor.VisitLeave(this);
 }
Ejemplo n.º 2
0
 public void Accept(IVisitor visitor)
 {
     visitor.VisitEnter(this);
     Expression.Accept(visitor);
     Index.Accept(visitor);
     visitor.VisitLeave(this);
 }
Ejemplo n.º 3
0
        public OptionalValue <BitcodeModule> Generate(IAstNode ast)
        {
            ast.ValidateNotNull(nameof(ast));
            ast.Accept(this);

            if (AnonymousFunctions.Count > 0)
            {
                var mainFunction = Module.CreateFunction("main", Context.GetFunctionType(Context.VoidType));
                var block        = mainFunction.AppendBasicBlock("entry");
                var irBuilder    = new InstructionBuilder(block);
                var printdFunc   = Module.CreateFunction("printd", Context.GetFunctionType(Context.DoubleType, Context.DoubleType));
                foreach (var anonFunc in AnonymousFunctions)
                {
                    var value = irBuilder.Call(anonFunc);
                    irBuilder.Call(printdFunc, value);
                }

                irBuilder.Return( );

                // Use always inline and Dead Code Elimination module passes to inline all of the
                // anonymous functions. This effectively strips all the calls just generated for main()
                // and inlines each of the anonymous functions directly into main, dropping the now
                // unused original anonymous functions all while retaining all of the original source
                // debug information locations.
                using var mpm = new ModulePassManager( );
                mpm.AddAlwaysInlinerPass( )
                .AddGlobalDCEPass( )
                .Run(Module);

                Module.DIBuilder.Finish( );
            }

            return(OptionalValue.Create(Module));
        }
Ejemplo n.º 4
0
        protected internal virtual string Output2MySql(IAstNode node, string sql)
        {
            var sb = new StringBuilder(sql.Length);

            node.Accept(new MySqlOutputAstVisitor(sb));
            return(sb.ToString());
        }
Ejemplo n.º 5
0
        public static string ToString(IAstNode ast, bool showOffsets = false)
        {
            var dumper = new DumpAstVisitor(showOffsets);
            var code   = ast.Accept(dumper);

            return(code);
        }
Ejemplo n.º 6
0
 public IExpression Resolve(IAstNode node)
 {
     return(node
            .Accept(new ConstantParsingVisitor())
            .Accept(new BindingVisitor(this))
            .Accept(new ConversionVisitor(this)));
 }
Ejemplo n.º 7
0
        public List <IOperation> Compile(IAstNode node)
        {
            var irVisitor = new IRVisitor();

            node.Accept(irVisitor);
            return(irVisitor.Operations);
        }
Ejemplo n.º 8
0
        private IExpression Index(IAstNode operand, AstNodeCollection arguments)
        {
            var resolvedArguments = ResolveArguments(arguments);

            var resolvedOperand = operand.Accept(this);

            if (resolvedOperand.Type.IsArray)
            {
                if (resolvedArguments.Length != resolvedOperand.Type.GetArrayRank())
                {
                    throw new ExpressionsException(
                              "Invalid array index rank",
                              ExpressionsExceptionType.TypeMismatch
                              );
                }

                foreach (var argument in resolvedArguments)
                {
                    if (!TypeUtil.IsCastAllowed(argument.Type, typeof(int)))
                    {
                        throw new ExpressionsException(
                                  "Argument of array index must be convertable to integer",
                                  ExpressionsExceptionType.TypeMismatch
                                  );
                    }
                }

                if (resolvedArguments.Length == 1)
                {
                    return(new Expressions.Index(resolvedOperand, resolvedArguments[0], resolvedOperand.Type.GetElementType()));
                }
                else
                {
                    return(_resolver.ResolveMethod(resolvedOperand, "Get", resolvedArguments));
                }
            }

            var defaultMemberAttributes = resolvedOperand.Type.GetCustomAttributes(typeof(DefaultMemberAttribute), true);

            if (defaultMemberAttributes.Length != 1)
            {
                throw new ExpressionsException(
                          "Operand does not support indexing",
                          ExpressionsExceptionType.TypeMismatch
                          );
            }

            var result = _resolver.ResolveMethod(resolvedOperand, "get_" + ((DefaultMemberAttribute)defaultMemberAttributes[0]).MemberName, resolvedArguments);

            if (result == null)
            {
                throw new ExpressionsException(
                          "Unresolved index method",
                          ExpressionsExceptionType.UnresolvedMethod
                          );
            }

            return(result);
        }
Ejemplo n.º 9
0
        public IReadOnlyList <Block> Render(IAstNode node)
        {
            var context = new ParsingContext(1);

            node.Accept(this, context);
            context.Blocks.Trim();
            return(context.Blocks);
        }
Ejemplo n.º 10
0
        /// <summary>Gets the complete collection of errors for this node and children</summary>
        /// <param name="node">Node to traverse for errors</param>
        /// <remarks>Traverses the node hierarchy to find all error node at any depth</remarks>
        /// <returns>Collection of errors found</returns>
        public static IReadOnlyCollection <ErrorNode> CollectErrors([ValidatedNotNull] this IAstNode node)
        {
            node.ValidateNotNull(nameof(node));
            var collector = new ErrorNodeCollector();

            node.Accept <string>(collector);
            return(collector.Errors);
        }
Ejemplo n.º 11
0
        private IEnumerable <IInstruction> Eval(IAstNode node, IInstruction atTheEnd)
        {
            var evalVisitor = new CodeGenVisitor(this.readOnlyEnvData);

            node.Accept(evalVisitor);
            evalVisitor.instructions.Add(atTheEnd);
            return(evalVisitor.instructions);
        }
Ejemplo n.º 12
0
        internal void Ast_VisitsCorrectMethod(IAstNode node, string expectedCalledMethod)
        {
            var visitorCallCounting = new AstVisitorCallCounting();

            node.Accept(visitorCallCounting);
            Assert.Single(visitorCallCounting.CallCount);
            Assert.Equal(1, visitorCallCounting.CallCount[expectedCalledMethod]);
        }
Ejemplo n.º 13
0
        /// <summary>
        ///     Calculated two values and returns the result
        /// </summary>
        /// <param name="target">Visitor to use when calculating the values</param>
        /// <param name="value1">Value to the left</param>
        /// <param name="value2">Value to the right</param>
        /// <param name="calcInt">Method to calculate values if int</param>
        /// <param name="calcDec">Method to calculate values if decimal</param>
        /// <param name="error">Method to handle errors (usually type errors)</param>
        /// <returns>The result of the calculation</returns>
        public static object Calculate(this IVisitor target, IAstNode value1, IAstNode value2,
                                       Func <int, int, object> calcInt, Func <decimal, decimal, object> calcDec,
                                       Func <object, object, Exception, object> error)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (value1 == null)
            {
                throw new ArgumentNullException(nameof(value1));
            }

            if (value2 == null)
            {
                throw new ArgumentNullException(nameof(value2));
            }

            if (calcInt == null)
            {
                throw new ArgumentNullException(nameof(calcInt));
            }

            if (calcDec == null)
            {
                throw new ArgumentNullException(nameof(calcDec));
            }

            if (error == null)
            {
                throw new ArgumentNullException(nameof(error));
            }

            var v1 = value1.Accept(target);
            var v2 = value2.Accept(target);

            try
            {
                if (v1 is int i1 && v2 is int i2)
                {
                    return(calcInt(i1, i2));
                }

                if (!ValueHelper.IsNumeric(v1) || !ValueHelper.IsNumeric(v2))
                {
                    return(error(v1, v2, new InvalidOperationException("Value is not numeric!")));
                }

                var d1 = Convert.ToDecimal(v1);
                var d2 = Convert.ToDecimal(v2);
                return(calcDec(d1, d2));
            }
            catch (Exception innerException)
            {
                return(error(v1, v2, innerException));
            }
        }
Ejemplo n.º 14
0
        public static DirectedGraph CreateGraph([ValidatedNotNull] this IAstNode node)
        {
            node.ValidateNotNull(nameof(node));

            var generator = new AstGraphGenerator();

            node.Accept(generator);
            return(generator.Graph);
        }
Ejemplo n.º 15
0
        public static void AstEquals(IAstNode astExpected, IAstNode astActual, bool showOffsets = false)
        {
            var dumper = new DumpAstVisitor(showOffsets);

            var expectedCode = astExpected.Accept(dumper);
            var actualCode   = astActual.Accept(dumper);

            Check.That(actualCode).IsEqualTo(expectedCode);
            Console.WriteLine(expectedCode);
        }
Ejemplo n.º 16
0
        public static void AstEquals(IAstNode astExpected, IAstNode astActual, bool showOffsets = false)
        {
            var dumper = new DumpAstVisitor(showOffsets);

            var expectedCode = astExpected.Accept(dumper);
            var actualCode = astActual.Accept(dumper);

            Check.That(actualCode).IsEqualTo(expectedCode);
            Console.WriteLine(expectedCode);
        }
Ejemplo n.º 17
0
 public Value Generate(IAstNode ast, Action <CodeGeneratorException> codeGenerationErroHandler)
 {
     try
     {
         // Prototypes, including extern are ignored as AST generation
         // adds them to the RuntimeState so that already has the declarations
         return((ast is FunctionDefinition) ? ast.Accept(this) : null);
     }
     catch (CodeGeneratorException ex) when(codeGenerationErroHandler != null)
     {
         codeGenerationErroHandler(ex);
         return(null);
     }
 }
Ejemplo n.º 18
0
        private void Accept(SqlAstVisitor visitor, IList<ITransformer> tranformers, IAstNode parent)
        {
            Debug.WriteLine(parent.Level+"\t"+parent.ParentNode + "\t" + parent +"\t" + parent.OriginalValue);

            foreach (ITransformer transformer in tranformers)
            {
                parent.Transform(transformer);
            }
            parent.Accept(visitor);

            IList<IAstNode> childs = parent.ChildNodes;
            if (childs == null)
            {
                return;
            }

            foreach(IAstNode child in childs)
            {
                Accept(visitor, tranformers, child);
            }
        }
Ejemplo n.º 19
0
        public Value Generate(IAstNode ast, Action <CodeGeneratorException> codeGenerationErroHandler)
        {
            try
            {
                ast.Accept(this);

                if (AnonymousFunctions.Count > 0)
                {
                    var mainFunction = Module.AddFunction("main", Context.GetFunctionType(Context.VoidType));
                    var block        = mainFunction.AppendBasicBlock("entry");
                    var irBuilder    = new InstructionBuilder(block);
                    var printdFunc   = Module.AddFunction("printd", Context.GetFunctionType(Context.DoubleType, Context.DoubleType));
                    foreach (var anonFunc in AnonymousFunctions)
                    {
                        var value = irBuilder.Call(anonFunc);
                        irBuilder.Call(printdFunc, value);
                    }

                    irBuilder.Return( );

                    // Use always inline and Dead Code Elimination module passes to inline all of the
                    // anonymous functions. This effectively strips all the calls just generated for main()
                    // and inlines each of the anonymous functions directly into main, dropping the now
                    // unused original anonymous functions all while retaining all of the original source
                    // debug information locations.
                    var mpm = new ModulePassManager( )
                              .AddAlwaysInlinerPass( )
                              .AddGlobalDCEPass( );
                    mpm.Run(Module);
                    Module.DIBuilder.Finish( );
                }
            }
            catch (CodeGeneratorException ex) when(codeGenerationErroHandler != null)
            {
                codeGenerationErroHandler(ex);
            }

            return(null);
        }
Ejemplo n.º 20
0
        private void Accept(SqlAstVisitor visitor, IList <ITransformer> tranformers, IAstNode parent)
        {
            Debug.WriteLine(parent.Level + "\t" + parent.ParentNode + "\t" + parent + "\t" + parent.OriginalValue);

            foreach (ITransformer transformer in tranformers)
            {
                parent.Transform(transformer);
            }
            parent.Accept(visitor);

            IList <IAstNode> childs = parent.ChildNodes;

            if (childs == null)
            {
                return;
            }

            foreach (IAstNode child in childs)
            {
                Accept(visitor, tranformers, child);
            }
        }
Ejemplo n.º 21
0
        private bool IsEqual(IAstNode value1, IAstNode value2)
        {
            var v1 = value1.Accept(this);
            var v2 = value2.Accept(this);

            if (v1 == null && v2 == null)
            {
                return(true);
            }

            if (v1 == null || v2 == null)
            {
                return(false);
            }

            if (ValueHelper.IsNumeric(v1) && ValueHelper.IsNumeric(v2))
            {
                var d1 = Convert.ToDecimal(v1);
                var d2 = Convert.ToDecimal(v2);
                return(d1 == d2);
            }

            return(v1.Equals(v2));
        }
Ejemplo n.º 22
0
 public static void DumpAst(IAstNode ast)
 {
     ast.Accept(new DumpAstVisitor());
 }
Ejemplo n.º 23
0
 public static string ToString(IAstNode ast, bool showOffsets = false)
 {
     var dumper = new DumpAstVisitor(showOffsets);
     var code = ast.Accept(dumper);
     return code;
 }
Ejemplo n.º 24
0
 public IExpression Resolve(IAstNode node)
 {
     return node
         .Accept(new ConstantParsingVisitor())
         .Accept(new BindingVisitor(this))
         .Accept(new ConversionVisitor(this));
 }
Ejemplo n.º 25
0
 public IAstNode Eval(IAstNode ast)
 {
     ast.Accept(this);
     return(ast);
 }
Ejemplo n.º 26
0
 private void Visit(IAstNode node) => node.Accept(this);
Ejemplo n.º 27
0
 public void Accept(IVisitor visitor)
 {
     visitor.VisitEnter(this);
     Arg.Accept(visitor);
     visitor.VisitLeave(this);
 }
Ejemplo n.º 28
0
 internal static void Generate(IAstNode p, TextWriter streamWriter, string nspace)
 {
     p.Accept(new ProtoGenerator(streamWriter,nspace));
 }
Ejemplo n.º 29
0
 public void Resolve(IAstNode root, ResolveContext context)
 {
     root.Accept(this, context);
 }
Ejemplo n.º 30
0
 internal static void Generate(IAstNode p, TextWriter streamWriter, string nspace)
 {
     p.Accept(new ProtoGenerator(streamWriter, nspace));
 }
Ejemplo n.º 31
0
 public void Generate(IAstNode rootNode, TextWriter textWriter)
 {
     MdlGeneratorAstVisitor generatorAstVisitor = new MdlGeneratorAstVisitor(textWriter);
     rootNode.Accept(generatorAstVisitor);
 }
Ejemplo n.º 32
0
 protected internal virtual string Output2MySql(IAstNode node, string sql)
 {
     var sb = new StringBuilder(sql.Length);
     node.Accept(new MySqlOutputAstVisitor(sb));
     return sb.ToString();
 }