Example #1
0
        /// <summary>
        /// </summary>
        /// <param name="args">
        /// </param>
        private static void CommandLoop(string[] args)
        {
            bool processedargs = false;

            Console.WriteLine(locales.ZoneEngineConsoleCommands);

            while (!exited)
            {
                if (!processedargs)
                {
                    if (args.Length == 1)
                    {
                        if (args[0].ToLower() == "/autostart")
                        {
                            Console.WriteLine(locales.ServerConsoleAutostart);
                            csc.Compile(false);
                            StartTheServer();
                        }
                    }

                    processedargs = true;
                }

                Console.Write(Environment.NewLine + "{0} >>", locales.ServerConsoleCommand);
                string consoleCommand = Console.ReadLine();

                if (consoleCommand != null)
                {
                    if (!consoleCommands.Execute(consoleCommand))
                    {
                        ShowCommandHelp();
                    }
                }
            }
        }
Example #2
0
        public void TestBaseCompile()
        {
            var compiler = new ScriptCompiler("Zeus.Library.Tests.ScriptCompilerTests", "Output/Scripts.dll");

            compiler.SourceAssemblies.Add(Path.GetFullPath(Environment.CurrentDirectory + "/Scripts/TestScript.cs"));
            Assert.True(compiler.Compile(/*debug*/ true, /*cache*/ false));
        }
        private bool Compile()
        {
            CompilerOptions options = new CompilerOptions();

            options.DebugFlavor = DebugFlavor;
            if (DebugFlavor)
            {
                options.IncludeTests = IncludeTests;
            }
            else
            {
                options.Minimize = Minimize;
            }
            options.Defines    = GetDefines();
            options.References = GetReferences();
            options.Sources    = GetSources(_sources);
            options.Resources  = GetResources(_resources);
            if (_template != null)
            {
                options.TemplateFile = new TaskItemInputStreamSource(_template, "Template");
            }
            if (_docCommentFile != null)
            {
                options.DocCommentFile = new TaskItemInputStreamSource(_docCommentFile, "DocComment");
            }

            ITaskItem scriptTaskItem = new TaskItem(OutputPath);

            options.ScriptFile = new TaskItemOutputStreamSource(scriptTaskItem);

            string errorMessage = String.Empty;

            if (options.Validate(out errorMessage) == false)
            {
                Log.LogError(errorMessage);
                return(false);
            }

            ScriptCompiler compiler = new ScriptCompiler(this);

            compiler.Compile(options);
            if (_hasErrors == false)
            {
                _script = scriptTaskItem;

                string projectName    = (_projectPath != null) ? Path.GetFileNameWithoutExtension(_projectPath) : String.Empty;
                string scriptFileName = Path.GetFileName(scriptTaskItem.ItemSpec);
                string scriptPath     = Path.GetFullPath(scriptTaskItem.ItemSpec);

                Log.LogMessage(MessageImportance.High, "{0} -> {1} ({2})", projectName, scriptFileName, scriptPath);
            }
            else
            {
                return(false);
            }

            return(true);
        }
Example #4
0
        private CompiledScript CompileScript()
        {
            compilationOutput.CDSWriteLine("* Compiling *");
            var compiledScript = ScriptCompiler.Compile(script: csharpEditor.CDSScript);

            Common.DisplayCompilationOutput(compilationOutput, compiledScript);
            compilationOutput.CDSWriteLine("* Compilation done *");
            return(compiledScript);
        }
Example #5
0
        public bool Compile(out ICompilationUnitResult compilationUnitResult)
        {
            bool compilerSuccess = scriptCompiler.Compile(compilerOptions);

            compilationUnitResult = CreateResult(compilerOptions.ScriptFile as InMemoryStream);
            compilationErrors.Clear();

            return(compilerSuccess);
        }
        public bool Execute()
        {
            _options.References = _references;
            _options.Sources    = _sources.Cast <IStreamSource>().ToList();
            _options.ScriptFile = _output;

            ScriptCompiler compiler = new ScriptCompiler(this);

            return(compiler.Compile(_options));
        }
Example #7
0
        public void CorrectCommandWithoutParamsWithSpacesBegins()
        {
            var text = "@AlfaScript\n\r\n     BuildConf()";

            var result = ScriptCompiler.Compile(text);

            Assert.AreEqual(0, result.Errors.Count);
            Assert.AreEqual(1, result.Programm.Count);
            Assert.IsTrue(result.Programm[0] is BuildConfCommand);
        }
Example #8
0
        public void ScriptIsEmpty()
        {
            string script = "";

            var result = ScriptCompiler.Compile(script);

            Assert.AreEqual(1, result.Errors.Count);
            Assert.AreEqual(StringConst.ERR_INCORR_HEADER, result.Errors[0].ToString());
            Assert.AreEqual(0, result.Programm.Count);
        }
Example #9
0
        public void OnlyCommentsInScript()
        {
            var text = "@AlfaScript\n  #Comment1\n   #Comment2";

            var result = ScriptCompiler.Compile(text);

            Assert.AreEqual(1, result.Errors.Count);
            Assert.AreEqual(StringConst.ERR_NO_COMMANDS, result.Errors[0].ToString());
            Assert.AreEqual(0, result.Programm.Count);
        }
Example #10
0
        public void IncorrectHeader()
        {
            var text = "Invalid Header";

            var result = ScriptCompiler.Compile(text);

            Assert.AreEqual(1, result.Errors.Count);
            Assert.AreEqual(StringConst.ERR_INCORR_HEADER, result.Errors[0].ToString());
            Assert.AreEqual(0, result.Programm.Count);
        }
Example #11
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var result = ScriptCompiler.Compile(scriptBox.Text);

            logBox.Clear();

            foreach (var err in result.Errors)
            {
                logBox.AppendText(err.ToString() + "\n");
            }
        }
Example #12
0
        public void SpaceBetweenCommandAndBracketWithSpacesBegin()
        {
            var text = "@AlfaScript\n    BuildConf ()";

            var result = ScriptCompiler.Compile(text);

            Assert.AreEqual(2, result.Errors.Count);
            Assert.AreEqual(StringConst.ERR_CMD_FORMAT_OP_BRACK + " [строка: 2, столбец: 14]", result.Errors[0].ToString());
            Assert.AreEqual(StringConst.ERR_NO_COMMANDS, result.Errors[1].ToString());
            Assert.AreEqual(0, result.Programm.Count);
        }
Example #13
0
        public void IncorrectCommandWithSpacesBegin()
        {
            var text = "@AlfaScript\n\r\n     IncorrectCommand(aaa, \"bbb\")";

            var result = ScriptCompiler.Compile(text);

            Assert.AreEqual(2, result.Errors.Count);
            Assert.AreEqual(StringConst.ERR_UNKN_COMMAND + " [строка: 3, столбец: 6]", result.Errors[0].ToString());
            Assert.AreEqual(StringConst.ERR_NO_COMMANDS, result.Errors[1].ToString());
            Assert.AreEqual(0, result.Programm.Count);
        }
Example #14
0
        public void OnlyValidCommandNameInScriptWithSpacesBegins()
        {
            var text = "@AlfaScript\n         BuildConf";

            var result = ScriptCompiler.Compile(text);

            Assert.AreEqual(2, result.Errors.Count);

            Assert.AreEqual(StringConst.ERR_CMD_FORMAT_OP_BRACK + " [строка: 2, столбец: 19]", result.Errors[0].ToString());
            Assert.AreEqual(StringConst.ERR_NO_COMMANDS, result.Errors[1].ToString());
            Assert.AreEqual(0, result.Programm.Count);
        }
        public void CompileTest()
        {
            bool   bDebug = false;                      // TODO: 初始化为适当的值
            bool   bCache = false;                      // TODO: 初始化为适当的值
            string strAssemblyDirectory = string.Empty; // TODO: 初始化为适当的值
            string strScriptDirectory   = string.Empty; // TODO: 初始化为适当的值
            bool   expected             = false;        // TODO: 初始化为适当的值
            bool   actual;

            actual = ScriptCompiler.Compile(bDebug, bCache, strAssemblyDirectory, strScriptDirectory);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("验证此测试方法的正确性。");
        }
Example #16
0
        private bool Compile()
        {
            CompilerOptions options = new CompilerOptions();

            options.Minimize        = Minimize;
            options.Defines         = GetDefines();
            options.References      = GetReferences();
            options.Sources         = GetSources(Sources);
            options.Resources       = GetResources(Resources);
            options.IncludeResolver = this;
            options.AssemblyName    = AssemblyName;

            ITaskItem scriptTaskItem = new TaskItem(OutputPath);

            options.ScriptFile = new TaskItemOutputStreamSource(scriptTaskItem);

            if (GenerateScriptMetadata)
            {
                var metadataPath = Path.ChangeExtension(OutputPath, "meta.js");
                options.MetadataFile = new TaskItemOutputStreamSource(new TaskItem(metadataPath));
            }

            string errorMessage = string.Empty;

            if (options.Validate(out errorMessage) == false)
            {
                Log.LogError(errorMessage);
                return(false);
            }

            ScriptCompiler compiler = new ScriptCompiler(this);

            if (compiler.Compile(options) && hasErrors == false)
            {
                Script = scriptTaskItem;

                string projectName    = (ProjectPath != null) ? Path.GetFileNameWithoutExtension(ProjectPath) : string.Empty;
                string scriptFileName = Path.GetFileName(scriptTaskItem.ItemSpec);
                string scriptPath     = Path.GetFullPath(scriptTaskItem.ItemSpec);

                Log.LogMessage(MessageImportance.High, "{0} -> {1} ({2})", projectName, scriptFileName, scriptPath);
            }
            else
            {
                return(false);
            }

            return(true);
        }
Example #17
0
 private ExpressionScriptCompiled CompileScript(
     string dialect,
     string scriptName,
     string scriptExpression,
     string[] scriptParameterNames,
     Type[] parameterTypes,
     ExpressionScriptCompiled scriptCompiledBuf,
     ImportServiceCompileTime importService,
     ScriptCompiler scriptingCompiler)
 {
     return new ExpressionScriptCompiledImpl(
         scriptingCompiler.Compile(
             Script.OptionalDialect ?? _defaultDialect,
             Script));
 }
        public bool Execute()
        {
            _output = new CompilationOutput(_test.TestContext.TestName);

            _options.References     = _references;
            _options.Sources        = _sources.Cast <IStreamSource>().ToList();
            _options.Resources      = _resources.Cast <IStreamSource>().ToList();
            _options.TemplateFile   = _template;
            _options.DocCommentFile = _comments;
            _options.ScriptFile     = _output;

            ScriptCompiler compiler = new ScriptCompiler(this);

            return(compiler.Compile(_options));
        }
Example #19
0
        public IActionResult Index(string code, int?unused)
        {
            var compileResult = ScriptCompiler.Compile(code);

            if (compileResult.HasErrors)
            {
                return(View(new HomePageViewModel(compileResult.Diagnostics, code)));
            }

            //Store Code and Binary output in TempData and redirect to Download Page
            var key = GetFileCache().Store(JsonConvert.SerializeObject(new CodePackage {
                Code = code, OutputBinary = compileResult.OutputBinary
            }));

            return(RedirectToAction("Index", new { downloadKey = key }));
        }
Example #20
0
 /// <summary>Constructs a new command script.</summary>
 /// <param name="_name">The name of the script.</param>
 /// <param name="_typeName">The name of the script type.</param>
 /// <param name="_commands">All commands in the script.</param>
 /// <param name="engine">The backing script engine.</param>
 /// <param name="adj">How far to negatively adjust the entries' block positions, if any.</param>
 /// <param name="mode">What debug mode to use for this script.</param>
 public CommandScript(string _name, string _typeName, CommandEntry[] _commands, ScriptEngine engine, int adj = 0, DebugMode mode = DebugMode.FULL)
 {
     Debug        = mode;
     Name         = _name.ToLowerFast();
     TypeName     = _typeName;
     CommandArray = new CommandEntry[_commands.Length];
     System       = engine;
     for (int i = 0; i < CommandArray.Length; i++)
     {
         CommandArray[i]             = _commands[i].Duplicate();
         CommandArray[i].OwnIndex    = i;
         CommandArray[i].BlockStart -= adj;
         CommandArray[i].BlockEnd   -= adj;
     }
     Compiled = ScriptCompiler.Compile(this);
 }
Example #21
0
        private bool Compile(IEnumerable <ITaskItem> sourceItems, IEnumerable <ITaskItem> resourceItems, string locale)
        {
            CompilerOptions options = CreateOptions(sourceItems, resourceItems, locale, false, out ITaskItem scriptTaskItem);

            if (options.Validate(out string errorMessage) == false)
            {
                Log.LogError(errorMessage);
                return(false);
            }

            ScriptCompiler compiler = new ScriptCompiler(this);

            compiler.Compile(options);
            if (hasErrors == false)
            {
                // Only copy references once (when building language neutral scripts)
                bool copyReferences = string.IsNullOrEmpty(locale) && CopyReferences;

                OnScriptFileGenerated(scriptTaskItem, options, copyReferences);
                if (hasErrors)
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }

            if (Minimize)
            {
                CompilerOptions minimizeOptions    = CreateOptions(sourceItems, resourceItems, locale, true, out scriptTaskItem);
                ScriptCompiler  minimizingCompiler = new ScriptCompiler(this);
                minimizingCompiler.Compile(minimizeOptions);
                if (hasErrors == false)
                {
                    ExecuteCruncher(scriptTaskItem);
                    OnScriptFileGenerated(scriptTaskItem, minimizeOptions, /* copyReferences */ false);
                }
                else
                {
                    return(false);
                }
            }

            return(true);
        }
Example #22
0
        public static string LoadAssembly()
        {
            string error = "";

            if (_setting.Entity.IsScript)
            {
                ScriptCompiler.ClearTemp("smstemp");
                var refAsm = new string[] {
                    "NLog.dll",
                    "Newtonsoft.Json.dll",
                    "protobuf-net.dll",
                    "ZyGames.Framework.dll",
                    "ZyGames.Framework.Common.dll",
                    "ZyGames.Framework.Game.dll"
                };

                AppDomain.CurrentDomain.AppendPrivatePath(Path.Combine(MathUtils.RuntimePath, "smstemp"));
                var files = Directory.GetFiles(_setting.Entity.ScriptPath, "*.cs", SearchOption.AllDirectories);
                var cr    = ScriptCompiler.Compile(files, refAsm, "Entity.Model", false, false, "smstemp");
                if (cr != null)
                {
                    var assembly = cr.CompiledAssembly;
                    _setting.Entity.DymincEntity = assembly;
                }
                else
                {
                    error = "Compile fail";
                }
            }
            else
            {
                AppDomain.CurrentDomain.AppendPrivatePath(Path.GetFullPath(_setting.Entity.AssemblyPath));
                _setting.Entity.DymincEntity = AssemblyBuilder.ReadAssembly(_setting.Entity.AssemblyPath, null);
            }
            try
            {
                ProtoBufUtils.LoadProtobufType(_setting.Entity.DymincEntity);
            }
            catch (Exception)
            {
            }
            return(error);
        }
Example #23
0
        private static bool Execute(string[] args)
        {
            CommandLine commandLine = new CommandLine(args);

            if (commandLine.Options.Contains("attach"))
            {
                Debug.Fail("Attach");
            }

            if (commandLine.ShowHelp)
            {
                ShowUsage(string.Empty);

                return(true);
            }

            CompilerOptions compilerOptions = CreateCompilerOptions(commandLine);

            if (compilerOptions.Validate(out string errorMessage) == false)
            {
                ShowUsage(errorMessage);

                return(false);
            }

            if (commandLine.HideAbout == false)
            {
                ShowAbout();
            }

            ScriptCompiler compiler = new ScriptCompiler();
            bool           success  = compiler.Compile(compilerOptions);

#if DEBUG
            return(true);
#else
            return(success);
#endif
        }
Example #24
0
        public void Execute(Character character, string[] args)
        {
            if (args.Length == 0)
            {
                character.SendMessage("[Scripts] Using: /scripts <action>");
                character.SendMessage("[Scripts] Action: reboot");
                return;
            }

            switch (args[0])
            {
            case "reboot":
                CommandManager.Instance.Clear();
                ScriptCompiler.Compile();
                character.SendMessage("[Scripts] Done");
                break;

            default:
                character.SendMessage("[Scripts] Undefined action...");
                break;
            }
        }
Example #25
0
        public static ExpressionScriptCompiled CompileScript(
            string dialect,
            string scriptName,
            string expression,
            string[] parameterNames,
            Type[] evaluationTypes,
            ExpressionScriptCompiled optionalPrecompiled,
            ImportService importService,
            ScriptCompiler scriptingCompiler)
        {
#if NOT_USED
            ExpressionScriptCompiled compiled;
#endif
            if (optionalPrecompiled != null) {
                return optionalPrecompiled;
            }

            dialect ??= DEFAULT_DIALECT;
            return new ExpressionScriptCompiledImpl(
                scriptingCompiler.Compile(
                    dialect ?? DEFAULT_DIALECT,
                    new ExpressionScriptProvided(scriptName, expression, parameterNames, null, false, null, dialect)));
        }
            protected IMohidSim LoadUserInterface(CmdArgs args)
            {
                try
                {
                   FileName interfaceName;
                   data.sim.PreProcessing = OnPreProcessing;

                   if (args.HasParameter("script"))
                  interfaceName = new FileName(args.Parameters["script"]);
                   else
                  return null;

                   if (interfaceName.Extension.ToLower() == "dll") //it's a library
                   {
                  if (!args.HasParameter("class"))
                     return null;

                  string class_name = args.Parameter("class");

                  Assembly ass = Assembly.LoadFrom(interfaceName.FullPath);
                  data.userInterface = (IMohidSim)Activator.CreateInstance(ass.GetType("Mohid." + class_name));
                  return data.userInterface;
                   }
                   else //it's a script
                   {
                  ScriptCompiler sc = new ScriptCompiler();
                  Assembly ass = sc.Compile(interfaceName);
                  data.userInterface = (IMohidSim)sc.FindScriptInterface("IMohidSim", ass);
                  return data.userInterface;
                   }
                }
                catch (Exception ex)
                {
                   throw new Exception("MohidRunEngine.LoadUserInterface", ex);
                }
            }
Example #27
0
        static void Main(string[] args)
        {
            string appName = AppDomain.CurrentDomain.FriendlyName;
            string outputDirectory = Environment.CurrentDirectory;
            bool helpRequested = false;
            bool verboseOutputRequested = false;

            var optionSet = new OptionSet()
            {
                string.Format("Usage: {0} [OPTIONS] filename [filename ...]", appName),
                "",
                "Compile jumpman scripting language files (.jms files).",
                "",
                "  filename                   the path to a source file(s) to compile.",
                "",
                "Options:",
                { "o|out=", "the {DIRECTORY} to place compiler output.", value => outputDirectory = value },
                { "v|verbose", "write out extended runtime debug information.", value => verboseOutputRequested = value != null },
                { "h|help", "show this help message and exit.", value => helpRequested = value != null },
            };

            List<string> extra;
            try
            {
                extra = optionSet.Parse(args);
            }
            catch (OptionException e)
            {
                Console.WriteLine("{0}:", appName);
                Console.WriteLine(e.ToString());
                Console.WriteLine("Try '{0} --help' for more information.", appName);
                return;
            }

            Action writeUsage = () => optionSet.WriteOptionDescriptions(Console.Out);
            var filenames = extra.Select(filename => Path.GetFullPath(filename)).ToList<string>();
            var invalidFilenames = filenames.Where(filename => !File.Exists(filename)).ToList<string>();

            if (helpRequested)
            {
                writeUsage();
                return;
            }

            if (filenames.Count < 1)
            {
                Console.WriteLine("Must specify at least one filename.");
                Console.WriteLine();
                writeUsage();
                return;
            }

            if (invalidFilenames.Any())
            {
                Console.WriteLine("Cannot find file(s):");
                foreach (string invalidFilename in invalidFilenames)
                {
                    Console.WriteLine(invalidFilename);
                }
                Console.WriteLine();

                writeUsage();
                return;
            }

            Action<string, string> logDebugMessage = (formatString, param0) =>
                {
                    if (verboseOutputRequested)
                    {
                        Console.WriteLine(formatString, param0);
                    }
                };

            var scriptCompiler = new ScriptCompiler();
            foreach (string filenameToCompile in filenames)
            {
                string scriptBaseName = Path.GetFileNameWithoutExtension(filenameToCompile);
                string sourceDirectory = Path.GetDirectoryName(filenameToCompile);
                string includeDirectory = sourceDirectory;
                string binaryOutputFilename = Path.Combine(outputDirectory, scriptBaseName + ".bin");
                string constantsOutputFilename = Path.Combine(sourceDirectory, "ref" + scriptBaseName + ".jms");

                using (FileStream fileToCompileStream = File.OpenRead(filenameToCompile))
                using (StreamReader streamReader = new StreamReader(fileToCompileStream))
                {
                    logDebugMessage("Compiling file: {0}", filenameToCompile);
                    scriptCompiler.Compile(includeDirectory, streamReader.ReadToEnd());
                    logDebugMessage("Finished compiling file: {0}", filenameToCompile);

                    logDebugMessage("Writing output binary file: {0}", binaryOutputFilename);
                    scriptCompiler.WriteBinary(binaryOutputFilename);
                    logDebugMessage("Finished writing output binary file: {0}", binaryOutputFilename);

                    logDebugMessage("Writing output constants file: {0}", constantsOutputFilename);
                    scriptCompiler.WriteConstants(constantsOutputFilename, scriptBaseName);
                    logDebugMessage("Finished writing output constants file: {0}", constantsOutputFilename);
                }
            }
        }
Example #28
0
        /// <summary>
        /// </summary>
        /// <param name="args">
        /// </param>
        private static void Main(string[] args)
        {
            bool processedargs = false;

            LogUtil.SetupConsoleLogging(LogLevel.Debug);
            LogUtil.SetupFileLogging("${basedir}/ZoneEngineLog.txt", LogLevel.Trace);

            SettingsOverride.LoadCustomSettings("NBug.ZoneEngine.Config");
            Settings.WriteLogToDisk = true;
            AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
            TaskScheduler.UnobservedTaskException      += Handler.UnobservedTaskException;

            csc = new ScriptCompiler();

            // TODO: ADD More Handlers.
            Console.Title = "CellAO " + AssemblyInfoclass.Title + " Console. Version: " + AssemblyInfoclass.Description
                            + " " + AssemblyInfoclass.AssemblyVersion + " " + AssemblyInfoclass.Trademark;

            ConsoleText ct = new ConsoleText();

            ct.TextRead("main.txt");
            Console.Write("Loading ");
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.Write(AssemblyInfoclass.Title + " ");
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(AssemblyInfoclass.Description);
            Console.ResetColor();
            Console.WriteLine("...");

            zoneServer = Container.GetInstance <ZoneServer>();
            int Port = Convert.ToInt32(Config.Instance.CurrentConfig.ZonePort);

            try
            {
                if (Config.Instance.CurrentConfig.ListenIP == "0.0.0.0")
                {
                    zoneServer.TcpEndPoint = new IPEndPoint(IPAddress.Any, Port);
                }
                else
                {
                    zoneServer.TcpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP);
                }
            }
            catch
            {
                ct.TextRead("ip_config_parse_error.txt");
                Console.ReadKey();
                return;
            }

            string consoleCommand;

            ct.TextRead("zone_consolecommands.txt");

            // removed CheckDBs here, added commands check and updatedb (updatedb will change to a versioning
            while (true)
            {
                if (!processedargs)
                {
                    if (args.Length == 1)
                    {
                        if (args[0].ToLower() == "/autostart")
                        {
                            ct.TextRead("autostart.txt");
                            csc.Compile(false);
                            StartTheServer();
                        }
                    }

                    processedargs = true;
                }

                Console.Write("\nServer Command >>");
                consoleCommand = Console.ReadLine();
                switch (consoleCommand.ToLower())
                {
                case "start":
                    if (zoneServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Zone Server is already running");
                        Console.ResetColor();
                        break;
                    }

                    // TODO: Add Sql Check.
                    csc.Compile(false);
                    StartTheServer();
                    break;

                case "startm":     // Multiple dll compile
                    if (zoneServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Zone Server is already running");
                        Console.ResetColor();
                        break;
                    }

                    // TODO: Add Sql Check.
                    csc.Compile(true);
                    StartTheServer();
                    break;

                case "stop":
                    if (!zoneServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Zone Server is not running");
                        Console.ResetColor();
                        break;
                    }

                    zoneServer.Stop();
                    break;

                case "check":
                case "updatedb":
                    using (SqlWrapper sqltester = new SqlWrapper())
                    {
                        sqltester.CheckDBs();
                        Console.ResetColor();
                    }

                    break;

                case "exit":
                case "quit":
                    if (zoneServer.Running)
                    {
                        zoneServer.Stop();
                    }

                    Process.GetCurrentProcess().Kill();
                    break;

                case "ls":     // list all available scripts, dont remove it since it does what it should
                    Console.WriteLine("Available scripts");

                    /* Old Lua way
                     * string[] files = Directory.GetFiles("Scripts");*/
                    try
                    {
                        string[] files = Directory.GetFiles("Scripts", "*.cs", SearchOption.AllDirectories);
                        if (files.Length == 0)
                        {
                            Console.WriteLine("No scripts were found.");
                            break;
                        }

                        Console.ForegroundColor = ConsoleColor.Green;
                        foreach (string s in files)
                        {
                            Console.WriteLine(s);
                        }
                    }
                    catch (Exception)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Scripts folder not found.");
                    }

                    Console.ResetColor();
                    break;

                case "ping":

                    // ChatCom.Server.Ping();
                    Console.WriteLine("Ping is disabled till we can fix it");
                    break;

                case "running":
                    if (zoneServer.Running)
                    {
                        Console.WriteLine("Zone Server is Running");
                        break;
                    }

                    Console.WriteLine("Zone Server not Running");
                    break;

                case "online":
                    if (zoneServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.White;
                        lock (zoneServer.Clients)
                        {
                            foreach (Client c in zoneServer.Clients)
                            {
                                Console.WriteLine("Character " + c.Character.Name + " online");
                            }
                        }

                        Console.ResetColor();
                    }

                    break;

                default:
                    ct.TextRead("zone_consolecmdsdefault.txt");
                    break;
                }
            }
        }
Example #29
0
        public bool Execute()
        {
            _output = new CompilationOutput(_test.TestContext.TestName);

            _options.References = _references;
            _options.Sources = _sources.Cast<IStreamSource>().ToList();
            _options.Resources = _resources.Cast<IStreamSource>().ToList();
            _options.DocCommentFile = _comments;
            _options.ScriptFile = _output;
            _options.IncludeResolver = _includeResolver;

            ScriptCompiler compiler = new ScriptCompiler(this);
            return compiler.Compile(_options);
        }
Example #30
0
        private void compileScriptToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.FixMasters();
            var r      = this.PluginTree.SelectedRecord as Record;
            var plugin = this.GetPluginFromNode(r);

            if (plugin == null || plugin.Parent == null)
            {
                return;
            }

            string errors;

            if (this.Selection.SelectedSubrecord && this.Selection.Record.Name != "SCPT")
            {
                var sr = this.SubrecordList.SubRecord;
                if (sr == null)
                {
                    return;
                }

                if (sr.Name != "SCTX")
                {
                    MessageBox.Show("You need to select a SCPT record or SCTX subrecord to compile", "Error");
                    return;
                }

                ScriptCompiler.Setup(plugin.Masters);
                Record r2;
                if (!ScriptCompiler.CompileResultScript(sr, out r2, out errors))
                {
                    MessageBox.Show("There were compilation errors:\n" + errors);
                }
                else
                {
                    var srs = r.SubRecords;
                    int i   = srs.IndexOf(sr);
                    if (i >= 0)
                    {
                        while (i > 0 && (srs[i - 1].Name == "SCDA" || srs[i - 1].Name == "SCHR"))
                        {
                            srs.RemoveAt(--i);
                        }

                        while (i < srs.Count && (srs[i].Name == "SCTX" || srs[i].Name == "SLSD" || srs[i].Name == "SCVR" || srs[i].Name == "SCRO" || srs[i].Name == "SCRV"))
                        {
                            srs.RemoveAt(i);
                        }

                        srs.InsertRange(i, r2.SubRecords);
                        this.RebuildSelection();
                        this.PluginTree.RefreshObject(r);
                    }
                }

                return;
            }

            if (r == null || (r.Name != "SCPT"))
            {
                MessageBox.Show("You need to select a SCPT record or SCTX subrecord to compile", "Error");
                return;
            }

            ScriptCompiler.Setup(plugin.Masters);
            if (!ScriptCompiler.Compile(r, out errors))
            {
                MessageBox.Show("There were compilation errors:\n" + errors);
            }
            else
            {
                this.RebuildSelection();
                this.PluginTree.RebuildObjects();
            }
        }
        private bool Compile() {
            CompilerOptions options = new CompilerOptions();
            options.DebugFlavor = DebugFlavor;
            if (DebugFlavor) {
                options.IncludeTests = IncludeTests;
            }
            else {
                options.Minimize = Minimize;
            }
            options.Defines = GetDefines();
            options.References = GetReferences();
            options.Sources = GetSources(_sources);
            options.Resources = GetResources(_resources);
            if (_template != null) {
                options.TemplateFile = new TaskItemInputStreamSource(_template, "Template");
            }
            if (_docCommentFile != null) {
                options.DocCommentFile = new TaskItemInputStreamSource(_docCommentFile, "DocComment");
            }

            ITaskItem scriptTaskItem = new TaskItem(OutputPath);
            options.ScriptFile = new TaskItemOutputStreamSource(scriptTaskItem);

            string errorMessage = String.Empty;
            if (options.Validate(out errorMessage) == false) {
                Log.LogError(errorMessage);
                return false;
            }

            ScriptCompiler compiler = new ScriptCompiler(this);
            compiler.Compile(options);
            if (_hasErrors == false) {
                _script = scriptTaskItem;

                string projectName = (_projectPath != null) ? Path.GetFileNameWithoutExtension(_projectPath) : String.Empty;
                string scriptFileName = Path.GetFileName(scriptTaskItem.ItemSpec);
                string scriptPath = Path.GetFullPath(scriptTaskItem.ItemSpec);

                Log.LogMessage(MessageImportance.High, "{0} -> {1} ({2})", projectName, scriptFileName, scriptPath);
            }
            else {
                return false;
            }

            return true;
        }
Example #32
0
        protected IMohidTask LoadScript(FileName script_file_path)
        {
            ScriptInfo si = scripts.Find(delegate(ScriptInfo info) { return info.ScriptFile.FullPath == script_file_path.FullPath;  });
             if (si != null)
             {
            si.Interface.Reset();
            return si.Interface;
             }
             else
             {
            ScriptCompiler sc = new ScriptCompiler();
            Assembly ass;
            try
            {
               ass = sc.Compile(script_file_path);
            }
            catch (Exception ex)
            {
               throw new Exception("Error when trying to compile " + script_file_path.FullPath + ". The message returned was " + ex.Message);
            }

            si = new ScriptInfo();
            si.ScriptFile = script_file_path;
            si.Interface = (IMohidTask)sc.FindScriptInterface("IMohidTask", ass);

            scripts.Add(si);

            return si.Interface;
             }
        }
Example #33
0
        private void compileAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string errors;
            string thingy = string.Empty;
            int    count = 0, failed = 0, failed2 = 0;
            int    size;

            this.FixMasters();
            var plugin = this.GetPluginFromNode(this.PluginTree.SelectedRecord);

            if (plugin == null)
            {
                return;
            }

            ScriptCompiler.Setup(plugin.Masters);
            foreach (Rec rec in plugin.Records)
            {
                var gr = rec as GroupRecord;
                if (gr == null)
                {
                    continue;
                }

                if (gr.ContentsType == "SCPT")
                {
                    foreach (Record r in gr.Records)
                    {
                        count++;
                        size = 0;
                        foreach (SubRecord sr in r.SubRecords)
                        {
                            if (sr.Name == "SCDA")
                            {
                                size = (int)sr.Size;
                                break;
                            }
                        }

                        if (!ScriptCompiler.Compile(r, out errors))
                        {
                            failed++;
                            thingy += r.DescriptiveName + Environment.NewLine + errors + Environment.NewLine + Environment.NewLine;
                        }
                        else
                        {
                            foreach (SubRecord sr in r.SubRecords)
                            {
                                if (sr.Name == "SCDA")
                                {
                                    if (sr.Size != size)
                                    {
                                        failed2++;
                                        thingy += r.DescriptiveName + Environment.NewLine + "Size changed from " + size + " to " + sr.Size + Environment.NewLine + Environment.NewLine;
                                    }

                                    break;
                                }
                            }
                        }
                    }
                }
            }

            thingy += Environment.NewLine + Environment.NewLine + "Final results: " + count + "/" + failed + "/" + failed2;
            File.WriteAllText("script results.txt", thingy);
        }
        private bool Compile(IEnumerable<ITaskItem> sourceItems, IEnumerable<ITaskItem> resourceItems, string locale)
        {
            ITaskItem scriptTaskItem;

            CompilerOptions options =
                CreateOptions(sourceItems, resourceItems, locale,
                              /* includeTests */ false, /* minimize */ false,
                              out scriptTaskItem);

            string errorMessage = String.Empty;
            if (options.Validate(out errorMessage) == false) {
                Log.LogError(errorMessage);
                return false;
            }

            ScriptCompiler compiler = new ScriptCompiler(this);
            compiler.Compile(options);
            if (_hasErrors == false) {
                // Only copy references once (when building language neutral scripts)
                bool copyReferences = String.IsNullOrEmpty(locale) && CopyReferences;

                OnScriptFileGenerated(scriptTaskItem, options, copyReferences);
                if (_hasErrors) {
                    return false;
                }
            }
            else {
                return false;
            }

            if (options.HasTestTypes) {
                CompilerOptions testOptions =
                    CreateOptions(sourceItems, resourceItems, locale,
                                  /* includeTests */ true, /* minimize */ false,
                                  out scriptTaskItem);
                ScriptCompiler testCompiler = new ScriptCompiler(this);
                testCompiler.Compile(testOptions);
                if (_hasErrors == false) {
                    OnScriptFileGenerated(scriptTaskItem, testOptions, /* copyReferences */ false);
                }
                else {
                    return false;
                }
            }

            if (_minimize) {
                CompilerOptions minimizeOptions =
                    CreateOptions(sourceItems, resourceItems, locale,
                                  /* includeTests */ false, /* minimize */ true,
                                  out scriptTaskItem);
                ScriptCompiler minimizingCompiler = new ScriptCompiler(this);
                minimizingCompiler.Compile(minimizeOptions);
                if (_hasErrors == false) {
                    if (Crunch) {
                        ExecuteCruncher(scriptTaskItem);
                    }

                    OnScriptFileGenerated(scriptTaskItem, minimizeOptions, /* copyReferences */ false);
                }
                else {
                    return false;
                }
            }

            return true;
        }
Example #35
0
        public static void Run([Alias("file")] string filename)
        {
            //GameAssetStorage storage = new GameAssetStorage();
            //GameAssetKitchen kitchen = new GameAssetKitchen(storage);
            ////object obj = kitchen.Cook(@"Asset\VisualNovelUI.asset");
            ////GameAssetRecipe r = null;
            ////using (var fs = new FileStream(@"Asset\PSDToUI.recipe", FileMode.Open, FileAccess.Read))
            ////    r = GameAssetRecipe.Deserialize(fs);
            //GameAssetRecipe r = new GameAssetRecipe();
            //using (var fs = new FileStream(@"Asset\PSDToUI.recipe", FileMode.Create, FileAccess.Write))
            //    GameAssetRecipe.Serialize(fs, r);

            Block code = new Block(new Statement[]
            {
                new Function("Sum1To100", null, new ScriptObjectType[] { ScriptObjectType.Int }, new Statement[]
                {
                    new DeclareVariable("result", ScriptObjectType.Int),
                    new DeclareVariable("i", ScriptObjectType.Int),
                    new CallNativeFunction("Print", new ConstantExpression("Hello Malthm !")),
                    new AssignmentOperator(new VariableExpression("result"), new ConstantExpression(0)),
                    new AssignmentOperator(new VariableExpression("i"), new ConstantExpression(0)),
                    new While(new InequalityOperator(new VariableExpression("i"), new ConstantExpression(101)), new Statement[]
                    {
                        new AssignmentOperator(new VariableExpression("result"), new AdditionOperator(new VariableExpression("result"), new VariableExpression("i"))),
                        new AssignmentOperator(new VariableExpression("i"), new AdditionOperator(new VariableExpression("i"), new ConstantExpression(1))),
                    }),
                    new Return(new VariableExpression("result"))
                }),

                new Function("Factorial", new DeclareVariable[] { new DeclareVariable("N", ScriptObjectType.Int) }, new ScriptObjectType[] { ScriptObjectType.Int }, new Statement[]
                {
                    new If(new EqualityOperator(new VariableExpression("N"), new ConstantExpression(0)), new Statement[]
                    {
                        new Return(new ConstantExpression(0))
                    })
                    {
                        Else = new If(new EqualityOperator(new VariableExpression("N"), new ConstantExpression(1)), new Statement[]
                        {
                            new Return(new ConstantExpression(1))
                        })
                        {
                            Else = new Block(new Statement[]
                            {
                                new Return(new MultiplicationOperator(new VariableExpression("N"), new CallScriptFunction("Factorial", new Expression[] { new SubtractionOperator(new VariableExpression("N"), new ConstantExpression(1)) })))
                            })
                        }
                    },
                })
            });

            ScriptNativeFunctionTable.Rebuild();
            ScriptCompiler compiler = new ScriptCompiler();
            FileStream     fs       = new FileStream("Script.ab", FileMode.Create, FileAccess.Write);

            string text;

            compiler.Compile(code, out text);
            //ScriptWriter writer = new ScriptWriter();
            //string text;
            //writer.Write(new Asset.AssetStreamWriter(fs, null), compiler.Compile(code, out text));

            fs.Close();
        }
Example #36
0
 protected IMohidTask LoadScript(FileName script_file_path)
 {
     ScriptInfo si = scripts.Find(delegate(ScriptInfo info) { return info.ScriptFile.FullPath == script_file_path.FullPath;  });
      if (si != null)
      {
     si.Interface.Reset();
     return si.Interface;
      }
      else
      {
     ScriptCompiler sc = new ScriptCompiler();
     Assembly ass = sc.Compile(script_file_path);
     si = new ScriptInfo();
     si.ScriptFile = script_file_path;
     si.Interface = (IMohidTask)sc.FindScriptInterface("IMohidTask", ass);
     return si.Interface;
      }
 }
        private bool Compile(string name, IEnumerable<ITaskItem> sourceItems, IEnumerable<ITaskItem> resourceItems, string locale)
        {
            ITaskItem scriptTaskItem;

            CompilerOptions debugOptions =
                CreateOptions(name, sourceItems, resourceItems, locale,
                              /* debug */ true, /* includeTests */ false, /* minimize */ false,
                              out scriptTaskItem);

            string errorMessage = String.Empty;
            if (debugOptions.Validate(out errorMessage) == false) {
                Log.LogError(errorMessage);
                return false;
            }

            ScriptCompiler debugCompiler = new ScriptCompiler(this);
            debugCompiler.Compile(debugOptions);
            if (_hasErrors == false) {
                // Only copy references once (when building language neutral scripts)
                bool copyReferences = String.IsNullOrEmpty(locale) && CopyReferences;

                OnScriptFileGenerated(scriptTaskItem, debugOptions, copyReferences);
                if (_hasErrors) {
                    return false;
                }
            }
            else {
                return false;
            }

            if (debugOptions.HasTestTypes) {
                CompilerOptions testOptions =
                    CreateOptions(name, sourceItems, resourceItems, locale,
                                  /* debug */ true, /* includeTests */ true, /* minimize */ false,
                                  out scriptTaskItem);
                ScriptCompiler testCompiler = new ScriptCompiler(this);
                testCompiler.Compile(testOptions);
                if (_hasErrors == false) {
                    OnScriptFileGenerated(scriptTaskItem, testOptions, /* copyReferences */ false);
                }
                else {
                    return false;
                }
            }

            CompilerOptions releaseOptions =
                CreateOptions(name, sourceItems, resourceItems, locale,
                              /* debug */ false, /* includeTests */ false, /* minimize */ true,
                              out scriptTaskItem);
            ScriptCompiler releaseCompiler = new ScriptCompiler(this);
            releaseCompiler.Compile(releaseOptions);
            if (_hasErrors == false) {
                OnScriptFileGenerated(scriptTaskItem, releaseOptions, /* copyReferences */ false);
            }
            else {
                return false;
            }

            return true;
        }
Example #38
0
        private bool Compile(string name, IEnumerable <ITaskItem> sourceItems, IEnumerable <ITaskItem> resourceItems, string locale)
        {
            ITaskItem scriptTaskItem;

            CompilerOptions debugOptions =
                CreateOptions(name, sourceItems, resourceItems, locale,
                              /* debug */ true, /* includeTests */ false, /* minimize */ false,
                              out scriptTaskItem);

            string errorMessage = String.Empty;

            if (debugOptions.Validate(out errorMessage) == false)
            {
                Log.LogError(errorMessage);
                return(false);
            }

            ScriptCompiler debugCompiler = new ScriptCompiler(this);

            debugCompiler.Compile(debugOptions);
            if (_hasErrors == false)
            {
                // Only copy references once (when building language neutral scripts)
                bool copyReferences = String.IsNullOrEmpty(locale) && CopyReferences;

                OnScriptFileGenerated(scriptTaskItem, debugOptions, copyReferences);
                if (_hasErrors)
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }

            if (debugOptions.HasTestTypes)
            {
                CompilerOptions testOptions =
                    CreateOptions(name, sourceItems, resourceItems, locale,
                                  /* debug */ true, /* includeTests */ true, /* minimize */ false,
                                  out scriptTaskItem);
                ScriptCompiler testCompiler = new ScriptCompiler(this);
                testCompiler.Compile(testOptions);
                if (_hasErrors == false)
                {
                    OnScriptFileGenerated(scriptTaskItem, testOptions, /* copyReferences */ false);
                }
                else
                {
                    return(false);
                }
            }

            CompilerOptions releaseOptions =
                CreateOptions(name, sourceItems, resourceItems, locale,
                              /* debug */ false, /* includeTests */ false, /* minimize */ true,
                              out scriptTaskItem);
            ScriptCompiler releaseCompiler = new ScriptCompiler(this);

            releaseCompiler.Compile(releaseOptions);
            if (_hasErrors == false)
            {
                OnScriptFileGenerated(scriptTaskItem, releaseOptions, /* copyReferences */ false);
            }
            else
            {
                return(false);
            }

            return(true);
        }