コード例 #1
0
        public ActionResult <TranspileResponse> Transpile([FromQuery] TargetLanguage target, [FromBody] TranspileRequest input)
        {
            var response = new TranspileResponse {
                Target = target
            };

            var program = Parser.ParseSylvreInput(input.Code);

            if (program.HasParseErrors)
            {
                response.HasErrors   = true;
                response.ErrorSource = TranspileResponseErrorSource.Parser;
                response.Errors      = program.ParseErrors;

                return(Ok(response));
            }

            var output = Transpiler.TranspileSylvreToTarget(program, target);

            if (output.HasTranspileErrors)
            {
                response.HasErrors   = true;
                response.ErrorSource = TranspileResponseErrorSource.Transpiler;
                response.Errors      = output.TranspileErrors;

                return(Ok(response));
            }

            response.TranspiledCode = output.TranspiledCode;
            return(Ok(response));
        }
コード例 #2
0
        public void ParseFile(string moduleName, Stream inStream, Transpiler t)
        {
            Translator  = t;
            RootBlock   = RootBlock.Create(moduleName + "Module");
            t.RootBlock = RootBlock;
            Preprocessor preprocessor = new Preprocessor();
            TokenList    list         = preprocessor.Read(inStream);

#if DEBUG_TOKENIZER
            Debug.Print("");
            Debug.Print("");
            //DebugTextWriter writer = new DebugTextWriter();
            StringWriter writer = new StringWriter();
            list.Print(writer);
            Debug.Print(writer.ToString());
            Debug.Print("");
            Debug.Print("");
#endif
            //
            //PushPolicy(RootPolicy);
            CreateState(list);
            //Visit(RootBlock);
            PushDialect(new ParserDialect(this));
            ParseLines(RootBlock);
            PopState();
            //PopPolicy();

            //TODO:This should go in the compiler class.
            RootBlock.Resolve();
            t.Visit(RootBlock);
            //
            t.Close();
        }
コード例 #3
0
        //
        static bool Write_Default(Transpiler t, ClauseExpr d)
        {
            if (d.IsProperty)
            {
                t.WriteLine("if (_bwxClause != null && _bwxClause.Exists<{0}>({1}, {2}))",
                            d.Predicate.ToPredicate().Spec, t.Translate(d.Predicate), t.Translate(d.Object));
            }

            /*else if (d.HasMetaDefs)
             * {
             *  t.WriteLine("_bwxClause = bwxTask.Context.Find(new ClausePattern({0}, {1}, {2}));",
             *      t.Translate(d.Subject), t.Translate(d.Predicate), t.Translate(d.Object));
             *  t.WriteLine("if (_bwxClause != null)");
             * }*/
            else
            {
                if (d.Object.IsSnippet)
                {
                    t.WriteLine("if(bwxTask.Context.Exists<{0}>({1}, {2}, {3}))",
                                d.Type, t.Translate(d.Subject), t.Translate(d.Predicate), t.Translate(d.Object));
                }
                else
                {
                    t.WriteLine("if(bwxTask.Context.Exists({0}, {1}, {2}))",
                                t.Translate(d.Subject), t.Translate(d.Predicate), t.Translate(d.Object));
                }
            }
            return(false);
        }
コード例 #4
0
        public async Task SaveModuleOutput(bool decend = true, bool suppressMessage = false)
        {
            this.Transpiler.StartTranspilation(this.Name);
            if (!suppressMessage)
            {
                Console.WriteLine($"Perfectly parsed: {Name}");
            }
            await FileSystem.SaveFile("Model.xsd", this.OutPath, Transpiler.XsdToString());

            await FileSystem.SaveFile("index.html", this.OutPath, Transpiler.HtmlToString());

            foreach (var(key, value) in Transpiler.JsonToString())
            {
                await FileSystem.SaveFile(key, this.OutPath, value);
            }

            // Trickery to not parse infinately...
            // TODO: replace with propper topological order...
            if (decend)
            {
                // We would now also want to resolve the other modules
                // which depend upon this module so that they are automatically
                // regenerated and their output changed.
                // TODO: notice circular dependencies, remove diamond of death...
                this.Project
                .Modules
                .ToList()
                .FindAll(m => m.ReferencedModules.FirstOrDefault(r => r == this.Name) != null)
                .ForEach(async m =>
                {
                    m.Parse();
                    await m.SaveModuleOutput(false);
                });
            }
        }
コード例 #5
0
ファイル: TaskDef.cs プロジェクト: botworx/botworx-dotcore
        public string CreateParameterString(Transpiler t, bool isCall)
        {
            string result = "";

            if (isCall)
            {
                result = "MentalTask bwxTask";
            }
            else
            {
                if (IsInnerTask)
                {
                    result = "__bwxTask";
                }
                else
                {
                    result = "bwxTask";
                }
            }

            foreach (var param in Parameters)
            {
                result += ", ";
                if (isCall)
                {
                    result += param.TypeToken + " ";
                }
                result += param.Token.ToString();
            }
            return(result);
        }
コード例 #6
0
ファイル: TranspilerTests.cs プロジェクト: davidadsit/sellout
 public void Setup()
 {
     parserMock = new Mock <IParser>();
     writerMock = new Mock <ICSharpWriter>();
     transpiler = new Transpiler(parserMock.Object, writerMock.Object);
     File.WriteAllText(SourcePathRock, "");
 }
コード例 #7
0
ファイル: Program.cs プロジェクト: lewisc64/aoe2ai
        static void Main()
        {
            var config = new NLog.Config.LoggingConfiguration();

            config.AddRule(LogLevel.Debug, LogLevel.Fatal, new ColoredConsoleTarget {
                Layout = new SimpleLayout("${message}")
            });
            LogManager.Configuration = config;

            Console.WriteLine("Welcome to the aoe2ai snippeter!");
            Console.WriteLine("Results will be automatically copied to the clipboard.\n");

            var clipboard  = new Clipboard();
            var transpiler = new Transpiler();

            while (true)
            {
                Console.Write(">");
                var content = Console.ReadLine();

                var result = transpiler.Transpile(content).Render(new IFormatter[] { new IndentedDefrule(), new IndentedCondition() });
                if (!string.IsNullOrWhiteSpace(result))
                {
                    clipboard.SetText(result);
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine($"\n{result}\n");
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
            }
        }
                static IEnumerable <CodeInstruction> HaulBeforeSupply(IEnumerable <CodeInstruction> _codes, ILGenerator generator)
                {
                    var t = new Transpiler(_codes, MethodBase.GetCurrentMethod());

                    var nearbyResourcesIdx = t.TryFindCodeIndex(code => code.Calls(AccessTools.Method(typeof(WorkGiver_ConstructDeliverResources), "FindAvailableNearbyResources")));
                    var foundResIdx        = t.TryFindCodeLastIndex(nearbyResourcesIdx, code => code.opcode == OpCodes.Brfalse) + 1;
                    var foundRes           = generator.DefineLabel();

                    t.codes[foundResIdx].labels.Add(foundRes);
                    var returnJobIdx = t.TryFindCodeIndex(foundResIdx, code => code.opcode == OpCodes.Ret);
                    var jobVar       = t.codes[returnJobIdx - 1].operand;

                    t.TryInsertCodes(
                        0,
                        (i, codes) => i == foundResIdx,
                        (i, codes) => new List <CodeInstruction> {
                        // job = _HaulBeforeSupply(pawn, (Thing) c, foundRes);
                        new CodeInstruction(OpCodes.Ldarg_1),                  // Pawn pawn
                        new CodeInstruction(OpCodes.Ldarg_2),                  // IConstructible c
                        new CodeInstruction(OpCodes.Castclass, typeof(Thing)), // (Thing) c
                        new CodeInstruction(codes[i + 1]),                     // Thing foundRes
                        new CodeInstruction(codes[i + 2]),                     // Thing foundRes
                        new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(WorkGiver_ConstructDeliverResources_ResourceDeliverJobFor_Patch), nameof(_HaulBeforeSupply))),
                        new CodeInstruction(OpCodes.Stloc_S, jobVar),

                        // if (job != null) return job;
                        new CodeInstruction(OpCodes.Ldloc_S, jobVar),
                        new CodeInstruction(OpCodes.Brfalse_S, foundRes),
                        new CodeInstruction(OpCodes.Ldloc_S, jobVar),
                        new CodeInstruction(OpCodes.Ret),
                    });

                    return(t.GetFinalCodes());
                }
コード例 #9
0
ファイル: Program.cs プロジェクト: jolnsigkitu/implementation
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("You need to provide the (relative) path to your file(s) as an argument.");
                return;
            }

            foreach (var fileName in args)
            {
                string fileContent = File.ReadAllText(fileName);

                var transpiler = new Transpiler();

                try
                {
                    string transpiledCode = transpiler.fromString(fileContent);

                    string csFileName = Path.ChangeExtension(fileName, ".cs");
                    File.WriteAllText(csFileName, transpiledCode);
                }
                catch (Exception ex)
                {
                    throw new Exception($"An error occured while transpiling {fileName}:\n" + ex.Message, ex);
                }
            }
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: lewisc64/aoe2ai
        public static void Main(string[] args)
        {
            var parsedArgs = new ArgParser(args);

            if (parsedArgs.PositionalArguments.Count != 3 || parsedArgs.PositionalArguments.Contains("help"))
            {
                Console.WriteLine("Usage:");
                Console.WriteLine("  parsefile.exe INPUT_PATH OUTPUT_FOLDER_PATH AI_NAME");
                Console.WriteLine("Flags:");
                Console.WriteLine("  --minify");
                Console.WriteLine("  --rule-length=16");
                Console.WriteLine("  --rule-length=32");
                return;
            }

            var inputPath  = new FileInfo(parsedArgs.PositionalArguments[0]);
            var outputPath = new DirectoryInfo(parsedArgs.PositionalArguments[1]);
            var name       = parsedArgs.PositionalArguments[2];

            var minify = parsedArgs.Flags.Contains("--minify");

            if (parsedArgs.Flags.Any(x => x.StartsWith("--rule-length=")))
            {
                Defrule.MaxRuleSize = int.Parse(parsedArgs.Flags.Last(x => x.StartsWith("--rule-length=")).Split("=").Last());
            }

            var content = File.ReadAllText(inputPath.FullName);

            var config = new NLog.Config.LoggingConfiguration();

            config.AddRule(LogLevel.Debug, LogLevel.Fatal, new ColoredConsoleTarget {
                Layout = new SimpleLayout("${level:uppercase=true}|${logger}|${message}")
            });
            LogManager.Configuration = config;

            var transpiler = new Transpiler();
            var context    = new TranspilerContext
            {
                CurrentFileName = inputPath.Name,
                RootPath        = inputPath.DirectoryName,
                CurrentPath     = inputPath.DirectoryName,
            };

            var    output = transpiler.Transpile(content, context);
            string outputContent;

            if (minify)
            {
                output.InsertLineBreaks = false;
                outputContent           = output.Render(new IFormatter[] { new OneLineCondition(), new OneLineDefrule() });
            }
            else
            {
                outputContent = output.Render();
            }

            Save(name, outputPath, outputContent);
            Analyze(context);
        }
コード例 #11
0
 static bool Write_FS_TS_U(Transpiler t, ClauseExpr d)
 {
     t.WriteLine("foreach({0} {1} in bwxTask.Context.QueryType({2}))",
                 d.Subject.Type, t.Translate(d.Subject), t.Translate(d.Subject.AtomTypeExpr));
     t.StartBlock(null);
     Write_U(t, d);
     return(false);
 }
コード例 #12
0
        static void Main(string[] args)
        {
            ILexicalAnalyzer lexicalAnalyzer = new LexicalAnalyzer();
            ITranspiler      transpiler      = new Transpiler(lexicalAnalyzer);

            transpiler.Transpile(Directory.GetCurrentDirectory() + @"\Program.vm");

            Console.ReadLine();
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: dzw/cs2ts
        private static void NewMethod(string input, string output)
        {
            System.Console.WriteLine("translating " + input);

            var csCode  = System.IO.File.ReadAllText(input);
            var visitor = new Transpiler(csCode);
            var tsCode  = visitor.ToTypeScript();

            System.IO.File.WriteAllText(output, tsCode);
        }
コード例 #14
0
ファイル: Transpiler.cs プロジェクト: jasonmeisel/OverwatchCS
    static void Main(string[] args)
    {
        var transpiler = new Transpiler();
        var source     = File.ReadAllText(args.FirstOrDefault() ?? "Test\\Test.cs");
        var rules      = transpiler.TranspileToRules(source);

        Console.WriteLine(rules);
        TextCopy.Clipboard.SetText(rules);

        Console.WriteLine("Copied rules to clipboard. Open the workshop and click paste.");
    }
コード例 #15
0
        public void Should_Output_Valid_JavaScript_Function_Return(string sylvreInput, string jsRegex)
        {
            SylvreProgram program = Parser.ParseSylvreInput(sylvreInput);

            Assert.IsFalse(program.HasParseErrors);

            TranspileOutputBase output = Transpiler.TranspileSylvreToTarget(
                program, TargetLanguage.Javascript);

            StringAssert.IsMatch(jsRegex, output.TranspiledCode);
        }
コード例 #16
0
ファイル: LoopBlockTests.cs プロジェクト: shahzaib-m/Sylvre
        public void Should_Output_Valid_For_Loop_Block(string sylvreInput, string regexToMatch)
        {
            SylvreProgram program = Parser.ParseSylvreInput(sylvreInput);

            Assert.IsFalse(program.HasParseErrors);

            TranspileOutputBase output = Transpiler.TranspileSylvreToTarget(
                program, TargetLanguage.Javascript);

            StringAssert.IsMatch(regexToMatch, output.TranspiledCode);
        }
コード例 #17
0
        public void Should_Not_Provide_Transpile_Errors(string sylvreInput)
        {
            SylvreProgram program = Parser.ParseSylvreInput(sylvreInput);

            Assert.IsFalse(program.HasParseErrors);

            TranspileOutputBase output = Transpiler.TranspileSylvreToTarget(
                program, TargetLanguage.Javascript);

            Assert.IsFalse(output.HasTranspileErrors);
        }
コード例 #18
0
 static bool Write_FO(Transpiler t, ClauseExpr d)
 {
     if (d.IsMeta)
     {
         t.WriteLine("{0} {1} = ({0})_bwxClause[{2}];",
                     d.Type, t.Translate(d.Object), t.Translate(d.Predicate));
         return(false);
     }
     t.WriteLine("foreach({0} {1} in bwxTask.Context.QuerySubjPred<{0}>({2}, {3}))",
                 d.Type, t.Translate(d.Object), t.Translate(d.Subject), t.Translate(d.Predicate));
     return(true);
 }
コード例 #19
0
        public void Should_Provide_Transpile_Error_When_Assigning_To_Sylvre()
        {
            string        sylvreInput = "\nSylvre = 25.21#";
            SylvreProgram program     = Parser.ParseSylvreInput(sylvreInput);

            Assert.IsFalse(program.HasParseErrors);

            TranspileOutputBase output = Transpiler.TranspileSylvreToTarget(
                program, TargetLanguage.Javascript);

            Assert.IsTrue(output.HasTranspileErrors);
        }
コード例 #20
0
        public override void Parse(string line, TranspilerContext context)
        {
            var templateName = GetData(line)["name"].Value;

            if (!context.Templates.ContainsKey(templateName))
            {
                throw new System.InvalidOperationException($"Template '{templateName}' is not defined.");
            }

            var parameters = new Dictionary <string, string>();

            foreach (var match in ParamRegex.Matches(line).Cast <Match>())
            {
                var name  = match.Groups["name"].Value;
                var value = match.Groups["value"].Value;

                if (value.StartsWith("\"") && value.EndsWith("\""))
                {
                    value = value.Trim('"');
                }
                parameters[name] = value.Replace("\\\"", "\"");
            }

            var template = context.Templates[templateName];

            foreach ((string key, string value) in parameters)
            {
                template = template.Replace($"{{{key}}}", value);
            }

            Script rules = null;

            context.UsingSubcontext(subcontext =>
            {
                subcontext.CurrentFileName = $"template '{templateName}'";

                var transpiler = new Transpiler();
                rules          = transpiler.Transpile(template, subcontext);
            });

            if (context.ConditionStack.Any())
            {
                foreach (var rule in rules)
                {
                    (rule as Defrule)?.Actions.AddRange(context.ActionStack);
                }
                context.AddToScriptWithJump(rules, Condition.JoinConditions("and", context.ConditionStack).Invert());
            }
            else
            {
                context.AddToScript(context.ApplyStacks(rules));
            }
        }
コード例 #21
0
        public void Should_Output_Valid_JavaScript_Unary_Decrement_Suffix()
        {
            string        sylvreInput = "var decrement#";
            string        jsRegex     = @"""use strict"";__var.*--[n ]*;";
            SylvreProgram program     = Parser.ParseSylvreInput(sylvreInput);

            Assert.IsFalse(program.HasParseErrors);

            TranspileOutputBase output = Transpiler.TranspileSylvreToTarget(
                program, TargetLanguage.Javascript);

            StringAssert.IsMatch(jsRegex, output.TranspiledCode);
        }
コード例 #22
0
ファイル: LoopBlockTests.cs プロジェクト: shahzaib-m/Sylvre
        public void Should_Output_Valid_While_Loop_Block()
        {
            string        sylvreInput = "loopwhile(FALSE) < >";
            SylvreProgram program     = Parser.ParseSylvreInput(sylvreInput);

            Assert.IsFalse(program.HasParseErrors);

            TranspileOutputBase output = Transpiler.TranspileSylvreToTarget(
                program, TargetLanguage.Javascript);

            StringAssert.IsMatch(@"""use strict"";while[\n ]*\(.*\)[\n ]*{[\n ]*}",
                                 output.TranspiledCode);
        }
コード例 #23
0
        public void Should_Output_Valid_Else_Statement()
        {
            string        sylvreInput = "if (TRUE) <> else < >";
            SylvreProgram program     = Parser.ParseSylvreInput(sylvreInput);

            Assert.IsFalse(program.HasParseErrors);

            TranspileOutputBase output = Transpiler.TranspileSylvreToTarget(
                program, TargetLanguage.Javascript);

            StringAssert.IsMatch(@"""use strict"";.+else[\n ]*{[\n ]*}",
                                 output.TranspiledCode);
        }
コード例 #24
0
        public void Should_Append_Two_Underscores_If_FuncName_Is_Reserved_Keyword(string sylvreInput, string regexToMatch)
        {
            SylvreProgram program = Parser.ParseSylvreInput(sylvreInput);

            Assert.IsFalse(program.HasParseErrors);

            TranspileOutputBase output = Transpiler.TranspileSylvreToTarget(
                program, TargetLanguage.Javascript);

            Assert.IsFalse(output.HasTranspileErrors);

            StringAssert.IsMatch(regexToMatch, output.TranspiledCode);
        }
コード例 #25
0
        public void Should_Output_Valid_ComplexVarReference_IndexRef(string sylvreInput,
                                                                     string regexToMatch)
        {
            SylvreProgram program = Parser.ParseSylvreInput(sylvreInput);

            Assert.IsFalse(program.HasParseErrors);

            TranspileOutputBase output = Transpiler.TranspileSylvreToTarget(
                program, TargetLanguage.Javascript);

            Assert.IsFalse(output.HasTranspileErrors);

            StringAssert.IsMatch(regexToMatch, output.TranspiledCode);
        }
コード例 #26
0
        public void Should_Give_Error_When_Invalid_Module_Member_Ref_Is_Used(string sylvreInput)
        {
            SylvreProgram program = Parser.ParseSylvreInput(sylvreInput);

            Assert.IsFalse(program.HasParseErrors);

            TranspileOutputBase output = Transpiler.TranspileSylvreToTarget(
                program, TargetLanguage.Javascript);

            Assert.IsTrue(output.HasTranspileErrors);

            Assert.AreEqual("This Sylvre module member does not exist.",
                            output.TranspileErrors.First().Message);
        }
コード例 #27
0
        public void Should_Give_Error_When_Index_Reference_After_Module_Ref(string sylvreInput)
        {
            SylvreProgram program = Parser.ParseSylvreInput(sylvreInput);

            Assert.IsFalse(program.HasParseErrors);

            TranspileOutputBase output = Transpiler.TranspileSylvreToTarget(
                program, TargetLanguage.Javascript);

            Assert.IsTrue(output.HasTranspileErrors);

            Assert.AreEqual("An index reference is not allowed after a module reference.",
                            output.TranspileErrors.First().Message);
        }
コード例 #28
0
        public void Should_Give_Error_When_No_Member_Ref_After_Module_Ref(string sylvreInput)
        {
            SylvreProgram program = Parser.ParseSylvreInput(sylvreInput);

            Assert.IsFalse(program.HasParseErrors);

            TranspileOutputBase output = Transpiler.TranspileSylvreToTarget(
                program, TargetLanguage.Javascript);

            Assert.IsTrue(output.HasTranspileErrors);

            Assert.AreEqual("Missing a module member reference after module name.",
                            output.TranspileErrors.First().Message);
        }
コード例 #29
0
ファイル: BaseHandler.cs プロジェクト: SSoTme/cli
        public BaseHandler(Transpiler sourceTranspiler, SSOTMEPayload payload)
        {
            this.Payload    = payload;
            this.ScreenName = payload.ScreenName;

            this.Parameters              = new Dictionary <string, string>();
            this.OutputFileSet           = new FileSet();
            this.OutputFileSet.FileSetId = sourceTranspiler.TranspilerId;
            this.SourceTranspiler        = sourceTranspiler;
            this.RootDirInfo             = new DirectoryInfo(Path.Combine("C:\\temp\\", Guid.NewGuid().ToString()));
            this.RootDirInfo.Create();

            if (String.IsNullOrEmpty(this.Payload.CLIInputFileSetXml) && !String.IsNullOrEmpty(this.Payload.CLIInputFileSetJson))
            {
                this.Payload.CLIInputFileSetXml = this.Payload.CLIInputFileSetJson.JsonToXml().OuterXml;
            }

            if (String.IsNullOrEmpty(this.Payload.CLIInputFileSetXml))
            {
                this.InputFileSet = new FileSet();
            }
            else
            {
                this.InputFileSet = this.Payload.CLIInputFileSetXml.ToFileSet();
            }

            if (!ReferenceEquals(this.Payload.CLIInput, null) && this.Payload.CLIInput.Any())
            {
                this.InputFileName = this.Payload.CLIInput.First();
            }
            else
            {
                this.InputFileName = "";
            }

            this.OutputFileName = this.Payload.CLIOutput;


            if (String.IsNullOrEmpty(this.OutputFileName))
            {
                this.OutputFileName = this.GetParameterByName("OutputFileName");
                if (String.IsNullOrEmpty(this.OutputFileName))
                {
                    this.OutputFileName = "output.txt";
                }
            }

            this.Parameters = this.PopulateParameters();
        }
コード例 #30
0
        public Dictionary <string, string> ToReplacementDictionary(Dictionary <string, string> dct)
        {
            dct.Add("$aurelia_project_name$", AureliaProjectName);
            dct.Add("$aurelia_module_loader$", ModuleLoader.ToString());
            dct.Add("$aurelia_http_type$", HttpType.ToString());
            dct.Add("$aurelia_transpiler$", Transpiler.ToString());
            dct.Add("$aurelia_minification$", Minification.ToString());
            dct.Add("$aurelia_css_processing$", CSSProcessing.ToString());
            dct.Add("$aurelia_unit_ruinner$", UnitTestRunner.ToString());
            dct.Add("$aurelia_integration_testing$", IntegrationTesting.ToString());
            dct.Add("$aurelia_install_after$", InstallAfter.ToString());
            dct.Add("$aurelia_build_after$", BuildAfter.ToString());

            return(dct);
        }