Beispiel #1
0
        public static void Main(string[] args)
        {
            //Machine machine = new Machine ();

            //foreach ( var arg in args )
            //    machine.ExecuteFile ( arg );

            //machine.ExecuteFile ( @"/Users/Kanbaru/OneDrive/文档/CocoR/CocoRuby/test_0.rb" );

            // foreach ( var path in System.IO.Directory.GetFiles ( @"/Users/Kanbaru/OneDrive/文档/RubySharp/Src/RubySharp.Core.Tests/MachineFiles" ) ) {
            foreach (var path in System.IO.Directory.GetFiles(@"D:/OneDrive/文档/RubySharp/Src/RubySharp.Core.Tests/MachineFiles"))
            {
                if (System.IO.Path.GetExtension(path) != ".rb")
                {
                    continue;
                }

                if (!path.EndsWith("main.rb"))
                {
                    continue;
                }

                Console.WriteLine(path);

                AstParser aparser = new AstParser(System.IO.File.ReadAllText(path));
                aparser.filepath = path;
//				for ( var command = aparser.ParseCommand (); command != null; command = aparser.ParseCommand () ) {
//					Console.WriteLine ( command );
//				}
                var vm = new VM();

                UserDataUtility.RegAssembly(vm, typeof(Microsoft.Xna.Framework.Game).Assembly);
                // UserDataUtility.RegCustomClass ( vm, typeof ( Microsoft.Xna.Framework.Vector2 ) );
                // UserDataUtility.RegCustomClass ( vm, typeof ( Microsoft.Xna.Framework.Curve ) );

                vm.Evaluate(aparser.Parse());

                Console.WriteLine();
            }



            //if ( args.Length == 0 ) {
            //    Console.WriteLine ( "rush 0.0.1-alpha-alpha-alpha-realpha ;-)" );

            //    Parser parser = new Parser ( Console.In );

            //    while ( true )
            //        try {
            //            IExpression expr   = parser.ParseCommand ();
            //            var         result = expr.Evaluate ( machine.RootContext );
            //            var         text   = result == null ? "nil" : result.ToString ();
            //            Console.WriteLine ( string.Format ( "=> {0}", text ) );
            //        }
            //        catch ( Exception ex ) {
            //            Console.WriteLine ( ex.Message );
            //            Console.WriteLine ( ex.StackTrace );
            //        }
            //}
        }
        public void TestCases(ExpressionReductionTestCase testCase)
        {
            var tokens = Lexer.Process(DemoUtility.OperatorMap, testCase.Infix);
            var ex     = Assert.Throws <ExpressionReductionException>(() => AstParser.Parse(DemoUtility.OperatorMap, tokens));

            Assert.AreEqual(testCase.ExpectedRemaining, ex.RemainingValues);
        }
Beispiel #3
0
        public void TestCases(MissingTokenTestCase testCase)
        {
            var tokens = Lexer.Process(DemoUtility.OperatorMap, testCase.Infix);
            var ex     = Assert.Throws <MissingTokenException>(() => AstParser.Parse(DemoUtility.OperatorMap, tokens));

            Assert.AreEqual(testCase.ExpectedType, ex.Type);
        }
Beispiel #4
0
        public override Value Evaluate(RubyContext context)
        {
#if DEBUG
            context.VM.CurrentEvalNode = this;
#endif

            var result = new DefinedFunction(body, args, context);
            var fname  = AstParser.GetNamePathFinalName(name);
            if (fname == VM.INITIALIZE)
            {
                result.isConstructor = true;
            }

            if (context.Module != null)
            {
                context.Module.SetInstanceMethod(fname, result);
            }
            else
            {
                // context.Self.c.SetInstanceMethod ( AstParser.GetNamePathFinalName ( name ), result );
                (( RClass )context.Self).SetInstanceMethod(fname, result);
            }

            return(null);
        }
Beispiel #5
0
        private Ast ParseString(string source)
        {
            var tks = _tokenizer.Parse(source);
            var ts  = new TokenStream(tks);

            return(AstParser.Parse(ts));
        }
Beispiel #6
0
        public void TestCases(PrecedenceTestCase testCase)
        {
            var tokens = Lexer.Process(s_testOperatorMap, testCase.Infix);

            var node = AstParser.Parse(s_testOperatorMap, tokens);

            Assert.AreEqual(testCase.ExpectedNodeString, node.ToString());
        }
        public InteractionResult SetInteractionResult(string raw)
        {
            var resultingAst = new AstParser(new FunctionDeclarationsFactory()).Parse(raw);
            var result       = ParseInteractionResult((ListCell)ListParser.ParseAsList(resultingAst));

            _state = result.State;
            return(result);
        }
Beispiel #8
0
 public bool TryParse(AstParser <T> parser, AstNode node, out T result)
 {
     result = default;
     if (node is not AstGroup group)
     {
         return(false);
     }
     return(parser.TryParse(group.Content, out result));
 }
        public void TestCases(ArgumentMismatchTestCase testCase)
        {
            var tokens = Lexer.Process(DemoUtility.OperatorMap, testCase.Infix);
            var node   = AstParser.Parse(DemoUtility.OperatorMap, tokens);

            var ex = Assert.Throws <OverloadMismatchException>(() => ExpressionCompiler.Compile <double>(DemoUtility.CompilerFunctions, node));

            Assert.AreEqual(testCase.ExpectedOperator, ex.OperatorNode.OperatorInfo.Keyword);
            Assert.AreEqual(testCase.ActualArguments, ex.OperatorNode.Children.Count);
        }
Beispiel #10
0
        static void Main(string[] args)
        {
            string infix = string.Join(' ', args);

            Console.WriteLine(infix);

            var tokens = Lexer.Process(DemoUtility.OperatorMap, infix);
            var node   = AstParser.Parse(DemoUtility.OperatorMap, tokens);
            var func   = ExpressionCompiler.Compile <double>(DemoUtility.CompilerFunctions, node);

            Console.WriteLine(func());
        }
Beispiel #11
0
        public IIR Execute(IIR predecessorIR)
        {
            var xmlIR = predecessorIR as XmlIR;

            if (xmlIR == null)
            {
                // Message.Trace(Severity.Error, Resources.ErrorPhaseWorkflowIncorrectInputIRType, PredecessorIR.GetType().ToString(), this.Name);
            }

            var astIR = new AstIR(xmlIR)
            {
                AstRootNode = new AstRootNode(null)
            };

            var unboundReferences = new UnboundReferences();
            var languageSettings  = new LanguageSettings(_defaultXmlNamespace, typeof(AstNode));

            foreach (BimlFile bimlFile in astIR.BimlFiles)
            {
                if (bimlFile.XDocument.Root != null)
                {
                    AstParser.ParseDocument(bimlFile, astIR.AstRootNode, unboundReferences, languageSettings);
                }
            }

            unboundReferences.ResolveAll(astIR.AstRootNode.SymbolTable);
            CompileTimeResolver.ResolveAll(astIR.AstRootNode.SymbolTable, unboundReferences);

            if (unboundReferences.Count > 0)
            {
                foreach (var unboundReference in unboundReferences)
                {
                    string filename            = unboundReference.BimlFile.Name;
                    string refName             = unboundReference.XValue;
                    string refTypeFriendlyName = unboundReference.BoundProperty.PropertyType.Name;
                    string xml           = unboundReference.XObject.ToString();
                    int    line          = ((IXmlLineInfo)unboundReference.XObject).LineNumber;
                    int    offset        = ((IXmlLineInfo)unboundReference.XObject).LinePosition;
                    var    friendlyNames = (FriendlyNameAttribute[])unboundReference.BoundProperty.PropertyType.GetCustomAttributes(typeof(FriendlyNameAttribute), false);
                    if (friendlyNames != null && friendlyNames.Length > 0)
                    {
                        refTypeFriendlyName = friendlyNames[0].FriendlyName;
                    }

                    // TODO: Fatal Error
                    MessageEngine.Trace(filename, line, offset, Severity.Error, "V0101", null, "Could not resolve reference to '{0}' of type '{1}'. '{2}' is invalid.", refName, refTypeFriendlyName, xml);
                }

                throw new InvalidOperationException("Parsing was unsuccessful.");
            }

            return(astIR);
        }
Beispiel #12
0
        public void TestCases(End2EndTestCase <double> testCase)
        {
            var tokens = Lexer.Process(DemoUtility.OperatorMap, testCase.Infix);

            var node = AstParser.Parse(DemoUtility.OperatorMap, tokens);

            Assert.AreEqual(testCase.ExpectedNodeString, node.ToString());

            var functionActual = ExpressionCompiler.Compile <Context <double>, double>(DemoUtility.CompilerFunctions, node);

            Assert.AreEqual(testCase.ExpectedFunction(s_ctx), functionActual(s_ctx));
        }
Beispiel #13
0
        private ControlFlowGraph <Statement <DummyInstruction> > ConstructAst(
            IEnumerable <DummyInstruction> instructions)
        {
            var architecture = DummyArchitecture.Instance;

            var dfgBuilder = new DummyTransitionResolver();
            var cfgBuilder = new SymbolicFlowGraphBuilder <DummyInstruction>(architecture, instructions, dfgBuilder);

            var cfg        = cfgBuilder.ConstructFlowGraph(0);
            var astBuilder = new AstParser <DummyInstruction>(cfg, dfgBuilder.DataFlowGraph);

            return(astBuilder.Parse());
        }
        private void RunTest(string input, string output)
        {
            var ast =
                new AstParser(new FunctionDeclarationsFactory()).Parse(input);
            var reduced  = AstReducer.Reduce(ast);
            var expected =
                new AstParser(new FunctionDeclarationsFactory()).Parse(output);

            Console.WriteLine("<<<<<<<<Input ast>>>>>>>>");
            Console.WriteLine(ast.PrettyPrint());
            Console.WriteLine("<<<<<<<<Reduced ast>>>>>>>>");
            Console.WriteLine(reduced.PrettyPrint());
            Console.WriteLine("<<<<<<<<Expected ast>>>>>>>>");
            Console.WriteLine(expected.PrettyPrint());
            Assert.AreEqual(output, reduced.Print());
        }
Beispiel #15
0
        static LllCompiler()
        {
            SymTable = LllSymbolTable.CreateBasic();

            var tokenizer = Tokenizer.CreateBasic();

            tokenizer.FilePath = "<builtin>";
            var foreigns = new StringBuilder();

            foreigns.AppendLine("foreign func alloc as 'malloc' (size: size) -> void*;");
            foreigns.AppendLine("foreign func free as 'free' (ptr: void*);");
            foreigns.AppendLine("foreign func sizeof as 'sizeof' () -> size;");
            foreigns.AppendLine("foreign func printf as 'printf' (fmt: char*, ...) -> i32;");
            var foreignsTks = tokenizer.Parse(foreigns.ToString());
            var foreignsTs  = new TokenStream(foreignsTks);

            _program = AstParser.Parse(foreignsTs);
        }
Beispiel #16
0
        private static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;

            string example = File.ReadAllText("example.qt");
            Unit   unit    = AstParser.ParseUnit(example);

            using (var tc = new TypeChecker())
            {
                foreach (Def def in unit.Definitions)
                {
                    Console.WriteLine(def);
                    Stopwatch timer = Stopwatch.StartNew();
                    tc.TypeCheck(def);
                    Console.WriteLine("OK in {0} ms", timer.ElapsedMilliseconds);
                    Console.WriteLine();
                }
            }
        }
Beispiel #17
0
        public VarEnum(AstUserDefinedTypeName type) : base(type)
        {
            // Set our enum definition
            EnumDefinition = AstParser.GetNode <AstEnumDefinition>(type.ReferencedDeclaration);

            // Determine how many bytes is needed to address the enum. The enum size is
            // dependent on the amount of bytes needed to index all enum options.
            int enumSize           = 0;
            int highestMemberIndex = EnumDefinition.Members.Length - 1;

            while (highestMemberIndex > 0)
            {
                // Add one to our byte count, and shift over.
                highestMemberIndex >>= 8;
                enumSize++;
            }

            // Initialize our bounds
            InitializeBounds(1, enumSize);
        }
Beispiel #18
0
        public static ShaderFile CreateFromText(string payload, IGlobalScopeFactory globalScopeFactory = null)
        {
            globalScopeFactory = globalScopeFactory ?? new GlobalScopeFactory();
            ShaderFile result = new ShaderFile();
            AstParser  parser = new AstParser();

            result.SyntaxTree = parser.Parse(payload);

            var globalScope = globalScopeFactory.Construct(result.SyntaxTree.Version);

            SemanticModelBuilderVisitor sBuilder = new SemanticModelBuilderVisitor();
            SemanticModelBuilderContext sContext = new SemanticModelBuilderContext();

            sBuilder.Visit(result.SyntaxTree, sContext);

            result.SemanticContext = new SemanticContext(sContext.Result, globalScope);
            result.SemanticContext.ResolveSymbolReferences();

            return(result);
        }
Beispiel #19
0
    private IData ReadInput()
    {
        var reader = new AstReader();

        reader.Escape         = "!";
        reader.EscapeBehavior = AstReader.EscapeHandling.Skip;
        reader.SequenceSplit  = ",";
        var group   = new GroupSymbol("{", "}");
        var garbage = new GroupSymbol("<", ">", false);

        reader.AddGroup(group).AddGroup(garbage);

        var parser = new AstParser <IData>();

        parser.Add(new TupleParser <IData>(group, (IList <IData> args, out IData result) =>
        {
            result = new Group {
                Data = args.ToList()
            };
            return(true);
        }));
        parser.Add(new TupleParser <IData>(garbage, (IList <IData> args, out IData result) =>
        {
            result = new Garbage {
                Content = args.Count > 0 ? args[0] as GarbageData : null
            };
            return(true);
        }));
        parser.Add(new SequenceParser <IData>((AstParser <IData> _, IList <AstNode> nodes, out IData result) =>
        {
            result = new GarbageData(nodes.Str());
            return(true);
        }));

        var nodes = reader.Read(InputLine, new TokenSettings {
            SingleLetters = true
        });

        return(parser.Parse(nodes));
    }
Beispiel #20
0
        public string CompileString(string source)
        {
            var sw = new Stopwatch();

            Console.WriteLine("Parsing sources into tokens...");
            sw.Start();
            var tks = _tokenizer.Parse(source);

            sw.Stop();
            Console.WriteLine("Parsed to tokens in {0}ms", sw.ElapsedMilliseconds);
            var ts = new TokenStream(tks);

            Console.WriteLine("Parsing tokens into AST...");
            sw.Restart();
            Ast = AstParser.Parse(ts);
            sw.Stop();
            Console.WriteLine("Parsed to AST in {0}ms", sw.ElapsedMilliseconds);
            SemanticAnalyzer.Analyze(Ast);
            TypeChecker.Check(Ast);
            _program.AppendAst(Ast);
            return(_program.CompileToC());
        }
Beispiel #21
0
        public VarStruct(AstUserDefinedTypeName type, VarLocation location) : base(type)
        {
            // Set our struct definition
            StructDefinition = AstParser.GetNode <AstStructDefinition>(type.ReferencedDeclaration);

            // Obtain our struct members.
            Members = StructDefinition.Members.Select(x => new StateVariable(x)).ToArray();

            // Resolve all of the storage locations for these state variables.
            StorageLocation endLocation = StorageManager.ResolveStorageSlots(Members);

            // Obtain our next free slot based off of our end location.
            int nextFreeSlot = (int)endLocation.SlotKeyInteger;

            if (endLocation.DataOffset > 0)
            {
                nextFreeSlot++;
            }

            // Our next free slot signifies our used storage entry count to that point.

            // Initialize our bounds
            InitializeBounds(nextFreeSlot, UInt256.SIZE, location);
        }
Beispiel #22
0
        public override Value Evaluate(RubyContext context)
        {
#if DEBUG
            context.VM.CurrentEvalNode = this;
#endif

            string name   = AstParser.GetNamePathFinalName(this.name);
            RClass target = (context.Self is RClass) ? ( RClass )context.Self : null;
            Value  value  = null;

            if (context.Module != null)
            {
                if (context.Module.constants.HasLocalValue(name))
                {
                    value = context.Module.constants.GetLocalValue(name);
                }
            }
            else if (context.HasValue(name))
            {
                value = context.GetValue(name);
            }

            if (value == null || !(value is RClass))
            {
                var classclass = context.RootContext.GetLocalValue("Class").As <RClass> ();
                var superclass = context.RootContext.GetLocalValue("Object").As <RClass> ();
                var parent     = target == null ? context.Module : target;

                if (super != null)
                {
                    superclass = super.Evaluate(context)?.As <RClass> ();
                    if (superclass == null)
                    {
                        VM.ThrowException($"superclass '{super}' not found.");
                    }
                }

                var newclass = context.VM.DefClass(classclass, name, superclass, parent);
                value = Value.Class(newclass);

                if (context.VM.IsCustomClass(superclass))
                {
                    context.VM.WriteCustomClassFlag(newclass, context.VM.GetCustomClassType(superclass));
                    context.VM.WriteCustomClassRClass(newclass, context.VM.GetCustomClassRClass(superclass));
                }

                if (parent == null)
                {
                    context.RootContext.SetLocalValue(name, value);
                }
                else
                {
                    parent.constants.SetLocalValue(name, value);
                }
            }

            var dclass = value.As <RClass> ();

            RubyContext classcontext = context.VM.NewContext(dclass, context);

            body.Evaluate(classcontext);

            return(null);
        }