Exemplo n.º 1
0
        public static bool IsConstant(Ast ast, out object constantValue, bool forAttribute = false, bool forRequires = false)
        {
            try
            {
                if ((bool)ast.Accept(new IsConstantValueVisitor { CheckingAttributeArgument = forAttribute, CheckingRequiresArgument = forRequires }))
                {
                    Ast parent = ast.Parent;
                    while (parent != null)
                    {
                        if (parent is DataStatementAst)
                        {
                            break;
                        }
                        parent = parent.Parent;
                    }

                    if (parent == null)
                    {
                        constantValue = ast.Accept(new ConstantValueVisitor { AttributeArgument = forAttribute, RequiresArgument = forRequires });
                        return true;
                    }
                }
            }
            catch (Exception e)
            {
                // If we get an exception, ignore it and assume the expression isn't constant.
                // This can happen, e.g. if a cast is invalid:
                //     [int]"zed"
                CommandProcessorBase.CheckForSevereException(e);
            }

            constantValue = null;
            return false;
        }
Exemplo n.º 2
0
        public static string ToString(Ast ast)
        {
            var printer = new PrettyPrinter();

            ast.Accept(printer);
            return(printer.ToString());
        }
Exemplo n.º 3
0
        public void TestObjectify()
        {
            Parser p = new Parser();

            byte[] ser     = File.ReadAllBytes("testserpent.utf8.bin");
            Ast    ast     = p.Parse(ser);
            var    visitor = new ObjectifyVisitor();

            ast.Accept(visitor);
            object thing = visitor.GetObject();

            IDictionary dict = (IDictionary)thing;

            Assert.AreEqual(11, dict.Count);
            IList <object> list = dict["numbers"] as IList <object>;

            Assert.AreEqual(4, list.Count);
            Assert.AreEqual(999.1234, list[1]);
            Assert.AreEqual(new ComplexNumber(-3, 8), list[3]);
            string euro = dict["unicode"] as string;

            Assert.AreEqual("\u20ac", euro);
            IDictionary exc = (IDictionary)dict["exc"];

            object[] args = (object[])exc["args"];
            Assert.AreEqual("fault", args[0]);
            Assert.AreEqual("ZeroDivisionError", exc["__class__"]);
        }
Exemplo n.º 4
0
        public void TestObjectifyDictToClass()
        {
            Parser p = new Parser();

            byte[] ser = File.ReadAllBytes("testserpent.utf8.bin");
            Ast    ast = p.Parse(ser);

            var visitor = new ObjectifyVisitor(ZerodivisionFromDict);

            ast.Accept(visitor);
            object thing = visitor.GetObject();

            IDictionary dict = (IDictionary)thing;

            Assert.AreEqual(11, dict.Count);
            DivideByZeroException ex = (DivideByZeroException)dict["exc"];

            Assert.AreEqual("fault", ex.Message);

            thing = ast.GetData(ZerodivisionFromDict);
            dict  = (IDictionary)thing;
            Assert.AreEqual(11, dict.Count);
            ex = (DivideByZeroException)dict["exc"];
            Assert.AreEqual("fault", ex.Message);
        }
        internal bool IsAstSafe(Ast ast)
        {
            if ((bool)ast.Accept(this) && _visitCount < MaxVisitCount)
            {
                return(true);
            }

            return(false);
        }
Exemplo n.º 6
0
 public static bool IsAstSafe(Ast ast, GetSafeValueVisitor.SafeValueContext safeValueContext)
 {
     IsSafeValueVisitor visitor = new IsSafeValueVisitor(safeValueContext);
     if ((bool)ast.Accept(visitor) && visitor._visitCount < MaxVisitCount)
     {
         return true;
     }
     return false;
 }
Exemplo n.º 7
0
        public void TestComments()
        {
            Parser p = new Parser();

            Ast ast     = p.Parse("[ 1, 2 ]");          // no header whatsoever
            var visitor = new ObjectifyVisitor();

            ast.Accept(visitor);
            Object obj = visitor.GetObject();

            Assert.AreEqual(new int[] { 1, 2 }, obj);

            ast     = p.Parse(@"# serpent utf-8 python2.7
[ 1, 2,
   # some comments here
   3, 4]    # more here
# and here.
");
            visitor = new ObjectifyVisitor();
            ast.Accept(visitor);
            obj = visitor.GetObject();
            Assert.AreEqual(new int[] { 1, 2, 3, 4 }, obj);
        }
Exemplo n.º 8
0
 public static bool IsConstant(Ast ast, out object constantValue, bool forAttribute = false, bool forRequires = false)
 {
     try
     {
         IsConstantValueVisitor visitor2 = new IsConstantValueVisitor {
             CheckingAttributeArgument = forAttribute,
             CheckingRequiresArgument = forRequires
         };
         if ((bool) ast.Accept(visitor2))
         {
             Ast parent = ast.Parent;
             while (parent != null)
             {
                 if (parent is DataStatementAst)
                 {
                     break;
                 }
                 parent = parent.Parent;
             }
             if (parent == null)
             {
                 ConstantValueVisitor visitor = new ConstantValueVisitor {
                     AttributeArgument = forAttribute,
                     RequiresArgument = forRequires
                 };
                 constantValue = ast.Accept(visitor);
                 return true;
             }
         }
     }
     catch (Exception exception)
     {
         CommandProcessorBase.CheckForSevereException(exception);
     }
     constantValue = null;
     return false;
 }
        public static object GetSafeValue(Ast ast, ExecutionContext context, SafeValueContext safeValueContext)
        {
            s_context = context;
            if (IsSafeValueVisitor.IsAstSafe(ast, safeValueContext))
            {
                return(ast.Accept(new GetSafeValueVisitor()));
            }

            if (safeValueContext == SafeValueContext.ModuleAnalysis)
            {
                return(null);
            }

            throw PSTraceSource.NewArgumentException("ast");
        }
Exemplo n.º 10
0
 private static object CompileAndInvoke(Ast ast)
 {
     object obj2;
     try
     {
         Compiler visitor = new Compiler {
             CompilingConstantExpression = true
         };
         obj2 = Expression.Lambda((Expression) ast.Accept(visitor), new ParameterExpression[0]).Compile().DynamicInvoke(new object[0]);
     }
     catch (TargetInvocationException exception)
     {
         throw exception.InnerException;
     }
     return obj2;
 }
Exemplo n.º 11
0
        public CompileResult Compile(Ast ast)
        {
            Reset();
            ast.Accept(this);

            //chunk.WriteOpCode(OpCode.RETURN);
            //chunk.WriteOpCode(OpCode.CONSTANT);
            //chunk.WriteWord(chunk.AddConstant(new Value(1)));
            //chunk.WriteOpCode(OpCode.NEGATE);
            //chunk.WriteOpCode(OpCode.CONSTANT);
            //chunk.WriteWord(chunk.AddConstant(new Value(123)));
            //chunk.WriteOpCode(OpCode.DIV);
            //chunk.WriteOpCode(OpCode.CONSTANT);
            //chunk.WriteWord(chunk.AddConstant(new Value(1)));
            //chunk.WriteOpCode(OpCode.ADD);
            //chunk.WriteOpCode(OpCode.CONSTANT);
            //chunk.WriteWord(chunk.AddConstant(new Value(0.1)));
            //chunk.WriteOpCode(OpCode.DIV);
            //ChunkDebug.Dump("Chunk Dump:", chunk);

            return(new CompileResult(success, chunk, errors));
        }
Exemplo n.º 12
0
        public void ExampleUsage()
        {
            Console.WriteLine("using serpent library version {0}", LibraryVersion.Version);

            var data = new Dictionary <string, object> {
                { "tuple", new [] { 1, 2, 3 } },
                { "date", DateTime.Now },
                { "set", new HashSet <string> {
                      "a", "b", "c"
                  } },
                { "class", new SampleClass
                  {
                      Name = "Sally",
                      Age  = 26
                  } }
            };

            // serialize data structure to bytes
            Serializer serpent = new Serializer(true);
            var        ser     = serpent.Serialize(data);

            // print it on the screen, but normally you'd store byte bytes in a file or transfer them across a network connection
            Console.WriteLine("Serialized:");
            Console.WriteLine(Encoding.UTF8.GetString(ser));

            // parse the serialized bytes back into an abstract syntax tree of the datastructure
            Parser parser = new Parser();
            Ast    ast    = parser.Parse(ser);

            Console.WriteLine("\nParsed AST:");
            Console.WriteLine(ast.Root.ToString());

            // print debug representation
            DebugVisitor dv = new DebugVisitor();

            ast.Accept(dv);
            Console.WriteLine("DEBUG string representation:");
            Console.WriteLine(dv.ToString());

            // turn the Ast into regular .net objects
            var dict = (IDictionary)ast.GetData();

            // You can get the data out of the Ast manually as well, by using the supplied visitor:
            // var visitor = new ObjectifyVisitor();
            // ast.Accept(visitor);
            // var dict = (IDictionary) visitor.GetObject();

            // print the results
            Console.WriteLine("PARSED results:");
            Console.Write("tuple items: ");
            var tuple = (object[])dict["tuple"];

            Console.WriteLine(string.Join(", ", tuple.Select(e => e.ToString()).ToArray()));
            Console.WriteLine("date: {0}", dict["date"]);
            Console.Write("set items: ");
            var set = (HashSet <object>)dict["set"];

            Console.WriteLine(string.Join(", ", set.Select(e => e.ToString()).ToArray()));
            Console.WriteLine("class attributes:");
            var clazz = (IDictionary)dict["class"];                     // custom classes are serialized as dicts

            Console.WriteLine("  type: {0}", clazz["__class__"]);
            Console.WriteLine("  name: {0}", clazz["name"]);
            Console.WriteLine("  age: {0}", clazz["age"]);

            Console.WriteLine("");

            // parse and print the example file
            ser = File.ReadAllBytes("testserpent.utf8.bin");
            ast = parser.Parse(ser);
            dv  = new DebugVisitor();
            ast.Accept(dv);
            Console.WriteLine("DEBUG string representation of the test file:");
            Console.WriteLine(dv.ToString());
        }
Exemplo n.º 13
0
 public void PostVisit(Ast ast)
 {
     ast.Accept(_symbolResolvePostActionVisitor);
 }
Exemplo n.º 14
0
 private void GenerateWhileLoop(string loopLabel, Action generateCondition, Action generateLoopBody, Ast continueAction = null)
 {
     Block next = new Block();
     if (continueAction != null)
     {
         Block block2 = new Block();
         this._currentBlock.FlowsTo(block2);
         this._currentBlock = next;
         continueAction.Accept(this);
         this._currentBlock.FlowsTo(block2);
         this._currentBlock = block2;
     }
     else
     {
         this._currentBlock.FlowsTo(next);
         this._currentBlock = next;
     }
     Block block3 = new Block();
     Block block4 = new Block();
     if (generateCondition != null)
     {
         generateCondition();
         this._currentBlock.FlowsTo(block4);
     }
     this._loopTargets.Add(new LoopGotoTargets(loopLabel ?? "", block4, next));
     this._currentBlock.FlowsTo(block3);
     this._currentBlock = block3;
     generateLoopBody();
     this._currentBlock.FlowsTo(next);
     this._currentBlock = block4;
     this._loopTargets.RemoveAt(this._loopTargets.Count - 1);
 }
Exemplo n.º 15
0
 private bool IsValidAttributeArgument(Ast ast, IsConstantValueVisitor visitor)
 {
     return (bool)ast.Accept(visitor);
 }
Exemplo n.º 16
0
 internal Expression Compile(Ast ast)
 {
     return (Expression)ast.Accept(this);
 }
Exemplo n.º 17
0
 public void Print()
 {
     Ast.Accept(this);
 }
Exemplo n.º 18
0
        public static object GetSafeValue(Ast ast, ExecutionContext context, SafeValueContext safeValueContext)
        {
            s_context = context;
            if (IsSafeValueVisitor.IsAstSafe(ast, safeValueContext))
            {
                return ast.Accept(new GetSafeValueVisitor());
            }

            if (safeValueContext == SafeValueContext.ModuleAnalysis)
            {
                return null;
            }
            throw PSTraceSource.NewArgumentException("ast");
        }
Exemplo n.º 19
0
 private static object CompileAndInvoke(Ast ast)
 {
     try
     {
         var compiler = new Compiler { CompilingConstantExpression = true };
         return Expression.Lambda((Expression)ast.Accept(compiler)).Compile().DynamicInvoke();
     }
     catch (TargetInvocationException tie)
     {
         throw tie.InnerException;
     }
 }
Exemplo n.º 20
0
 private void CheckIsConstant(Ast ast, string msg)
 {
     Diagnostics.Assert(
         (bool)ast.Accept(new IsConstantValueVisitor { CheckingAttributeArgument = this.AttributeArgument, CheckingRequiresArgument = RequiresArgument }), msg);
 }
Exemplo n.º 21
0
 private bool IsValidAttributeArgument(Ast ast)
 {
     var obj = ast.Accept(this._isConstantValueVisitor);
     if (obj is bool) return (bool)obj;
     return false;
 }
Exemplo n.º 22
0
        private void GenerateWhileLoop(string loopLabel,
                                       Action generateCondition,
                                       Action generateLoopBody,
                                       Ast continueAction = null)
        {
            // We model the flow graph like this (if continueAction is null, the first part is slightly different):
            //    goto L
            //    :ContinueTarget
            //        continueAction
            //    :L
            //    if (condition)
            //    {
            //        loop body
            //        // break -> goto BreakTarget
            //        // continue -> goto ContinueTarget
            //        goto ContinueTarget
            //    }
            //    :BreakTarget

            var continueBlock = new Block();

            if (continueAction != null)
            {
                var blockAfterContinue = new Block();

                // Represent the goto over the condition before the first iteration.
                _currentBlock.FlowsTo(blockAfterContinue);

                _currentBlock = continueBlock;
                continueAction.Accept(this);

                _currentBlock.FlowsTo(blockAfterContinue);
                _currentBlock = blockAfterContinue;
            }
            else
            {
                _currentBlock.FlowsTo(continueBlock);
                _currentBlock = continueBlock;
            }

            var bodyBlock = new Block();
            var breakBlock = new Block();

            // Condition can be null from an uncommon for loop: for() {}
            if (generateCondition != null)
            {
                generateCondition();
                _currentBlock.FlowsTo(breakBlock);
            }

            _loopTargets.Add(new LoopGotoTargets(loopLabel ?? "", breakBlock, continueBlock));
            _currentBlock.FlowsTo(bodyBlock);
            _currentBlock = bodyBlock;
            generateLoopBody();
            _currentBlock.FlowsTo(continueBlock);

            _currentBlock = breakBlock;

            _loopTargets.RemoveAt(_loopTargets.Count - 1);
        }
Exemplo n.º 23
0
 public Tacs Generate(Ast ast)
 {
     ast.Accept(this);
     return(tacs);
 }