Ejemplo n.º 1
0
        public bool TryBuildExpression(ASTBuilder treeBuilder, FunctionToken functionToken, Stack <Token> stack, ParameterExpression p, out Expression output)
        {
            if (functionToken.ParameterCount == 0)
            {
                throw new XPressionException(functionToken.Source, "format requires at least one argument", functionToken.Position);
            }
            var args = new List <Expression>();

            for (var i = 0; i < functionToken.ParameterCount; i++)
            {
                args.Add(treeBuilder.PopExpression(stack, p));
            }

            args.Reverse(); // reverse stack order

            output =
                Expression.Call(
                    MemberTokens.String.FormatWithProvider,
                    Expression.Constant(CultureInfo.InvariantCulture),
                    args[0],
                    Expression.NewArrayInit(
                        typeof(object),
                        args.Skip(1).Select(e => e.Type == typeof(object) ? e : Expression.Convert(e, typeof(object)))
                        )
                    );
            return(true);
        }
Ejemplo n.º 2
0
        public void ScalarMulCSTtoAST()
        {
            string source = "double a = 2.5; tensor b[2][2] = { [80, 25.2], [19.6, 66] }; tensor c[2][2] = a * b;";

            AntlrInputStream  inputStream = new AntlrInputStream(new StringReader(source));
            Lexer             lexer       = new ML4DLexer(inputStream);
            CommonTokenStream tokenStream = new CommonTokenStream(lexer);
            ML4DParser        parser      = new ML4DParser(tokenStream);
            LinesContext      cst         = parser.lines();
            LinesNode         ast         = new ASTBuilder().VisitLines(cst);

            Assert.IsTrue(ast.lines.Count == 3);
            Assert.IsTrue(ast.lines[0] is VariableDCLNode);
            List <Node> children0 = ast.lines[0].GetChildren();

            Assert.IsTrue(children0.Count == 1 && children0[0] is DoubleNode);

            Assert.IsTrue(ast.lines[1] is TensorDCLNode);
            List <Node> children1 = ast.lines[1].GetChildren();

            Assert.IsTrue(children1.Count == 1 && children1[0] is TensorInitNode);

            Assert.IsTrue(ast.lines[2] is TensorDCLNode);
            List <Node> children2 = ast.lines[2].GetChildren();

            Assert.IsTrue(children2.Count == 1 && children2[0] is MultiplicationNode);

            List <Node> mulChilldren = children2[0].GetChildren();

            Assert.IsTrue(mulChilldren[0] is IDNode);
            Assert.IsTrue(mulChilldren[1] is IDNode);
        }
Ejemplo n.º 3
0
        void ValueNodeTextBox_LabelChanged(object sender, LabelEventArgs e)
        {
            NodeTextBox box = sender as NodeTextBox;

            if (box.Parent.CurrentNode == null)
            {
                return;
            }
            VariableNode node = box.Parent.CurrentNode.Tag as VariableNode;

            node.IsEditing = false;
            try
            {
                var         debugManager   = PluginMain.debugManager;
                var         flashInterface = debugManager.FlashInterface;
                IASTBuilder b   = new ASTBuilder(false);
                ValueExp    exp = b.parse(new java.io.StringReader(node.GetVariablePath()));
                var         ctx = new ExpressionContext(flashInterface.Session, flashInterface.GetFrames()[debugManager.CurrentFrame]);
                var         obj = exp.evaluate(ctx);
                node.Variable = (Variable)obj;
                if (!watchMode)
                {
                    PanelsHelper.watchUI.UpdateElements();
                }
                if (ValueChanged != null)
                {
                    ValueChanged(this, EventArgs.Empty);
                }
            }
            catch (Exception ex)
            {
                ErrorManager.ShowError(TextHelper.GetString("Error.Reevaluate"), ex);
            }
        }
Ejemplo n.º 4
0
        public void Init()
        {
            TestsTraceListener.Setup();

            builder = new ASTBuilder();
            grammar = new Grammar <Symbol>(
                NicodemGrammarProductions.StartSymbol(),
                NicodemGrammarProductions.MakeProductionsDictionaryForGrammarConstructor());
            dummyFrag      = new DummyFragment("dummy");
            dummyProd      = null;
            operatorSymbol = new UniversalSymbol[] {
                P.Operator0Expression,
                P.Operator1Expression,
                P.Operator2Expression,
                P.Operator3Expression,
                P.Operator4Expression,
                P.Operator5Expression,
                P.Operator6Expression,
                P.Operator7Expression,
                P.Operator8Expression,
                P.Operator9Expression,
                P.Operator10Expression,
                P.Operator11Expression,
                P.Operator12Expression,
                P.Operator13Expression,
                P.Operator14Expression,
                P.Operator15Expression,
                P.Operator16Expression,
                P.Operator17Expression,
                P.Operator18Expression,
                P.Operator19Expression
            };
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            var input = new AntlrFileStream("C:/Users/Leandro/Desktop/Compiler/CoolCompiler/input.cl");
            var lexer = new CoolLexer(input);

            /*var errors = new List<string>();
             * lexer.RemoveErrorListeners();*/


            var tokens = new CommonTokenStream(lexer);

            var parser = new CoolParser(tokens);

            var tree = parser.program();

            ASTBuilder astBuilder = new ASTBuilder();
            ASTNode    ast        = astBuilder.Visit(tree);

            Console.WriteLine( );


            /* var a = new Dictionary<int,int>();
             * a.Add(1,2);
             * a.Add(3, 4);
             * a.Add(5, 6);
             *
             * foreach (var x in ast.Attributes)
             * {
             *   Console.WriteLine( "{"+
             *   x.Key.ToString() + ":" + x.Value.ToString() + "}" );
             * }
             */

            Console.WriteLine(tree.ToStringTree(parser));
        }
Ejemplo n.º 6
0
        public bool TryBuildExpression(ASTBuilder treeBuilder, FunctionToken functionToken, Stack <Token> stack, ParameterExpression p, out Expression output)
        {
            var rightToken = stack.Pop(); // must be a constant string
            var target     = treeBuilder.PopExpression(stack, p);

            if (target.IsNullConstant())
            {
                output = Expression.Convert(Expression.Constant(null), typeof(bool?));
                return(true);
            }
            Type type;

            try
            {
                type = treeBuilder.Grammar.GetType(rightToken.Lexeme);
            }
            catch (Exception ex)
            {
                throw new XPressionException(functionToken.Source, "Invalid type: " + rightToken.Lexeme, rightToken.Position, ex);
            }
            if ((!target.Type.IsValueType || target.Type.IsNullable()) && type.IsValueType && !type.IsNullable())
            {
                type = typeof(Nullable <>).MakeGenericType(type);
            }
            output = Expression.TypeEqual(target, type);
            return(true);
        }
        public DecompileCache(ProjectFile pf)
        {
            Types = new AssetResolverTypes(pf);
            GlobalFunctionNames = new Dictionary <GMFunctionEntry, string>();
            if (pf.DataHandle.VersionInfo.IsNumberAtLeast(2, 3))
            {
                // Find all function names in global scripts
                GMChunkCODE code = pf.DataHandle.GetChunk <GMChunkCODE>();
                Parallel.ForEach(pf.DataHandle.GetChunk <GMChunkGLOB>().List, scr =>
                {
                    GMCode entry = code.List[scr];

                    // Find fragments
                    List <Fragment> fragments = Fragments.FindAndProcess(entry, false);

                    // Find blocks in the main fragment that come after another fagment
                    foreach (Block b in fragments[^ 1].Blocks.List)
                    {
                        if (b.AfterFragment && b.Instructions.Count > 2 &&
                            b.Instructions[0].Kind == GMCode.Bytecode.Instruction.Opcode.Push &&
                            b.Instructions[0].Type1 == GMCode.Bytecode.Instruction.DataType.Int32 &&
                            b.Instructions[0].Value == null)
                        {
                            string name = ASTBuilder.GetNameAfterFragment(b);
                            if (name != null)
                            {
                                GMFunctionEntry func = b.Instructions[0].Function.Target;
                                lock (GlobalFunctionNames)
                                    GlobalFunctionNames[func] = name;
                            }
                        }
                    }
                });
Ejemplo n.º 8
0
        private static CompileResult ParseFile(SourceProjectFile sourceFile, out AST ast)
        {
            // If not virtual, make sure the file exists
            if (!sourceFile.IsVirtual)
            {
                if (!File.Exists(sourceFile.Value))
                {
                    ast = null;
                    return(new CompileResult(false, $"Source file \"{sourceFile.Value}\" not found."));
                }
            }

            // Lex program
            Lexer lexer = new Lexer();

            LexToken[] tokens = sourceFile.IsVirtual ? lexer.Lex(sourceFile.Value) : lexer.LexFile(sourceFile.Value);

            // Build AST and return it
            ASTBuilder    builder = new ASTBuilder(tokens);
            ParsingResult result  = builder.Parse();

            if (result.Success)
            {
                ast = builder.Build();
                ast.SetSource(sourceFile);
                return(new CompileResult(true));
            }
            else
            {
                ast = null;
                return(new CompileResult(false));
            }
        }
Ejemplo n.º 9
0
        FromParseTreeToBackend <TSymbol> (IParseTree <TSymbol> parseTree) where TSymbol : ISymbol <TSymbol>
        {
            // build AST
            var ast = new ASTBuilder().BuildAST(parseTree);

            // apply visitors
            ast.Accept(new NameResolutionVisitor());
            ast.Accept(new TypeCheckVisitor());
            ast.FillInNestedUseFlag();
            ast.Accept(new FunctionLocalVisitor()); // create backend function objects
            // get all functions from AST
            IEnumerable <FunctionDefinitionNode> funcList = ast.GetAllFunctionDefinitions();

            // for each function -> extract controlflow (controlflow graph = expression graph)
            // each vertex of this graph holds (AST) ExpressionNode
            // during this phase - substitute nested function definition with empty BlockExpression
            IEnumerable <Tuple <FunctionDefinitionNode, ControlFlowGraph> > funcCFGs = funcList.Select(
                t => Tuple.Create(t, new ControlFlowExtractor().Extract(t.Body))
                );

            // for each function - extract side effects
            funcCFGs = funcCFGs.Select(
                t => Tuple.Create(t.Item1, new SideEffectExtractor().Extract(t.Item2))
                );

            // finally build and return list of functions (backend tree representation is inside function)
            return(funcCFGs.Select(
                       t => BackendBuilder.BuildBackendFunction(t.Item1, t.Item2)
                       ));
        }
Ejemplo n.º 10
0
        public void ExecuteRule(ASTBuilder builder)
        {
            var bottomScope = builder.BottomScope;

            if (bottomScope.Count < 1)
            {
                throw new InvalidOperationException("Can't make node family without at least a parent");
            }


            if (_parentIndex == 0)
            {
                var parentNode = bottomScope.Pop();

                var skipNum    = _count == 0 ? 0 : bottomScope.Count - _count;
                var childNodes = bottomScope.Reverse().Skip(Math.Max(0, skipNum)).ToList();
                if (skipNum == 0)
                {
                    bottomScope.Clear();
                }
                else
                {
                    for (var i = 0; i < _count; ++i)
                    {
                        bottomScope.Pop();
                    }
                }

                parentNode.MakeFamily(childNodes);
                bottomScope.Push(parentNode);
            }
            else
            {
                List <ASTNodeBase> childNodes = new List <ASTNodeBase>();

                int indexCtr = 0;
                int countCtr = 0;
                for (; countCtr < _count; countCtr++)
                {
                    if (indexCtr == _parentIndex)
                    {
                        break;
                    }

                    childNodes.Add(bottomScope.Pop());

                    indexCtr++;
                }

                var parentNode = bottomScope.Pop();

                for (int i = countCtr; i < _count; i++)
                {
                    childNodes.Add(bottomScope.Pop());
                }

                parentNode.MakeFamily(childNodes);
                bottomScope.Push(parentNode);
            }
        }
Ejemplo n.º 11
0
        public static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Please name the C# file that you would like to compile as a program argument.");
                return;
            }

            StreamReader sr = new StreamReader(args[0]);

            ICharStream stream = CharStreams.fromString(sr.ReadToEnd());

            CSharpLexer lexer = new CSharpLexer(stream);

            ITokenStream tokenStream = new CommonTokenStream(lexer);

            CSharpParser parser = new CSharpParser(tokenStream);

            parser.BuildParseTree = true;

            IParseTree tree = parser.compilation_unit();

            Console.WriteLine(tree.ToStringTree(parser));

            AST         ast         = new AST();
            SymbolTable symbolTable = new SymbolTable();

            ASTBuilder astBuilder = new ASTBuilder(ast, symbolTable);

            ParseTreeWalker.Default.Walk(astBuilder, tree);

            ast.Print();
        }
Ejemplo n.º 12
0
        /// <summary>
        /// From source code, generates the assembly via Roslyn and generates the AST from the assembly using the <see cref="IASTBuilder"/>.
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static ASTInfo BuildAST(this string source)
        {
            IAssemblyProxy assembly = new AsmlDasmlAssemblyLoader(source).Load();
            var builder = new ASTBuilder(assembly);

            return builder.Build();
        }
        /// <summary> We can get at files by name or module id, eventually we will put functions in here too</summary>

        public ExpressionCache(DebugCLI cli)
        {
            m_builder     = new ASTBuilder(true);         // allow fdb's "*x" and "x." indirection operators
            m_expressions = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
            m_props       = new IntProperties();
            m_cli         = cli;
        }
Ejemplo n.º 14
0
 public ShuntingYardParser(IGrammar grammar)
 {
     if (grammar == null)
     {
         throw new ArgumentNullException("grammar");
     }
     _grammar    = grammar;
     _astBuilder = new ASTBuilder(grammar);
 }
Ejemplo n.º 15
0
        // C# equivalents:
        // if(test,body) => return test ? body() : true;
        // if(test,trueBody,falseBody) => return test ? trueBody() : falseBody();
        // if parametercount==2 (falseBody is omitted), then the falseBody always
        // returns true (so then the trueBody MUST return a boolean value as well)
        public bool TryBuildExpression(ASTBuilder treeBuilder, FunctionToken functionToken, Stack <Token> stack, ParameterExpression p, out Expression output)
        {
            var ifFalse = functionToken.ParameterCount >= 3 ? treeBuilder.PopExpression(stack, p) : Expression.Constant(true);
            var ifTrue  = treeBuilder.PopExpression(stack, p);
            var test    = treeBuilder.PopExpression(stack, p);

            output = Expression.Condition(test.Convert <bool>(), ifTrue, ifFalse);
            return(true);
        }
Ejemplo n.º 16
0
 private string processExpr(string expr)
 {
     IASTBuilder builder = new ASTBuilder(true);
     ValueExp exp = builder.parse(new java.io.StringReader(expr));
     var ctx = new ExpressionContext(PluginMain.debugManager.FlashInterface.Session, PluginMain.debugManager.FlashInterface.GetFrames()[PluginMain.debugManager.CurrentFrame]);
     var obj = exp.evaluate(ctx);
     if (obj is Variable) return ctx.FormatValue(((Variable)obj).getValue());
     if (obj is Value) return ctx.FormatValue((Value)obj);
     return obj.toString();
 }
Ejemplo n.º 17
0
        public void ExecuteRule(ASTBuilder builder)
        {
            Builder = builder;
            PreviousPreviousLookahead = builder.PreviousPreviousLookahead;
            PreviousLookahead         = builder.PreviousLookahead;
            Lookahead = builder.Lookahead;
            var scope = builder.BottomScope;
            var node  = CreateNode();

            scope.Push(node);
        }
Ejemplo n.º 18
0
        private void Manager_OnMouseHover(ScintillaControl sci, Int32 position)
        {
            DebuggerManager debugManager   = PluginMain.debugManager;
            FlashInterface  flashInterface = debugManager.FlashInterface;

            if (!PluginBase.MainForm.EditorMenu.Visible && flashInterface != null &&
                flashInterface.isDebuggerStarted && flashInterface.isDebuggerSuspended)
            {
                if (debugManager.CurrentLocation != null &&
                    debugManager.CurrentLocation.File != null)
                {
                    String localPath = debugManager.GetLocalPath(debugManager.CurrentLocation.File);

                    if (localPath == null || localPath != PluginBase.MainForm.CurrentDocument.FileName)
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }

                Point     dataTipPoint = Control.MousePosition;
                Rectangle rect         = new Rectangle(m_ToolTip.Location, m_ToolTip.Size);

                if (m_ToolTip.Visible && rect.Contains(dataTipPoint))
                {
                    return;
                }

                position = sci.WordEndPosition(position, true);
                String leftword = GetWordAtPosition(sci, position);
                if (leftword != String.Empty)
                {
                    try
                    {
                        ASTBuilder builder = new ASTBuilder(true);

                        ValueExp          exp     = builder.parse(new System.IO.StringReader(leftword));
                        ExpressionContext context = new ExpressionContext(flashInterface.Session);

                        context.Depth = debugManager.CurrentFrame;

                        Object obj = exp.evaluate(context);

                        Show(dataTipPoint, (Variable)obj);
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// The main entry point of the application
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();

            ASTResult ast = new ASTBuilder().BuildAST(ConfigurationManager.AppSettings["inputFile"]);

            ast = MainTypeChecker.GetTypeCheckDiagnosis(ast);

            controller = new MainController(this, ast);
            controller.CreateMainUIBody();
        }
Ejemplo n.º 20
0
        private static Package CheckSemantics(PackageSyntax packageSyntax)
        {
            DeclarationNumberAssigner.AssignIn(packageSyntax.AllEntityDeclarations);

            // Resolve symbols for the entities
            EntitySymbolBuilder.BuildFor(packageSyntax);

            var stringSymbol = packageSyntax.SymbolTrees
                               .GlobalSymbols
                               .OfType <ObjectTypeSymbol>()
                               .SingleOrDefault(s => s.Name == "String");

            // Basic Analysis includes: Name Binding, Type Checking, Constant Folding
            BasicAnalyzer.Check(packageSyntax, stringSymbol);

            // If there are errors from the basic analysis phase, don't continue on
            packageSyntax.Diagnostics.ThrowIfFatalErrors();

#if DEBUG
            new SymbolValidator(packageSyntax.SymbolTree).Validate(packageSyntax.AllEntityDeclarations);
            new TypeFulfillmentValidator().Validate(packageSyntax.AllEntityDeclarations);
            new TypeKnownValidator().Validate(packageSyntax.AllEntityDeclarations);
            new ExpressionSemanticsValidator().Validate(packageSyntax.AllEntityDeclarations);
#endif

            var package = new ASTBuilder().BuildPackage(packageSyntax);

            // From this point forward, analysis focuses on executable declarations (i.e. invocables and field initializers)
            var executableDeclarations = package.AllDeclarations.OfType <IExecutableDeclaration>().ToFixedSet();

            ShadowChecker.Check(executableDeclarations, package.Diagnostics);

            DataFlowAnalysis.Check(DefiniteAssignmentAnalyzer.Instance, executableDeclarations, package.SymbolTree, package.Diagnostics);

            DataFlowAnalysis.Check(BindingMutabilityAnalyzer.Instance, executableDeclarations, package.SymbolTree, package.Diagnostics);

            DataFlowAnalysis.Check(UseOfMovedValueAnalyzer.Instance, executableDeclarations, package.SymbolTree, package.Diagnostics);

            // TODO use DataFlowAnalysis to check for unused variables and report use of variables starting with `_`

            // Compute variable liveness needed by reachability analyzer
            DataFlowAnalysis.Check(LivenessAnalyzer.Instance, executableDeclarations, package.SymbolTree, package.Diagnostics);

            ReachabilityAnalyzer.Analyze(executableDeclarations, package.SymbolTree, package.Diagnostics);

            // TODO remove live variables if SaveLivenessAnalysis is false

            return(package);
        }
Ejemplo n.º 21
0
        private string processExpr(string expr)
        {
            IASTBuilder builder = new ASTBuilder(true);
            ValueExp    exp     = builder.parse(new java.io.StringReader(expr));
            var         ctx     = new ExpressionContext(PluginMain.debugManager.FlashInterface.Session, PluginMain.debugManager.FlashInterface.GetFrames()[PluginMain.debugManager.CurrentFrame]);
            var         obj     = exp.evaluate(ctx);

            if (obj is Variable)
            {
                return(ctx.FormatValue(((Variable)obj).getValue()));
            }
            if (obj is Value)
            {
                return(ctx.FormatValue((Value)obj));
            }
            return(obj.toString());
        }
Ejemplo n.º 22
0
        /// <summary>
        /// From source code, generates the assembly via Roslyn and generates the AST from the assembly using the <see cref="IASTBuilder"/>.
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static SyntaxNode ExtractASTRoot(this string source)
        {
            IAssemblyProxy assembly = new AsmlDasmlAssemblyLoader(source, ScriptNamespaceAttributeHelper.AttributeSourceCode).Load();

            var builder = new ASTBuilder(assembly); // ScriptSharp Reflector
            var astInfo = builder.Build();

            // Getting the AST node
            var generatedTree = astInfo.Tree as CSharpSyntaxTree;

            if (generatedTree == null)
            {
                throw new InvalidOperationException("Invalid generated tree");
            }

            return(generatedTree.GetRoot());
        }
Ejemplo n.º 23
0
        public void TopologicalSortFail()
        {
            UnitTestParsing testParsing   = new UnitTestParsing();
            string          directoryFail = "../../../TestCases/Algorithm/fail/";
            DirectoryInfo   directory     = new DirectoryInfo(directoryFail);

            FileInfo[] files = directory.GetFiles();

            foreach (var file in files)
            {
                var errors = new List <string>();
                testParsing.ParsingFile(file.FullName);
                var         astBuilder = new ASTBuilder();
                ProgramNode program    = astBuilder.Visit(testParsing.tree) as ProgramNode;
                Algorithm.TopologicalSort(program.Classes, errors);
                Assert.IsTrue(errors.Count != 0, $"Not found cycles in class dependency in file {file.Name}");
            }
        }
Ejemplo n.º 24
0
        public void ASTBuilderSuccess()
        {
            UnitTestParsing testParsing      = new UnitTestParsing();
            string          directorySuccess = "../../../TestCases/Parsing/success/";
            DirectoryInfo   directory        = new DirectoryInfo(directorySuccess);

            FileInfo[] files = directory.GetFiles();

            foreach (var file in files)
            {
                testParsing.ParsingFile(file.FullName);
                var     astBuilder = new ASTBuilder();
                ASTNode root       = astBuilder.Visit(testParsing.tree);

                Assert.IsFalse(root is null, "AST no created. (root is null)");
                Assert.IsTrue(root is ProgramNode, $"AST created with big problems. (root is not a ProgramNode, root is {root})");
            }
        }
Ejemplo n.º 25
0
        private DataNode GetExpressionNode(string item)
        {
            DataNode node;

            try
            {
                if (!PluginMain.debugManager.FlashInterface.isDebuggerStarted || !PluginMain.debugManager.FlashInterface.isDebuggerSuspended)
                {
                    return(new ErrorNode(item, new Exception("")));
                }

                IASTBuilder builder = new ASTBuilder(false);
                ValueExp    exp     = builder.parse(new java.io.StringReader(item));
                var         ctx     = new ExpressionContext(PluginMain.debugManager.FlashInterface.Session, PluginMain.debugManager.FlashInterface.GetFrames()[PluginMain.debugManager.CurrentFrame]);
                var         obj     = exp.evaluate(ctx);
                if (obj is Variable)
                {
                    node = new VariableNode((Variable)obj)
                    {
                        HideClassId       = PluginMain.settingObject.HideClassIds,
                        HideFullClasspath = PluginMain.settingObject.HideFullClasspaths
                    };
                }
                else if (obj is Value)
                {
                    node = new ValueNode(item, (Value)obj)
                    {
                        HideClassId       = PluginMain.settingObject.HideClassIds,
                        HideFullClasspath = PluginMain.settingObject.HideFullClasspaths
                    };
                }
                else
                {
                    node = new ScalarNode(item, obj.toString());
                }
                node.Tag = item;
            }
            catch (Exception ex)
            {
                node = new ErrorNode(item, ex);
            }
            node.Text = item;
            return(node);
        }
Ejemplo n.º 26
0
        public void TestExpression(Dictionary <string, object> context, string expression, object expectedResult)
        {
            var questions = new List <Questionnaires.RunTime.Question>();

            foreach (var value in context)
            {
                questions.Add(ValueCreator.CreateQuestion(value.Key, (dynamic)value.Value));
            }

            var store = new QuestionStore(questions);

            var astFactory = new ASTBuilder(new Result());
            var AST        = astFactory.BuildExpression(expression);

            var evaluator = new Questionnaires.RunTime.ExpressionEvaluator(store);
            var result    = evaluator.Evaluate((IExpression)AST);

            Value.ValueTester.Test((dynamic)result, expectedResult);
        }
Ejemplo n.º 27
0
        public CompiledScript Compile(string source, Options options = Options.None,
                                      IDictionary <string, VariableValue> variables = null)
        {
            _rpnConverter.Reset();
            // Tokenization
            var tokens = _lexer.Analyze(source);

            // Parse
            _tokenParser.Parse(tokens);
            // Convert to RPN
            _rpnConverter.Convert(_tokenParser.Elements);
            // Build AST
            var rootNode = ASTBuilder.Build(_rpnConverter.Rpn, options, variables, _functions);

            // Optimize
            rootNode = rootNode.Optimize();
            // Create script wrapper
            return(new CompiledScript(rootNode));
        }
Ejemplo n.º 28
0
        private static ASTNode ParseInput(string inputPath)
        {
            //try
            {
                var input = new AntlrFileStream(inputPath);
                var lexer = new CoolLexer(input);

                var errors = new List <string>();
                lexer.RemoveErrorListeners();
                lexer.AddErrorListener(new LexerErrorListener(errors));

                var tokens = new CommonTokenStream(lexer);

                var parser = new CoolParser(tokens);

                parser.RemoveErrorListeners();
                parser.AddErrorListener(new ParserErrorListener(errors));

                IParseTree tree = parser.program();

                if (errors.Any())
                {
                    Console.WriteLine();
                    foreach (var item in errors)
                    {
                        Console.WriteLine(item);
                    }
                    return(null);
                }

                var     astBuilder = new ASTBuilder();
                ASTNode ast        = astBuilder.Visit(tree);
                return(ast);
            }

            /*catch (Exception e)
             * {
             *
             *  Console.WriteLine(e.Message);
             *  return null;
             * }*/
        }
Ejemplo n.º 29
0
        public bool TryBuildExpression(ASTBuilder treeBuilder, FunctionToken functionToken, Stack <Token> stack, ParameterExpression p, out Expression output)
        {
            var target = treeBuilder.PopExpression(stack, p);

            if (target.Type.EnsureNotNullable() != typeof(DateTimeOffset))
            {
                throw new XPressionException(functionToken.Source, "expected a datatimeoffset argument", functionToken.Position);
            }
            if (target.IsNullConstant())
            {
                output = Expression.Convert(Expression.Constant(null), typeof(int?));
                return(true);
            }
            if (target.Type.IsNullable())
            {
                output = Expression.Convert(target, target.Type.EnsureNotNullable());
                return(true);
            }
            output = Expression.MakeMemberAccess(Expression.MakeMemberAccess(target, MemberTokens.DateTimeOffset.Offset), MemberTokens.TimeSpan.TotalMinutes);
            return(true);
        }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            try
            {
                if (string.IsNullOrEmpty(args[0]) || string.IsNullOrEmpty(args[1]))
                {
                    throw new Exception(
                              "No run arguments were found. Missing arguments: <source filename> <target filename>");
                }

                string sourceFilename = args[0].Trim();
                string targetFileName = args[1].Trim();
                string text           = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + sourceFilename + ".ML4D");

                // ANTLR Lexer, Paser, and AST
                var inputStream = new AntlrInputStream(new StringReader(text));
                var lexer       = new ML4DLexer(inputStream);
                var tokenStream = new CommonTokenStream(lexer);
                var parser      = new ML4DParser(tokenStream);
                var cst         = parser.lines();
                var ast         = new ASTBuilder().VisitLines(cst);

                // Symbol Table and Type check
                SymbolTable symbolTable = new SymbolTable();
                symbolTable.OpenScope(); // Global scope
                var typesymbolVisitor = new TypeCheckSymbolTableVisitor(symbolTable);
                typesymbolVisitor.Visit(ast);

                // Code generation
                symbolTable.OnlyGlobalScope();
                CodeGeneration codeGen = new CodeGeneration(symbolTable);
                codeGen.Visit(ast);
                codeGen.WriteToFile(targetFileName);
                SymbolTable.Clear();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 31
0
		public void UpdateElements()
		{
			treeControl.Tree.BeginUpdate();
			treeControl.Nodes.Clear();
			foreach (String item in watches)
			{
				DataNode node = new DataNode(item); // todo, introduce new Node types.
				try
				{
                    IASTBuilder builder = new ASTBuilder(false);
                    ValueExp exp = builder.parse(new java.io.StringReader(item));
                    var ctx = new ExpressionContext(PluginMain.debugManager.FlashInterface.Session, PluginMain.debugManager.FlashInterface.Session.getFrames()[PluginMain.debugManager.CurrentFrame]);
                    var obj = exp.evaluate(ctx);
                    node = new DataNode((Variable)obj);
				}
				catch { }
				node.Text = item;
				treeControl.AddNode(node);
			}
			treeControl.Tree.EndUpdate();
			treeControl.Enabled = true;
		}
Ejemplo n.º 32
0
 public void UpdateElements()
 {
     treeControl.Tree.BeginUpdate();
     treeControl.Nodes.Clear();
     foreach (String item in watches)
     {
         DataNode node = new DataNode(item);                 // todo, introduce new Node types.
         try
         {
             IASTBuilder builder = new ASTBuilder(false);
             ValueExp    exp     = builder.parse(new java.io.StringReader(item));
             var         ctx     = new ExpressionContext(PluginMain.debugManager.FlashInterface.Session, PluginMain.debugManager.FlashInterface.Session.getFrames()[PluginMain.debugManager.CurrentFrame]);
             var         obj     = exp.evaluate(ctx);
             node = new DataNode((Variable)obj);
         }
         catch { }
         node.Text = item;
         treeControl.AddNode(node);
     }
     treeControl.Tree.EndUpdate();
     treeControl.Enabled = true;
 }
Ejemplo n.º 33
0
        private DataNode GetExpressionNode(string item)
        {
            DataNode node;
            try
            {
                if (!PluginMain.debugManager.FlashInterface.isDebuggerStarted || !PluginMain.debugManager.FlashInterface.isDebuggerSuspended )
                {
                    return new ErrorNode(item, new Exception(""));
                }

                IASTBuilder builder = new ASTBuilder(false);
                ValueExp exp = builder.parse(new java.io.StringReader(item));
                var ctx = new ExpressionContext(PluginMain.debugManager.FlashInterface.Session, PluginMain.debugManager.FlashInterface.GetFrames()[PluginMain.debugManager.CurrentFrame]);
                var obj = exp.evaluate(ctx);
                if (obj is Variable)
                {
                    node = new VariableNode((Variable)obj)
                    {
                        HideClassId = PluginMain.settingObject.HideClassIds,
                        HideFullClasspath = PluginMain.settingObject.HideFullClasspaths
                    };
                }
                else if (obj is Value)
                {
                    node = new ValueNode(item, (Value)obj)
                    {
                        HideClassId = PluginMain.settingObject.HideClassIds,
                        HideFullClasspath = PluginMain.settingObject.HideFullClasspaths
                    };
                }
                else node = new ScalarNode(item, obj.toString());
                node.Tag = item;
            }
            catch (Exception ex)
            {
                node = new ErrorNode(item, ex);
            }
            node.Text = item;
            return node;
        }
Ejemplo n.º 34
0
        void TreeExpanding(Object sender, TreeViewAdvEventArgs e)
        {
            if (e.Node.Index >= 0)
            {
                DataNode node = e.Node.Tag as DataNode;
                if (node.Nodes.Count == 0 && node.Variable != null)
                {
                    FlashInterface flashInterface = PluginMain.debugManager.FlashInterface;
                    List<DataNode> nodes = new List<DataNode>();
                    List<DataNode> inherited = new List<DataNode>();
                    List<DataNode> statics = new List<DataNode>();
                    int tmpLimit = node.ChildrenShowLimit;
                    foreach (Variable member in node.Variable.getValue().getMembers(flashInterface.Session))
                    {
                        DataNode memberNode = new DataNode(member);

                        if (member.isAttributeSet(VariableAttribute_.IS_STATIC))
                        {
                            statics.Add(memberNode);
                        }
                        else if (member.getLevel() > 0)
                        {
                            inherited.Add(memberNode);
                        }
                        else
                        {
                            nodes.Add(memberNode);
                        }
                    }
                    if (inherited.Count > 0)
                    {
                        DataNode inheritedNode = new DataNode("[inherited]");
                        inherited.Sort();
                        foreach (DataNode item in inherited)
                        {
                            inheritedNode.Nodes.Add(item);
                        }
                        node.Nodes.Add(inheritedNode);
                    }
                    if (statics.Count > 0)
                    {
                        DataNode staticNode = new DataNode("[static]");
                        statics.Sort();
                        foreach (DataNode item in statics)
                        {
                            staticNode.Nodes.Add(item);
                        }
                        node.Nodes.Add(staticNode);
                    }
                    //test children
                    foreach (String ch in node.Variable.getValue().getClassHierarchy(false))
                    {
                        if (ch.Equals("flash.display::DisplayObjectContainer"))
                        {
                            double numChildren = ((java.lang.Double)node.Variable.getValue().getMemberNamed(flashInterface.Session, "numChildren").getValue().getValueAsObject()).doubleValue();
                            DataNode childrenNode = new DataNode("[children]");
                            for (int i = 0; i < numChildren; i++)
                            {
                                try
                                {
                                    IASTBuilder b = new ASTBuilder(false);
                                    string cmd = GetVariablePath(node) + ".getChildAt(" + i + ")";
                                    ValueExp exp = b.parse(new java.io.StringReader(cmd));
                                    var ctx = new ExpressionContext(flashInterface.Session, flashInterface.GetFrames()[PluginMain.debugManager.CurrentFrame]);
                                    var obj = exp.evaluate(ctx);
                                    if (obj is flash.tools.debugger.concrete.DValue) obj = new flash.tools.debugger.concrete.DVariable("getChildAt(" + i + ")", (flash.tools.debugger.concrete.DValue)obj, ((flash.tools.debugger.concrete.DValue)obj).getIsolateId());
                                    DataNode childNode = new DataNode((Variable)obj);
                                    childNode.Text = "child_" + i;
                                    childrenNode.Nodes.Add(childNode);
                                }
                                catch (Exception) { }
                            }
                            node.Nodes.Add(childrenNode);
                        }
                        else if (ch.Equals("flash.events::EventDispatcher"))
                        {
                            Variable list = node.Variable.getValue().getMemberNamed(flashInterface.Session, "listeners");
                            var omg = list.getName();
                            /*
                            double numChildren = ((java.lang.Double)node.Variable.getValue().getMemberNamed(flashInterface.Session, "numChildren").getValue().getValueAsObject()).doubleValue();
                            DataNode childrenNode = new DataNode("[children]");
                            for (int i = 0; i < numChildren; i++)
                            {
                                try
                                {

                                    IASTBuilder b = new ASTBuilder(false);
                                    string cmd = GetVariablePath(node) + ".getChildAt(" + i + ")";
                                    ValueExp exp = b.parse(new java.io.StringReader(cmd));
                                    var ctx = new ExpressionContext(flashInterface.Session, flashInterface.Session.getFrames()[PluginMain.debugManager.CurrentFrame]);
                                    var obj = exp.evaluate(ctx);
                                    if (obj is flash.tools.debugger.concrete.DValue) obj = new flash.tools.debugger.concrete.DVariable("child_" + i, (flash.tools.debugger.concrete.DValue)obj);
                                    DataNode childNode = new DataNode((Variable)obj);
                                    childrenNode.Nodes.Add(childNode);
                                }
                                catch (Exception) { }
                            }
                            node.Nodes.Add(childrenNode);
                             * */
                        }
                    }
                    //test children
                    nodes.Sort();
                    _tree.BeginUpdate();
                    foreach (DataNode item in nodes)
                    {
                        if (0 == tmpLimit--) break;
                        node.Nodes.Add(item);
                    }
                    if (tmpLimit == -1)
                    {
                        DataNode moreNode = new DataNode("...");
                        node.Nodes.Add(moreNode);
                    }
                    _tree.EndUpdate();
                }
            }
        }
Ejemplo n.º 35
0
        public void ListChildItems(ValueNode node)
        {
            if (node != null && node.Nodes.Count == 0 && node.PlayerValue != null)
            {
                FlashInterface flashInterface = PluginMain.debugManager.FlashInterface;
                List<VariableNode> nodes = new List<VariableNode>();
                List<VariableNode> inherited = new List<VariableNode>();
                List<VariableNode> statics = new List<VariableNode>();
                int tmpLimit = node.ChildrenShowLimit;
                foreach (Variable member in node.PlayerValue.getMembers(flashInterface.Session))
                {
                    VariableNode memberNode = new VariableNode(member)
                    {
                        HideClassId = PluginMain.settingObject.HideClassIds,
                        HideFullClasspath = PluginMain.settingObject.HideFullClasspaths
                    };
                    if (member.isAttributeSet(VariableAttribute_.IS_STATIC))
                    {
                        statics.Add(memberNode);
                    }
                    else if (member.getLevel() > 0)
                    {
                        inherited.Add(memberNode);
                    }
                    else nodes.Add(memberNode);
                }
                // inherited vars
                if (inherited.Count > 0)
                {
                    if (PluginMain.settingObject.CombineInherited)
                    {
                        // list inherited alongside main class members
                        foreach (DataNode item in inherited)
                        {
                            node.Nodes.Add(item);
                        }

                    }
                    else
                    {
                        // list inherited in a [inherited] group
                        ValueNode inheritedNode = new ValueNode("[inherited]");
                        inherited.Sort();
                        foreach (DataNode item in inherited)
                        {
                            inheritedNode.Nodes.Add(item);
                        }
                        node.Nodes.Add(inheritedNode);

                    }
                }
                // static vars
                if (!PluginMain.settingObject.HideStaticMembers && statics.Count > 0)
                {
                    DataNode staticNode = new ValueNode("[static]");
                    statics.Sort();
                    foreach (DataNode item in statics)
                    {
                        staticNode.Nodes.Add(item);
                    }
                    node.Nodes.Add(staticNode);
                }
                // test children
                foreach (String ch in node.PlayerValue.getClassHierarchy(false))
                {
                    if (ch.Equals("flash.display::DisplayObjectContainer"))
                    {
                        double numChildren = ((java.lang.Double)node.PlayerValue.getMemberNamed(flashInterface.Session, "numChildren").getValue().getValueAsObject()).doubleValue();
                        DataNode childrenNode = new ValueNode("[children]");
                        for (int i = 0; i < numChildren; i++)
                        {
                            try
                            {
                                IASTBuilder b = new ASTBuilder(false);
                                string cmd = node.GetVariablePath() + ".getChildAt(" + i + ")";
                                ValueExp exp = b.parse(new java.io.StringReader(cmd));
                                var ctx = new ExpressionContext(flashInterface.Session, flashInterface.GetFrames()[PluginMain.debugManager.CurrentFrame]);
                                var obj = exp.evaluate(ctx);
                                if (obj is flash.tools.debugger.concrete.DValue) obj = new flash.tools.debugger.concrete.DVariable("getChildAt(" + i + ")", (flash.tools.debugger.concrete.DValue)obj, ((flash.tools.debugger.concrete.DValue)obj).getIsolateId());
                                DataNode childNode = new VariableNode((Variable) obj)
                                {
                                    HideClassId = PluginMain.settingObject.HideClassIds,
                                    HideFullClasspath = PluginMain.settingObject.HideFullClasspaths
                                };
                                childNode.Text = "child_" + i;
                                childrenNode.Nodes.Add(childNode);
                            }
                            catch (Exception) { }
                        }
                        node.Nodes.Add(childrenNode);
                    }
                    else if (ch.Equals("flash.events::EventDispatcher"))
                    {
                        Variable list = node.PlayerValue.getMemberNamed(flashInterface.Session, "listeners");
                        var omg = list.getName();
                        /*
                        double numChildren = ((java.lang.Double)node.Variable.getValue().getMemberNamed(flashInterface.Session, "numChildren").getValue().getValueAsObject()).doubleValue();
                        DataNode childrenNode = new DataNode("[children]");
                        for (int i = 0; i < numChildren; i++)
                        {
                            try
                            {

                                IASTBuilder b = new ASTBuilder(false);
                                string cmd = GetVariablePath(node) + ".getChildAt(" + i + ")";
                                ValueExp exp = b.parse(new java.io.StringReader(cmd));
                                var ctx = new ExpressionContext(flashInterface.Session, flashInterface.Session.getFrames()[PluginMain.debugManager.CurrentFrame]);
                                var obj = exp.evaluate(ctx);
                                if (obj is flash.tools.debugger.concrete.DValue) obj = new flash.tools.debugger.concrete.DVariable("child_" + i, (flash.tools.debugger.concrete.DValue)obj);
                                DataNode childNode = new DataNode((Variable)obj);
                                childrenNode.Nodes.Add(childNode);
                            }
                            catch (Exception) { }
                        }
                        node.Nodes.Add(childrenNode);
                        */
                    }
                }
                //test children
                nodes.Sort();
                // add child items
                _tree.BeginUpdate();
                foreach (DataNode item in nodes)
                {
                    if (0 == tmpLimit--) break;
                    node.Nodes.Add(item);
                }
                if (tmpLimit == -1)
                {
                    DataNode moreNode = new ContinuedDataNode();
                    node.Nodes.Add(moreNode);
                }
                _tree.EndUpdate();
            }
        }
Ejemplo n.º 36
0
 void ValueNodeTextBox_LabelChanged(object sender, LabelEventArgs e)
 {
     NodeTextBox box = sender as NodeTextBox;
     if (box.Parent.CurrentNode == null) return;
     VariableNode node = box.Parent.CurrentNode.Tag as VariableNode;
     node.IsEditing = false;
     try
     {
         var debugManager = PluginMain.debugManager;
         var flashInterface = debugManager.FlashInterface;
         IASTBuilder b = new ASTBuilder(false);
         ValueExp exp = b.parse(new java.io.StringReader(node.GetVariablePath()));
         var ctx = new ExpressionContext(flashInterface.Session, flashInterface.GetFrames()[debugManager.CurrentFrame]);
         var obj = exp.evaluate(ctx);
         node.Variable = (Variable)obj;
         if (!watchMode) PanelsHelper.watchUI.UpdateElements();
         if (ValueChanged != null) ValueChanged(this, EventArgs.Empty);
     }
     catch (Exception ex)
     {
         ErrorManager.ShowError(TextHelper.GetString("Error.Reevaluate"), ex);
     }
 }
Ejemplo n.º 37
0
        static void Main(string[] args)
        {
            var rootNode = getRoot(System.IO.File.ReadAllText("test.t"), new TSharpCompiler.TuringGrammarBroken());
            if (rootNode == null)
                Console.WriteLine("Parsing failed");
            else
            {
                var file = new StreamWriter("parseTree.txt");
                dispTree(rootNode, 0, file);
                file.Close();
                //Console.WriteLine(Compile(rootNode));
                //CodeGen codeGen = new CodeGen(rootNode, "test.exe");
                ASTBuilder builder = new ASTBuilder();
                var program = builder.BuildAST(rootNode) as AST.UnitNode;
                program.CreateProgram("test.exe");

                Console.WriteLine("done");
            }

            /* This can be interesting, it allows to embed the assembly within the existing assembly, useful for an editor
            DynamicMethod meth = new DynamicMethod("", null, null);
            ILGenerator il = meth.GetILGenerator();
            il.EmitWriteLine("Hello, World!");

            il.Emit(OpCodes.Ret);

            Test1 t1 = (Test1)meth.CreateDelegate(typeof(Test1));
            t1();
            */
            Console.ReadKey();
        }
Ejemplo n.º 38
0
 private void Manager_OnMouseHover(ScintillaControl sci, Int32 position)
 {
     DebuggerManager debugManager = PluginMain.debugManager;
     FlashInterface flashInterface = debugManager.FlashInterface;
     if (!PluginBase.MainForm.EditorMenu.Visible && flashInterface != null && flashInterface.isDebuggerStarted && flashInterface.isDebuggerSuspended)
     {
         if (debugManager.CurrentLocation != null && debugManager.CurrentLocation.getFile() != null)
         {
             String localPath = debugManager.GetLocalPath(debugManager.CurrentLocation.getFile());
             if (localPath == null || localPath != PluginBase.MainForm.CurrentDocument.FileName)
             {
                 return;
             }
         }
         else return;
         Point dataTipPoint = Control.MousePosition;
         Rectangle rect = new Rectangle(m_ToolTip.Location, m_ToolTip.Size);
         if (m_ToolTip.Visible && rect.Contains(dataTipPoint))
         {
             return;
         }
         position = sci.WordEndPosition(position, true);
         String leftword = GetWordAtPosition(sci, position);
         if (leftword != String.Empty)
         {
             try
             {
                 IASTBuilder b = new ASTBuilder(false);
                 ValueExp exp = b.parse(new java.io.StringReader(leftword));
                 var ctx = new ExpressionContext(flashInterface.Session, flashInterface.GetFrames()[debugManager.CurrentFrame]);
                 var obj = exp.evaluate(ctx);
                 if (obj as Variable != null)
                 {
                     Show(dataTipPoint, (Variable)obj, leftword);
                 }
             }
             catch (Exception){}
         }
     }
 }
        /// <summary>
        /// 编译FireML
        /// </summary>
        public FireMLRoot CompileFireML()
        {
            FireMLRoot root = new FireMLRoot();

            #region 读取Asset
            AssetBuilder assetBuilder = new AssetBuilder(this);
            assetBuilder.Build(assetFiles, root);
            #endregion

            #region 构造AST
            ASTBuilder astBuilder = new ASTBuilder(this);
            astBuilder.Build(plotFiles, root);
            #endregion

            #region AST合法性检查
            ASTChecker astChecker = new ASTChecker(this);
            astChecker.Check(root);
            #endregion

            #region 生成ID号
            IDGenerator idGenerator = new IDGenerator();
            idGenerator.Generate(root);
            #endregion

            #region 资源存在性检查
            //ContentChecker contentChecker = new ContentChecker(this);
            //contentChecker.Check(root);
            #endregion

            if (errorList.Count > 0)
                return null;
            else
                return root;
        }