Example #1
0
        public static void LoadXml(string xml, Action <string, InvocationDelegate> callback)
        {
            LoadXmlNode(xml, new Action <string, XmlNode>((name, node) =>
            {
                XmlExpressionReader reader = new XmlExpressionReader();
                XmlNode firstChild         = null;
                foreach (XmlNode child in node.ChildNodes)
                {
                    if (child.NodeType == XmlNodeType.Element)
                    {
                        firstChild = child;
                        break;
                    }
                }
                //convert xml node to expression
                Expression expr = reader.Read(firstChild);

                CompileContext compile = new CompileContext();

                //compile expression
                var eval = compile.Compile(expr);

                callback(name, eval);
            }));
        }
Example #2
0
        internal CompileContext CreateCompileContext(string pattern)
        {
            var context = new CompileContext(pattern)
            {
                Options           = Options.ToPatternOptions(),
                JitCompileOptions = Options.ToJitCompileOptions()
            };

            if (_newLine != null && _newLine != PcreNewLine.Default)
            {
                context.NewLine = (NewLine)_newLine;
            }

            if (_backslashR != null && _backslashR != PcreBackslashR.Default)
            {
                context.BackslashR = (BackslashR)_backslashR;
            }

            if (_parensLimit != null)
            {
                context.ParensNestLimit = _parensLimit.Value;
            }

            return(context);
        }
Example #3
0
        public override void Run(CompileContext c)
        {
            CompileErrors = new List<Error>();
            Process = new Process();

            if (Metadata.ReadOutput)
            {
                Process.StartInfo = new ProcessStartInfo
                    {
                        RedirectStandardOutput = true,
                        RedirectStandardInput = true,
                        RedirectStandardError = true,
                        UseShellExecute = false,
                        CreateNoWindow = true
                    };
            }

            var args = GameConfigurationManager.SubstituteValues(GetParameterString(), c.MapFile); ;

            Process.StartInfo.FileName = GameConfigurationManager.SubstituteValues(Metadata.Path);
            Process.StartInfo.Arguments = string.Join(" ", args);
            Process.StartInfo.WorkingDirectory = runningDirectory;

            Process.Start();
            Process.PriorityClass = ProcessPriorityClass.BelowNormal;

            if (Metadata.ReadOutput)
                readOutput();
        }
Example #4
0
        public CompileResult Compile(string source, CompileContext context)
        {
            var sourceFile = context.RootDirectory.GetFile(context.SourceFilePath);
            lock (_lock)
            {
                rootDirectory = sourceFile.Directory;
                Initialize();

                StartRecordingOpenedFiles();

                try
                {
                    var compilerOptions = GetCompilerOptions(sourceFile);
                    var css = (string)sassCompiler.compile(source, compilerOptions);
                    return new CompileResult(css, importedFilePaths);
                }
                catch (Exception e)
                {
                    // Provide more information for SassSyntaxErrors
                    if (e.Message == "Sass::SyntaxError")
                    {
                        throw CreateSassSyntaxError(sourceFile, e);
                    }
                    else
                    {
                        throw;
                    }
                }
                finally
                {
                    StopRecordingOpenedFiles();
                }
            }
        }
    public override void GenTyped(CompileContext compileContext)
    {
        JSType TreeType = this.TreeType;

        ((ExpressionNode)base.Children[0]).GenTyped(compileContext, TreeType);
        ((ExpressionNode)base.Children[1]).GenTyped(compileContext, TreeType);
        this.GenTypedOp(compileContext);
    }
        public TypeSymbol GetTypeSymbolWithoutRedirect(ITypeSymbol type)
        {
            TypeSymbol typeSymbol = CompileContext.GetTypeSymbol(type, this);

            OnSymbolRetrieved(typeSymbol);

            return(typeSymbol);
        }
Example #7
0
 public override Intermediate.IRNode Emit(CompileContext context, Model.Scope scope, Target target)
 {
     var r = new TransientNode();
     if (_struct.size == 0) throw new InternalError("Struct size not yet determined");
     r.AddInstruction(Instructions.SET, target.GetOperand(TargetUsage.Push),
         Constant((ushort)_struct.size));
     return r;
 }
Example #8
0
		/// <summary>
		/// Compiles the specified JavaScript file via Babel
		/// </summary>
		/// <param name="source">The source.</param>
		/// <param name="context">The context.</param>
		/// <returns>JavaScript</returns>
		public CompileResult Compile(string source, CompileContext context)
		{
			var output = _environment.Babel.Transform(
				source, 
				Path.GetFileName(context.SourceFilePath)
			);
			return new CompileResult(output, Enumerable.Empty<string>());
		}
Example #9
0
 public override void Compile(CompileContext context)
 {
     foreach (Expression exp in ChildNodes)
     {
         exp.Compile(context);
     }
     context.ILGenerator.Emit(OpCodes.Newobj, _constructor);
 }
Example #10
0
        public Symbol GetSymbolNoRedirect(ISymbol sourceSymbol)
        {
            Symbol symbol = CompileContext.GetSymbol(sourceSymbol, this);

            OnSymbolRetrieved(symbol);

            return(symbol);
        }
Example #11
0
        /// <summary>
        /// Create a compilation context.
        /// </summary>
        /// <param name="name">Unique key of the template</param>
        /// <param name="scope">The template data.</param>
        /// <param name="environment"></param>
        /// <returns></returns>
        private static CompileContext GenerateContext(this IHostEnvironment environment, string name, IVariableScope scope)
        {
            var ctx = new CompileContext(environment);

            ctx.Name = name;
            ctx.Data = scope ?? ctx.CreateVariableScope();
            return(ctx);
        }
Example #12
0
        public object ReadExpr(FSMContext context, XmlNode exprNode, bool isBlock)
        {
            CompileContext ctx = new CompileContext(new FSMExpressionContextAdapter(context));

            var expr = exprReader.Read(exprNode, isBlock, ctx);

            return(expr);
        }
Example #13
0
        public static Neo.ASML.Node.ASMProject Compile(Microsoft.CodeAnalysis.SyntaxNode node)
        {
            var            proj    = new Neo.ASML.Node.ASMProject();
            CompileContext context = new CompileContext();

            CompileNode(context, proj, node);
            return(proj);
        }
Example #14
0
    internal override void GenLazyEval(CompileContext compileContext, Label lblTrue, Label lblFalse)
    {
        Label lblPartTwo = compileContext.gen.DefineLabel();

        ((ExpressionNode)base.Children[0]).GenLazyEval(compileContext, lblPartTwo, lblFalse);
        compileContext.gen.MarkLabel(lblPartTwo);
        ((ExpressionNode)base.Children[1]).GenLazyEval(compileContext, lblTrue, lblFalse);
    }
Example #15
0
        public override void Run(CompileContext context)
        {
            CompilePalLogger.LogLine("\nCompilePal - Nav Generator");
            mapname      = System.IO.Path.GetFileName(context.BSPFile).Replace(".bsp", "");
            mapnav       = context.CopyLocation.Replace(".bsp", ".nav");
            mapcfg       = context.Configuration.GameFolder + "/cfg/" + mapname + ".cfg";
            mapCFGBackup = context.Configuration.GameFolder + "/cfg/" + mapname + "_cpalbackup.cfg";

            hidden = GetParameterString().Contains("-hidden");

            string args = "-game \"" + context.Configuration.GameFolder + "\" -windowed -novid -nosound +sv_cheats 1 +map " + mapname;

            if (hidden)
            {
                args += " -noborder -x 4000 -y 2000";
            }

            var startInfo = new ProcessStartInfo(context.Configuration.GameEXE, args);

            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow  = false;

            CompilePalLogger.LogLine("Generating...");
            if (File.Exists(mapcfg))
            {
                if (File.Exists(mapCFGBackup))
                {
                    System.IO.File.Delete(mapCFGBackup);
                }
                System.IO.File.Move(mapcfg, mapCFGBackup);
            }

            System.IO.File.Create(mapcfg).Dispose();
            TextWriter tw = new StreamWriter(mapcfg);

            tw.WriteLine("nav_generate");
            tw.Close();

            Process = new Process {
                StartInfo = startInfo
            };
            Process.Start();

            FileSystemWatcher fw = new FileSystemWatcher();

            fw.Path                = System.IO.Path.GetDirectoryName(mapnav);
            fw.Filter              = "*.nav";
            fw.NotifyFilter        = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            fw.Changed            += new FileSystemEventHandler(fileSystemWatcher_NavCreated);
            fw.Created            += new FileSystemEventHandler(fileSystemWatcher_NavCreated);
            fw.EnableRaisingEvents = true;

            Process.WaitForExit();
            fw.Dispose();

            cleanUp();
            CompilePalLogger.LogLine("nav file complete!");
        }
        public override void Compile(CompileContext context)
        {
            if (Expression is StringExpression stringExpression)
            {
                context.AddWarning(this, $"This string is unused, did you mean to call 'say \"{stringExpression}\"'");
            }

            Expression.Compile(context);
        }
Example #17
0
 internal void GenCreate(CompileContext compileContext)
 {
     for (int i = 0; i < this.varNames.Length; i++)
     {
         compileContext.gen.Emit(OpCodes.Ldarg_0);
         compileContext.gen.Emit(OpCodes.Ldstr, this.varNames[i]);
         compileContext.gen.EmitCallV(CompileContext.mi_CreateMutableBinding);
     }
 }
Example #18
0
 public override void GenTyped(CompileContext compileContext)
 {
     ((ExpressionNode)base.Children[0]).GenTyped(compileContext, JSType.Number);
     compileContext.gen.EmitCallV(CompileContext.fnc_Utilities_JSToInt32);
     ((ExpressionNode)base.Children[1]).GenTyped(compileContext, JSType.Number);
     compileContext.gen.EmitCallV(CompileContext.fnc_Utilities_JSToInt32);
     compileContext.gen.Emit(this._op);
     compileContext.gen.Emit(OpCodes.Conv_R8);
 }
Example #19
0
        /// <summary>
        /// Compiles the specified JavaScript file via Babel
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="context">The context.</param>
        /// <returns>JavaScript</returns>
        public CompileResult Compile(string source, CompileContext context)
        {
            var output = _environment.Babel.Transform(
                source,
                Path.GetFileName(context.SourceFilePath)
                );

            return(new CompileResult(output, Enumerable.Empty <string>()));
        }
Example #20
0
        public TypeSymbol GetTypeSymbol(SpecialType type)
        {
            TypeSymbol typeSymbol = CompileContext.GetTypeSymbol(type, this);

            typeSymbol = (TypeSymbol)RedirectTypeSymbol(typeSymbol);
            OnSymbolRetrieved(typeSymbol);

            return(typeSymbol);
        }
Example #21
0
 void processImport(CompileContext ctx, Value s, Env env)
 {
     for (Value codeCons = s.Cdr; !codeCons.IsNil; codeCons = codeCons.Cdr)
     {
         var code      = codeCons.Car;
         var importSet = parseImportSet(code);
         importSet.Module.ImportToEnv(env, importSet);
     }
 }
    protected override void EmitClassDefinition(CodeWriter writer, CompileContext context)
    {
        string attribute = $"[FlatBufferStruct]";

        writer.AppendSummaryComment(this.Documentation);
        writer.AppendLine(attribute);
        writer.AppendLine("[System.Runtime.CompilerServices.CompilerGenerated]");
        writer.AppendLine($"public partial class {this.Name}");
    }
Example #23
0
        //===================================================================
        // define-library
        //===================================================================
        void processDefineLibrary(CompileContext ctx, Value s)
        {
            Value _, moduleNameList, rest;

            Value.Bind2Rest(s, out _, out moduleNameList, out rest);
            string moduleName = Module.GetModuleName(moduleNameList);

            var module = new Module(moduleName);
            var env    = new Env(null);

            for (Value codeCons = rest; !codeCons.IsNil; codeCons = codeCons.Cdr)
            {
                var code = codeCons.Car;
                switch (code.Car.AsSymbol.ToString())
                {
                case "import":
                {
                    processImport(ctx, code, env);
                }
                break;

                case "export":
                {
                    for (Value sym = code.Cdr; !sym.IsNil; sym = sym.Cdr)
                    {
                        module.Export(sym.Car.AsSymbol);
                    }
                }
                break;

                case "include":
                case "include-ci":
                    break;

                case "begin":
                {
                    var compiler = new Compiler(vm_, env);

                    for (Value c = code.Cdr; !c.IsNil; c = c.Cdr)
                    {
                        var lmd     = compiler.Compile(c.Car);
                        var closure = new Closure(lmd, env);
                        var result  = vm_.Eval.Run(closure);
                    }
                }
                break;

                default:
                    throw new LispException($"Invalid define-library command {code}");
                }
            }

            module.ExportFromEnv(env);

            vm_.Modules[moduleName] = module;
        }
    internal override void GenStatementCode(CompileContext compileContext, bool bGenDebug)
    {
        Label lblTop  = compileContext.gen.DefineLabel();
        Label lblCond = base.continuedest = compileContext.gen.DefineLabel();

        compileContext.gen.MarkLabel(lblTop);
        ((StatementNode)base.Children[0]).GenCode(compileContext);
        compileContext.gen.MarkLabel(lblCond);
        ((ExpressionNode)base.Children[1]).GenLazyEval(compileContext, lblTop, base.breakdest);
    }
Example #25
0
        private IEvaluator CreateEvaluator(Type type, MethodInfo execute, CompileContext compileContext)
        {
            var instance    = CreateInstance(type, compileContext);
            var ins         = Expression.Parameter(typeof(object), "proxy");
            var state       = Expression.Parameter(typeof(object), "state");
            var callExecute = Expression.Call(Expression.Convert(ins, type), execute, state);
            var func        = Expression.Lambda <Func <object, object, object> >(callExecute, "Evaluate", new[] { ins, state }).Compile();

            return(compileContext.Cacheable ? (IEvaluator) new CachableEvaluator(instance, func) : new Evaluator(instance, func));
        }
Example #26
0
    public override void GenTyped(CompileContext compileContext)
    {
        LocalBuilder l = compileContext.gen.DeclareLocal(typeof(string));

        ((ExpressionNode)base.Children[0]).GenTyped(compileContext, JSType.String);
        compileContext.gen.Emit(OpCodes.Stloc, l.LocalIndex);
        ((ExpressionNode)base.Children[1]).GenCode(compileContext);
        compileContext.gen.Emit(OpCodes.Ldloc, l.LocalIndex);
        compileContext.gen.EmitCallV(CompileContext.mi_JSValue_HasProperty_in);
    }
Example #27
0
 internal override void GenStatementCode(CompileContext compileContext, bool bGenDebug)
 {
     if (this.ChildCount != 0)
     {
         foreach (StatementNode n in base.Children)
         {
             n.GenCode(compileContext);
         }
     }
 }
Example #28
0
        private static bool Compile <TModel>(CompileContext compileContext, string templatePath, Options options, Result result)
        {
            DateTime startTime = DateTime.Now;

            if (options.DiagnosticLevel == DiagnosticLevel.Diagnostics)
            {
                foreach (var reference in compileContext.MetadataReferenceManager.References)
                {
                    result.AddDiagnostic(new Diagnostic(DiagnosticSeverity.Info, Result.Sources.Compiler, "Diagnostic", $"Referencing assembly: {reference.Display}", -1, -1));
                }
            }
            string templateName = MakeTemplateName(options, templatePath);

            string assemblyPath     = MakeAssemblyPath(options, templateName);
            var    referenceManager = compileContext.MetadataReferenceManager;
            CSharpCompilationOptions compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            CSharpCompilation        compilation        = CSharpCompilation.Create(templateName)
                                                          .AddReferences(referenceManager.References)
                                                          .AddSyntaxTrees(compileContext.CompilationUnit.SyntaxTree)
                                                          .WithOptions(compilationOptions);

            try
            {
                var emitResult = compilation.Emit(assemblyPath);

                DateTime compileTime = DateTime.Now;

                result.CompileTime = compileTime - startTime;

                foreach (var diagnostic in emitResult.Diagnostics)
                {
                    var location = diagnostic.Location.GetMappedLineSpan();
                    switch (diagnostic.Severity)
                    {
                    case Microsoft.CodeAnalysis.DiagnosticSeverity.Error:
                        result.AddDiagnostic(new Diagnostic(DiagnosticSeverity.Error, Result.Sources.Roslyn, "error", diagnostic.GetMessage(), location.StartLinePosition.Line + 1, -1));
                        break;

                    case Microsoft.CodeAnalysis.DiagnosticSeverity.Warning:
                        result.AddDiagnostic(new Diagnostic(DiagnosticSeverity.Warning, Result.Sources.Roslyn, "warning", diagnostic.GetMessage(), location.StartLinePosition.Line + 1, -1));
                        break;

                    case Microsoft.CodeAnalysis.DiagnosticSeverity.Info:
                        result.AddDiagnostic(new Diagnostic(DiagnosticSeverity.Info, Result.Sources.Roslyn, "info", diagnostic.GetMessage(), location.StartLinePosition.Line + 1, -1));
                        break;
                    }
                }
                return(emitResult.Success);
            }
            catch (Exception e)
            {
                result.AddDiagnostic(new Diagnostic(DiagnosticSeverity.Error, Result.Sources.Roslyn, "emit", e.Message));
                return(false);
            }
        }
Example #29
0
        public override void Run(CompileContext context)
        {
            vbspInfo      = context.Configuration.VBSPInfo;
            bspFile       = context.CopyLocation;
            CompileErrors = new List <Error>();

            try
            {
                CompilePalLogger.LogLine("\nCompilePalMulti - Cubemap Generator");

                if (!File.Exists(context.CopyLocation))
                {
                    throw new FileNotFoundException();
                }

                hidden = GetParameterString().Contains("-hidden");
                FetchHDRLevels();

                string mapname = System.IO.Path.GetFileName(context.CopyLocation).Replace(".bsp", "");

                string args = "-steam -game \"" + context.Configuration.GameFolder + "\" -windowed -novid -nosound +mat_specular 0 %HDRevel% +map " + mapname + " -buildcubemaps";

                if (hidden)
                {
                    args += " -noborder -x 4000 -y 2000";
                }

                if (HDR && LDR)
                {
                    CompilePalLogger.LogLine("Map requires two sets of cubemaps");

                    CompilePalLogger.LogLine("Compiling LDR cubemaps...");
                    RunCubemaps(context.Configuration.GameEXE, args.Replace("%HDRevel%", "+mat_hdr_level 0"));

                    CompilePalLogger.LogLine("Compiling HDR cubemaps...");
                    RunCubemaps(context.Configuration.GameEXE, args.Replace("%HDRevel%", "+mat_hdr_level 2"));
                }
                else
                {
                    CompilePalLogger.LogLine("Map requires one set of cubemaps");
                    CompilePalLogger.LogLine("Compiling cubemaps...");
                    RunCubemaps(context.Configuration.GameEXE, args.Replace("%HDRevel%", ""));
                }
                CompilePalLogger.LogLine("Cubemaps compiled");
            }
            catch (FileNotFoundException)
            {
                CompilePalLogger.LogCompileError($"Could not find file: {context.CopyLocation}", new Error($"Could not find file: {context.CopyLocation}", ErrorSeverity.Error));
            }
            catch (Exception exception)
            {
                CompilePalLogger.LogLine("Something broke:");
                CompilePalLogger.LogCompileError($"{exception}\n", new Error(exception.ToString(), "CompilePalMulti Internal Error", ErrorSeverity.FatalError));
            }
        }
Example #30
0
        public override void GatherSymbols(CompileContext context, Model.Scope enclosingScope)
        {
            base.GatherSymbols(context, enclosingScope);
            staticLabel = Intermediate.Label.Make("_STRING");

            var data = new List<Intermediate.Operand>();
            data.Add(Constant((ushort)value.Length));
            foreach (var c in value)
                data.Add(Constant((ushort)c));
            context.AddData(staticLabel, data);
        }
Example #31
0
        public Symbol GetSymbol(ISymbol sourceSymbol)
        {
            Symbol symbol = CompileContext.GetSymbol(sourceSymbol, this);

            symbol = RedirectTypeSymbol(symbol);
            symbol = RedirectParameterSymbol(symbol);
            symbol = RedirectMethodSymbol(symbol);
            OnSymbolRetrieved(symbol);

            return(symbol);
        }
        public void Run(CompileContext context)
        {
            var settings = new BinaryWriter.BinaryWriterSettings();

            if (context.Options.CertificateThumbprint != null)
                settings.Certificate = FindCertificate(context.Options.CertificateThumbprint);

            var writer = new BinaryWriter(context.Output, settings);
            writer.Descriptions.Add(context.Description);
            writer.Write();
        }
Example #33
0
        internal override int?OnDetermineDecimalPlaces(CompileContext context)
        {
            // Return at least the default number of decimal places.

            int?suggested = base.OnDetermineDecimalPlaces(context);
            int defaultDp = context.GetDecimalPlaces(ResultType);

            int result = Math.Max(suggested ?? defaultDp, defaultDp);

            return(result);
        }
 /// <summary>
 /// Copies a range of elements from an <see cref="TemplateContext"/> starting at the first element and pastes them into another <see cref="CompileContext"/> starting at the first element.
 /// </summary>
 /// <param name="ctx1">The <see cref="TemplateContext"/> that contains the data to copy.</param>
 /// <param name="ctx2">The <see cref="CompileContext"/> that receives the data.</param>
 public static void CopyTo(this TemplateContext ctx1, CompileContext ctx2)
 {
     if (ctx1 != null && ctx2 != null)
     {
         ctx2.Data            = ctx1.TempData;
         ctx2.CurrentPath     = ctx1.CurrentPath;
         ctx2.Charset         = ctx1.Charset;
         ctx2.StripWhiteSpace = ctx1.StripWhiteSpace;
         ctx2.ThrowExceptions = ctx1.ThrowExceptions;
     }
 }
Example #35
0
 public override Intermediate.IRNode Emit(CompileContext context, Model.Scope scope, Target target)
 {
     Model.Label destination = null;
     foreach (var _label in scope.activeFunction.function.labels)
         if (_label.declaredName == label) destination = _label;
     if (destination == null) context.ReportError(this, "Unknown label - " + label);
     var r = new StatementNode();
     if (destination != null)
         r.AddInstruction(Instructions.SET, Operand("PC"), Label(destination.realName));
     return r;
 }
Example #36
0
 internal override void GenStatementCode(CompileContext compileContext, bool bGenDebug)
 {
     if (bGenDebug)
     {
         base.GenDebugWrap(compileContext, new Action <CompileContext>(this.GenStatementCode));
     }
     else
     {
         this.GenStatementCode(compileContext);
     }
 }
Example #37
0
 internal void GenTyped(CompileContext compileContext, JSType aJType)
 {
     if (this.TreeType == aJType)
     {
         this.GenTyped(compileContext);
     }
     else
     {
         this.GenTypedBase(compileContext, aJType);
     }
 }
Example #38
0
        public SassCompiler_Tests()
        {
            directory = new Mock<IDirectory>();
            file = new Mock<IFile>();
            directory.Setup(d => d.GetFile(It.IsAny<string>())).Returns(new NonExistentFile("~"));
            directory.Setup(d => d.GetFile("~/test.scss")).Returns(file.Object);
            file.SetupGet(f => f.FullPath).Returns("~/test.scss");
            file.SetupGet(f => f.Directory).Returns(directory.Object);

            compileContext = new CompileContext { RootDirectory = directory.Object, SourceFilePath = "~/test.scss" };
            compiler = new SassCompiler();
        }
Example #39
0
        public override void Run(CompileContext context)
        {
            vbspInfo = context.Configuration.VBSPInfo;
            bspFile = context.CopyLocation;

            try
            {
                CompilePalLogger.LogLine("\nCompilePal - Cubemap Generator");

                if (!File.Exists(context.CopyLocation))
                {
                    throw new FileNotFoundException();
                }

                hidden = GetParameterString().Contains("-hidden");
                FetchHDRLevels();

                string mapname = System.IO.Path.GetFileName(context.CopyLocation).Replace(".bsp", "");

                string args = "-game \"" + context.Configuration.GameFolder + "\" -windowed -novid -nosound +mat_specular 0 %HDRevel% +map " + mapname + " -buildcubemaps";

                if (hidden)
                    args += " -noborder -x 4000 -y 2000";

                if (HDR && LDR)
                {
                    CompilePalLogger.LogLine("Map requires two sets of cubemaps");

                    CompilePalLogger.LogLine("Compiling LDR cubemaps...");
                    RunCubemaps(context.Configuration.GameEXE, args.Replace("%HDRevel%", "+mat_hdr_level 0"));

                    CompilePalLogger.LogLine("Compiling HDR cubemaps...");
                    RunCubemaps(context.Configuration.GameEXE, args.Replace("%HDRevel%", "+mat_hdr_level 2"));
                }
                else
                {
                    CompilePalLogger.LogLine("Map requires one set of cubemaps");
                    CompilePalLogger.LogLine("Compiling cubemaps...");
                    RunCubemaps(context.Configuration.GameEXE, args.Replace("%HDRevel%", ""));
                }
                CompilePalLogger.LogLine("Cubemaps compiled");
            }
            catch (FileNotFoundException)
            {
                CompilePalLogger.LogLine("FAILED - Could not find " + context.CopyLocation);
            }
            catch (Exception exception)
            {
                CompilePalLogger.LogLine("Something broke:");
                CompilePalLogger.LogLine(exception.ToString());
            }
        }
Example #40
0
        public override Intermediate.IRNode Emit(CompileContext context, Model.Scope scope, Target target)
        {
            var r = new StatementNode();
            r.AddChild(new Annotation(context.GetSourceSpan(this.Span)));

            if (ChildNodes.Count > 0)
            {
                r.AddChild(Child(0).Emit(context, scope, Target.Stack));
                r.AddInstruction(Instructions.SET, Operand("A"), Operand("POP"));
            }
            r.AddChild(scope.activeFunction.CompileReturn(context, scope));

            return r;
        }
Example #41
0
        public override Intermediate.IRNode Emit(CompileContext context, Model.Scope scope, Target target)
        {
            var r = new StatementNode();
            r.AddChild(new Annotation(context.GetSourceSpan(this.Span)));

            var fetch_token = Child(1).GetFetchToken();
            if (fetch_token == null)
            {
                var rTarget = Target.Register(context.AllocateRegister());
                r.AddChild(Child(1).Emit(context, scope, rTarget));
                fetch_token = rTarget.GetOperand(TargetUsage.Pop);
            }

            r.AddChild((Child(0) as AssignableNode).EmitAssignment(context, scope, fetch_token, opcodes[@operator]));
            return r;
        }
 public CompileResult Compile(string source, CompileContext context)
 {
     Trace.Source.TraceInformation("Compiling {0}", context.SourceFilePath);
     var workItem = compilationQueue.EnqueueCompilation(source);
     try
     {
         var javascript = workItem.AwaitResult();
         return new CompileResult(javascript, Enumerable.Empty<string>());
     }
     catch (Exception ex)
     {
         var message = ex.Message + " in " + context.SourceFilePath;
         Trace.Source.TraceEvent(TraceEventType.Critical, 0, message);
         throw new CoffeeScriptCompileException(message, context.SourceFilePath, ex);                    
     }
 }
        public void Run(CompileContext context)
        {
            XmlLoader loader = new XmlLoader();
            loader.Load(context.Input);

            context.Errors.AddRange(loader.LoadErrors.Select(e => new CompileError(e)));
            if (loader.LoadErrors.Count(e => e.Category == LoadErrorCategory.Error) > 0)
                return;

            var description = loader.GetDescriptions()[0];

            // The component XML format doesn't provide an ID, so make one now
            description.ID = "C0";

            context.Description = description;
        }
Example #44
0
        public CompileResult Compile(string source, CompileContext context)
        {
            var sourceFile = context.RootDirectory.GetFile(context.SourceFilePath);
            importedFilePaths = new HashedSet<string>();
            var parser = new Parser
            {
                Importer = new Importer(new CassetteLessFileReader(sourceFile.Directory, importedFilePaths))
            };
            var errorLogger = new ErrorLogger();
            var engine = new LessEngine(
                                    parser,
                                    errorLogger,
                                    configuration.MinifyOutput,
                                    configuration.Debug,
                                    configuration.DisableVariableRedefines,
                                    configuration.DisableColorCompression,
                                    configuration.KeepFirstSpecialComment,
                                    configuration.Plugins);

            string css;
            try
            {
                css = engine.TransformToCss(source, sourceFile.FullPath);
            }
            catch (Exception ex)
            {
                throw new LessCompileException(
                    string.Format("Error compiling {0}{1}{2}", context.SourceFilePath, Environment.NewLine, ex.Message),
                    ex
                );
            }

            if (errorLogger.HasErrors)
            {
                var exceptionMessage = string.Format(
                    "Error compiling {0}{1}{2}",
                    context.SourceFilePath,
                    Environment.NewLine,
                    errorLogger.ErrorMessage
                );
                throw new LessCompileException(exceptionMessage);
            }
            else
            {
                return new CompileResult(css, importedFilePaths);
            }
        }
Example #45
0
        Intermediate.IRNode AssignableNode.EmitAssignment(CompileContext context, Model.Scope scope, Intermediate.Operand from, Intermediate.Instructions opcode)
        {
            var r = new TransientNode();

            if (member == null)
            {
                context.ReportError(this, "Member was not resolved");
                return r;
            }

            var target = Target.Register(context.AllocateRegister());
            r.AddChild(Child(0).Emit(context, scope, target));
            r.AddInstruction(opcode, target.GetOperand(TargetUsage.Peek,
                Intermediate.OperandSemantics.Dereference | Intermediate.OperandSemantics.Offset, (ushort)member.offset),
                from);
            return r;
        }
Example #46
0
        public override void Run(CompileContext context)
        {
            // don't run unless it's the last map of the queue
            if (CompilingManager.MapFiles.Last() == context.MapFile)
            {
                CompilePalLogger.LogLine("\nCompilePal - Shutdown");
                CompilePalLogger.LogLine("The system will shutdown soon.");
                CompilePalLogger.LogLine("You can cancel this shutdown by using the command \"shutdown -a\"");

                var startInfo = new ProcessStartInfo("shutdown", GetParameterString());
                startInfo.UseShellExecute = false;
                startInfo.CreateNoWindow = true;

                Process = new Process { StartInfo = startInfo };
                Process.Start();
            }
        }
Example #47
0
        public override void ResolveTypes(CompileContext context, Model.Scope enclosingScope)
        {
            _struct = enclosingScope.FindType(typeName);
            if (_struct == null)
            {
                CachedFetchToken = Constant(0);
                context.ReportError(this, "Could not find type " + typeName);
            }
            else if (_struct.size == 0)
            {
                throw new InternalError("Struct size must be determined before types are resolved.");
            }
            else
                CachedFetchToken = Constant((ushort)_struct.size);

             ResultType = "word";
        }
 public CompileResult Compile(string coffeeScriptSource, CompileContext context)
 {
     Trace.Source.TraceInformation("Compiling {0}", context.SourceFilePath);
     lock (ScriptEngine) // ScriptEngine is NOT thread-safe, so we MUST lock.
     {
         try
         {
             Trace.Source.TraceInformation("Compiled {0}", context.SourceFilePath);
             var javascript = ScriptEngine.CallGlobalFunction<string>("compile", coffeeScriptSource);
             return new CompileResult(javascript, Enumerable.Empty<string>());
         }
         catch (Exception ex)
         {
             var message = ex.Message + " in " + context.SourceFilePath;
             Trace.Source.TraceEvent(TraceEventType.Critical, 0, message);
             throw new CoffeeScriptCompileException(message, context.SourceFilePath, ex);
         }
     }
 }
Example #49
0
        public override void ResolveTypes(CompileContext context, Model.Scope enclosingScope)
        {
            _struct = enclosingScope.FindType(typeName);

            if (_struct == null)
            {
                context.ReportError(this, "Could not find type " + typeName);
                CachedFetchToken = Constant(0);
            }
            else
            {
                var memberIndex = _struct.members.FindIndex(m => m.name == memberName);
                if (memberIndex < 0)
                {
                    context.ReportError(this, "Member not found : " + memberName);
                    CachedFetchToken = Constant(0);
                }
                else
                    CachedFetchToken = Constant((ushort)memberIndex);
            }

            ResultType = "word";
        }
Example #50
0
        public override Intermediate.IRNode Emit(CompileContext context, Model.Scope scope, Target target)
        {
            var r = new TransientNode();

            if (member == null)
            {
                context.ReportError(this, "Member was not resolved.");
                return r;
            }

            Target objectTarget = target;
            if (target.target == Targets.Stack)
                objectTarget = Target.Register(context.AllocateRegister());

            r.AddChild(Child(0).Emit(context, scope, objectTarget));
            if (member.isArray)
            {
                if (target != objectTarget)
                    r.AddInstruction(Instructions.SET, target.GetOperand(TargetUsage.Push), objectTarget.GetOperand(TargetUsage.Pop));
                r.AddInstruction(Instructions.ADD, target.GetOperand(TargetUsage.Peek), Constant((ushort)member.offset));
            }
            else
            {
                if (member.offset == 0)
                    r.AddInstruction(Instructions.SET,
                        target.GetOperand(TargetUsage.Push),
                        objectTarget.GetOperand(TargetUsage.Pop, Intermediate.OperandSemantics.Dereference));
                else
                    r.AddInstruction(Instructions.SET,
                        target.GetOperand(TargetUsage.Push),
                        objectTarget.GetOperand(TargetUsage.Pop,
                            Intermediate.OperandSemantics.Dereference | Intermediate.OperandSemantics.Offset,
                            (ushort)member.offset));
            }

            return r;
        }
 public EvaluatePropertiesPhase(CompileContext compileContext, bool withDebug)
     : this(compileContext)
 {
     _withDebug = withDebug;
 }
Example #52
0
 public override Intermediate.IRNode Emit(CompileContext context, Model.Scope scope, Target target)
 {
     return new Intermediate.Annotation("Declaration of function " + function.name);
 }
 public EvaluatePropertiesPhase(CompileContext compileContext)
 {
     _compileContext = compileContext;
 }
Example #54
0
		/// <summary>
		/// Compiles the specified JSX file into JavaScript
		/// </summary>
		/// <param name="source">The source.</param>
		/// <param name="context">The context.</param>
		/// <returns>JavaScript</returns>
		public CompileResult Compile(string source, CompileContext context)
		{
			var output = _environment.JsxTransformer.TransformJsx(source);
			return new CompileResult(output, Enumerable.Empty<string>());
		}
Example #55
0
 public override void GatherSymbols(CompileContext context, Model.Scope enclosingScope)
 {
     Child(0).GatherSymbols(context, enclosingScope);
     Child(1).GatherSymbols(context, enclosingScope);
 }
Example #56
0
        public override void Run(CompileContext context)
        {
            try
            {

            CompilePalLogger.LogLine("\nCompilePal - Nav Generator");

                if (!File.Exists(context.CopyLocation))
                {
                    throw new FileNotFoundException();
                }

                mapname = System.IO.Path.GetFileName(context.CopyLocation).Replace(".bsp", "");
            mapnav = context.CopyLocation.Replace(".bsp", ".nav");
            mapcfg = context.Configuration.GameFolder + "/cfg/" + mapname + ".cfg";
            mapCFGBackup = context.Configuration.GameFolder + "/cfg/" + mapname + "_cpalbackup.cfg";

                deleteNav(mapname, context.Configuration.GameFolder);

            hidden = GetParameterString().Contains("-hidden");

            string args = "-game \"" + context.Configuration.GameFolder + "\" -windowed -novid -nosound +sv_cheats 1 +map " + mapname;

            if (hidden)
                args += " -noborder -x 4000 -y 2000";

            var startInfo = new ProcessStartInfo(context.Configuration.GameEXE, args);
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = false;

            CompilePalLogger.LogLine("Generating...");
            if (File.Exists(mapcfg))
            {
                if (File.Exists(mapCFGBackup))
                    System.IO.File.Delete(mapCFGBackup);
                System.IO.File.Move(mapcfg, mapCFGBackup);
            }

            System.IO.File.Create(mapcfg).Dispose();
            TextWriter tw = new StreamWriter(mapcfg);
            tw.WriteLine("nav_generate");
            tw.Close();

            Process = new Process { StartInfo = startInfo };
            Process.Start();

            FileSystemWatcher fw = new FileSystemWatcher();
            fw.Path = System.IO.Path.GetDirectoryName(mapnav);
            fw.Filter = "*.nav";
            fw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            fw.Changed += new FileSystemEventHandler(fileSystemWatcher_NavCreated);
            fw.Created += new FileSystemEventHandler(fileSystemWatcher_NavCreated);
            fw.EnableRaisingEvents = true;

            Process.WaitForExit();
            fw.Dispose();

            cleanUp();
            CompilePalLogger.LogLine("nav file complete!");
            }
            catch (FileNotFoundException)
            {
                CompilePalLogger.LogLine("FAILED - Could not find " + context.CopyLocation);
            }
            catch (Exception exception)
            {
                CompilePalLogger.LogLine("Something broke:");
                CompilePalLogger.LogLine(exception.ToString());
            }
        }
Example #57
0
        public virtual Intermediate.IRNode CompileFunction(CompileContext context)
        {
            if (context.options.strip && !function.reached)
                return new Intermediate.Annotation("Function " + function.name + " stripped.");

            context.nextVirtualRegister = 0;
            var body = new Intermediate.IRNode();
            foreach (var child in ChildNodes)
                body.AddChild((child as CompilableNode).Emit(context, function.localScope, Target.Discard));

            body.CollapseTransientNodes();

            if (context.options.collapse_statements)
                body.MergeConsecutiveStatements();

            if (context.options.ssa)
                body.ApplySSA();

            body.PeepholeTree(context.peepholes);

            var registers = new bool[] { true, false, false, false, false, false, false, true };
            var used = 0;

            // If we are emitting intermediate representation, we don't want to replace virtual registers.
            if (!context.options.emit_ir)
            {
                body.AssignRegisters(null);
                body.MarkUsedRealRegisters(registers);
                used = registers.Count((rs) => rs == true) - 2; //Why -2? Don't preserve A or J.
                body.CorrectVariableOffsets(-used);
            }

            var r = new Intermediate.Function
            {
                functionName = function.name,
                entranceLabel = function.label,
                parameterCount = function.parameterCount
            };

            r.AddChild(new Intermediate.Annotation(context.GetSourceSpan(this.headerSpan)));

            r.AddLabel(function.label);

            r.AddChild(new Intermediate.Annotation("Save frame pointer in J"));
            r.AddInstruction(Intermediate.Instructions.SET, Operand("PUSH"), Operand("J"));
            r.AddInstruction(Intermediate.Instructions.SET, Operand("J"), Operand("SP"));

            //Save registers
            for (int i = 1; i < 7; ++i)
                if (registers[i])
                    r.AddInstruction(Intermediate.Instructions.SET, Operand("PUSH"), Operand((Model.Register)i));

            r.AddChild(body);

            r.AddLabel(footerLabel);
            r.AddInstruction(Intermediate.Instructions.SET, Operand("SP"), Operand("J"));
            if (used != 0)
                r.AddInstruction(Intermediate.Instructions.SUB, Operand("SP"), Constant((ushort)used));

            //Restore registers
            for (int i = 6; i >= 1; --i)
                if (registers[i])
                    r.AddInstruction(Intermediate.Instructions.SET, Operand((Model.Register)i), Operand("POP"));

            r.AddInstruction(Intermediate.Instructions.SET, Operand("J"), Operand("POP"));
            r.AddInstruction(Intermediate.Instructions.SET, Operand("PC"), Operand("POP"));

            foreach (var nestedFunction in function.SubordinateFunctions)
                r.AddChild(nestedFunction.Node.CompileFunction(context));

            return r;
        }
Example #58
0
 public override void ResolveTypes(CompileContext context, Model.Scope enclosingScope)
 {
     Child(0).ResolveTypes(context, enclosingScope);
     Child(1).ResolveTypes(context, enclosingScope);
     ResultType = Child(0).ResultType;
 }
Example #59
0
 public CreateProducersPhase(CompileContext compileContext)
 {
     _compileContext = compileContext;
 }
 public CompileResult Compile(string source, CompileContext context)
 {
     var javascript = _scriptEngine.CallGlobalFunction<string>("handlebarsPrecompile", source);
     return new CompileResult(javascript, Enumerable.Empty<string>());
 }