Ejemplo n.º 1
0
 public void Compile(CompilationContext context)
 {
     targetObject.Compile(context);
     value.Compile(context);
     CompilationHelper.PrepareValueOnStack(context, fieldInfo.FieldType, value.itemType);
     context.Emit(OpCodes.Stfld, fieldInfo);
 }
Ejemplo n.º 2
0
        internal override IEnumerable<AssociativeNode> BuildAst(List<AssociativeNode> inputAstNodes, CompilationContext context)
        {
            var rhs = AstFactory.BuildStringNode(Value);
            var assignment = AstFactory.BuildAssignment(GetAstIdentifierForOutputIndex(0), rhs);

            return new[] { assignment };
        }
Ejemplo n.º 3
0
		static int Main(string[] args)
		{
			if (args != null && args.Length == 1)
			{
				if (args[0].Equals("-w", StringComparison.InvariantCultureIgnoreCase) ||
				    args[0].Equals("-wait", StringComparison.InvariantCultureIgnoreCase))
					Console.ReadLine();
				else
					siteRoot = args[0];
			}
			if (siteRoot == null)
			{
				string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
				siteRoot = baseDirectory.Substring(0, baseDirectory.LastIndexOf("\\bin", StringComparison.InvariantCultureIgnoreCase));
			}
			Console.WriteLine("Compiling [" + siteRoot + "] ...");

			InitializeConfig();

			if (!Directory.Exists(siteRoot))
			{
				PrintHelpMessage(string.Format("The path '{0}' does not exist", siteRoot));
				Console.ReadLine();
				return -1;
			}

			OfflineCompiler compiler;
			try
			{
				ICompilationContext compilationContext = new CompilationContext(
					new DirectoryInfo(Path.Combine(siteRoot, "bin")),
					new DirectoryInfo(siteRoot),
					new DirectoryInfo(Path.Combine(siteRoot, "views")),
					new DirectoryInfo(options.CompilerOptions.TemporarySourceFilesDirectory));

				compiler = new OfflineCompiler(
					new CSharpCodeProviderAdapterFactory(),
					new PreProcessor(), 
					compilationContext, options.CompilerOptions, new DefaultFileSystemAdapter());
			}
			catch
			{
				PrintHelpMessage("Could not start the compiler.");
				return -2;
			}

			try
			{
				string path = compiler.Execute();

				Console.WriteLine("[{0}] compiled into [{1}].", siteRoot, path);
				return 0;
			}
			catch (Exception ex)
			{
				PrintHelpMessage("Could not compile." + Environment.NewLine + ex);
				return -3;
			}

		}
Ejemplo n.º 4
0
        public static void EmitCall(
            CompilationContext context,
            IAstRefOrAddr invocationObject,
            MethodInfo methodInfo,
            List<IAstStackItem> arguments)
        {
            if (arguments == null)
            {
                arguments = new List<IAstStackItem>();
            }
            if (invocationObject != null)
            {
                invocationObject.Compile(context);
            }

            ParameterInfo[] args = methodInfo.GetParameters();
            if (args.Length != arguments.Count)
            {
                throw new Exception("Invalid method parameters count");
            }

            for (int i = 0; i < args.Length; ++i)
            {
                arguments[i].Compile(context);
                PrepareValueOnStack(context, args[i].ParameterType, arguments[i].itemType);
            }
            if (methodInfo.IsVirtual)
            {
                context.EmitCall(OpCodes.Callvirt, methodInfo);
            }
            else
            {
                context.EmitCall(OpCodes.Call, methodInfo);
            }
        }
        private void CompileDirectory(CompilationContext context, string viewDirectory)
        {
            // Prevent processing of the same directories multiple times (sligh performance optimization,
            // as the build manager second call to compile a view is essentially a "no-op".
            if (context.ProcessedDirectories.Contains(viewDirectory))
                return;
            context.ProcessedDirectories.Add(viewDirectory);

            var stopwatch = new Stopwatch();
            stopwatch.Start();
            try {
                var firstFile = _virtualPathProvider
                    .ListFiles(viewDirectory)
                    .Where(f => context.FileExtensionsToCompile.Any(e => f.EndsWith(e, StringComparison.OrdinalIgnoreCase)))
                    .FirstOrDefault();

                if (firstFile != null)
                    BuildManager.GetCompiledAssembly(firstFile);
            }
            catch(Exception e) {
                // Some views might not compile, this is ok and harmless in this
                // context of pre-compiling views.
                Logger.Information(e, "Compilation of directory '{0}' skipped", viewDirectory);
            }
            stopwatch.Stop();
            Logger.Information("Directory '{0}' compiled in {1} msec", viewDirectory, stopwatch.ElapsedMilliseconds);
        }
Ejemplo n.º 6
0
 public override void Compile(CompilationContext context)
 {
     CompilationHelper.CheckIsValue(itemType);
     array.Compile(context);
     context.Emit(OpCodes.Ldc_I4, index);
     context.Emit(OpCodes.Ldelema, itemType);
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Executes the translation process.
        /// </summary>
        /// <param name="context">The compilation context.</param>
        public void Execute(CompilationContext context)
        {
            if (context == null || context.Model == null)
                return;

            if (context.OutputStream == null || !context.OutputStream.CanWrite)
                throw new CompilationException("The translation output stream is null or not writable.");

            var translationCtx = new TranslationContext();
            translationCtx.OutputStream = context.OutputStream;

            // write enum declarations
            var enumTranslator = new EnumTranslator();
            foreach (var item in context.Model.Enums)
                enumTranslator.Translate(item, translationCtx);

            // write class declarations
            var classTranslator = new ClassTranslator();
            foreach (var item in ClassSorter.Sort(context.Model.Classes))
                classTranslator.Translate(item, translationCtx);

            // write global statements
            if (context.Model.GlobalStatements.Any())
            {
                translationCtx.WriteLine();
                foreach (var item in context.Model.GlobalStatements)
                    translationCtx.WriteModel(item);
            }
        }
        public void Compile(CompilationContext context)
        {
            AstBuildHelper.CallMethod(
				_setMethod, 
				_targetObject,
                new List<IAstStackItem>() { _value }
			).Compile(context);
        }
Ejemplo n.º 9
0
 public void Compile(CompilationContext context)
 {
     if(localType.IsValueType)
     {
         context.Emit(OpCodes.Ldloca, localIndex);
         context.Emit(OpCodes.Initobj, localType);
     }
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Executes the model validation process.
        /// </summary>
        /// <param name="context">The compilation context.</param>
        public void Execute(CompilationContext context)
        {
            var provider = new ImportProvider<IModelValidator>();

            foreach (var validator in provider.GetImports())
            {
                validator.Validate(context.Model, context.Result);
            }
        }
Ejemplo n.º 11
0
        public void Compile(CompilationContext context)
        {
			new AstCallMethod(methodInfo, invocationObject, arguments).Compile(context);

            if (methodInfo.ReturnType != typeof(void))
            {
                context.Emit(OpCodes.Pop);
            }
        }
Ejemplo n.º 12
0
 public void Compile(CompilationContext context)
 {
     var endBlock = context.ilGenerator.BeginExceptionBlock();
     protectedBlock.Compile(context);
     context.ilGenerator.BeginCatchBlock(exceptionType);
     context.ilGenerator.Emit(OpCodes.Stloc, eceptionVariable);
     handlerBlock.Compile(context);
     context.ilGenerator.EndExceptionBlock();
 }
Ejemplo n.º 13
0
 public virtual void Compile(CompilationContext context)
 {
     AstReadArgument arg = new AstReadArgument()
                               {
                                   argumentIndex = 0,
                                   argumentType = thisType
                               };
     arg.Compile(context);
 }
Ejemplo n.º 14
0
        public void Compile(CompilationContext context)
        {
            value.Compile(context);

            if (value.itemType.IsValueType)
            {
                context.Emit(OpCodes.Box, itemType);
            }
        }
Ejemplo n.º 15
0
 public IncrementalHighlighter(Highlighter highlighter)
 {
     highlightingParser = new HighlightingParser(highlighter);
     var context = new CompilationContext();
     tokenizer = context.CreateTokenizer(
         token => highlightingParser.OnToken(token),
         () => highlightingParser.OnDone(),
         () => {}
     );
 }
		public Delegate Compile ()
		{
#if TARGET_JVM || MONOTOUCH
			return new System.Linq.jvm.Runner (this).CreateDelegate ();
#else
			var context = new CompilationContext ();
			context.AddCompilationUnit (this);
			return context.CreateDelegate ();
#endif
		}
Ejemplo n.º 17
0
 public void Compile(CompilationContext context)
 {
     Label ifNotNullLabel = context.ilGenerator.DefineLabel();
     _value.Compile(context);
     context.Emit(OpCodes.Dup);
     context.Emit(OpCodes.Brtrue_S, ifNotNullLabel);
     context.Emit(OpCodes.Pop);
     _ifNullValue.Compile(context);
     context.ilGenerator.MarkLabel(ifNotNullLabel);
 }
Ejemplo n.º 18
0
 public void Compile(CompilationContext context)
 {
     foreach (IAstNode node in nodes)
     {
         if (node != null)
         {
             node.Compile(context);
         }
     }
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Executes the syntax validation process.
        /// </summary>
        /// <param name="context">The compilation context.</param>
        public void Execute(CompilationContext context)
        {
            var visitor = new SyntaxValidationVisitor(
                new SyntaxValidatorProvider(), context.Result);

            foreach (var tree in context.Compilation.SyntaxTrees)
            {
                visitor.CurrentTree = tree;
                visitor.Visit(tree.GetRoot());
            }
        }
Ejemplo n.º 20
0
        public virtual void Compile(CompilationContext context)
        {
            MethodInfo mi = propertyInfo.GetGetMethod();

            if (mi == null)
            {
                throw new Exception("Property " + propertyInfo.Name + " doesn't have get accessor");
            }

            AstBuildHelper.CallMethod(mi, sourceObject, null).Compile(context);
        }
Ejemplo n.º 21
0
 override public void Compile(CompilationContext context)
 {
     CompilationHelper.CheckIsValue(itemType);
     if (itemType == typeof(Int32))
     {
         context.Emit(OpCodes.Ldind_I4);
     }
     else
     {
         throw new Exception("Unsupported type");
     }
 }
Ejemplo n.º 22
0
 public void Compile(CompilationContext context)
 {
     LocalBuilder loc = context.ilGenerator.DeclareLocal(itemType);
     new AstInitializeLocalVariable(loc).Compile(context);
     new AstWriteLocal()
         {
             localIndex = loc.LocalIndex,
             localType = loc.LocalType,
             value = value
         }.Compile(context);
     new AstReadLocalAddr(loc).Compile(context);
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Executes the preprocessing process.
        /// </summary>
        /// <param name="context">The compilation context.</param>
        public void Execute(CompilationContext context)
        {
            if (context == null || context.Compilation == null)
                return;

            // get local imports
            var provider = new ImportProvider<IPreprocessor>(null);
            var sorter = new PreprocessorSorter();

            foreach (var preprocessor in sorter.Sort(provider.GetImports()))
            {
                context.Compilation = preprocessor.ProcessCompilation(context.Compilation);
            }
        }
Ejemplo n.º 24
0
 public static void PrepareValueOnStack(CompilationContext context, Type desiredType, Type typeOnStack)
 {
     if (typeOnStack.IsValueType && !desiredType.IsValueType)
     {
         context.Emit(OpCodes.Box, typeOnStack);
     }
     else if (!typeOnStack.IsValueType && desiredType.IsValueType)
     {
         context.Emit(OpCodes.Unbox_Any, desiredType);
     }
     else if (desiredType != typeOnStack)
     {
         context.Emit(OpCodes.Castclass, desiredType);
     }
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Executes the module builder process
        /// </summary>
        /// <param name="context">The compilation context.</param>
        public void Execute(CompilationContext context)
        {
            if (context.Input == null)
                throw new CompilationException("The compilation input cannot be null.");

            // ensure the output directory is available
            if (!Directory.Exists(context.Input.TargetDirectory))
                Directory.CreateDirectory(context.Input.TargetDirectory);

            CompilerResults compileResult = null;

            using (var codeProvider = new CSharpCodeProvider())
            {
                // create compiler and options
                var options = new CompilerParameters
                {
                    GenerateExecutable = false,
                    GenerateInMemory = true,
                    IncludeDebugInformation = false,
                    CompilerOptions = "/t:library /noconfig /nostdlib"
                };

                // add referenced assemblies
                options.ReferencedAssemblies.AddRange(
                    context.Input.ReferencePaths.ToArray());

                // compile to module
                compileResult = codeProvider.CompileAssemblyFromFile(options,
                    context.Input.SourceFilePaths.ToArray());
            }

            // check for errors or warnings
            foreach (var item in compileResult.Errors.OfType<CompilerError>())
            {
                var msg = new CompilationMessage
                {
                    FilePath = item.FileName,
                    Message = item.ErrorText
                };

                if (item.IsWarning)
                    context.Result.AddWarning(msg);
                else context.Result.AddError(msg);
            }
        }
Ejemplo n.º 26
0
        public RootTokenizer(Action<Token> tokenConsumer,
							 Action tokenReady,
							 Action lineReady,
							 CompilationContext compilationContext)
        {
            if(tokenConsumer == null) {
                throw new ArgumentNullException("tokenConsumer");
            } else if(tokenReady == null) {
                throw new ArgumentNullException("tokenReady");
            } else if(lineReady == null) {
                throw new ArgumentNullException("lineReady");
            } else if(compilationContext == null) {
                throw new ArgumentNullException("compilationContext");
            }
            this.tokenConsumer = tokenConsumer;
            this.tokenReady = tokenReady;
            this.lineReady = lineReady;
            this.compilationContext = compilationContext;
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Executes the transformation process.
        /// </summary>
        /// <param name="context">The compilation context.</param>
        public void Execute(CompilationContext context)
        {
            if (context == null || context.Compilation == null)
                return;

            if (context.Model == null)
                context.Model = new CompilationModel();

            if (context.Compilation is Roslyn.Compilers.CSharp.Compilation)
                TransformCSharp(context);
            else if (context.Compilation is Roslyn.Compilers.VisualBasic.Compilation)
                TransformVisualBasic(context);
            else throw new NotImplementedException("Transformation not implemented for compilation of type: " + context.Compilation.GetType().FullName);

            if (!context.Result.HasErrors)
            {
                ModelRegistry.Current.ExtendCompilation(context.Model, context.Compilation.Assembly);
            }
        }
Ejemplo n.º 28
0
        public void DefaultConstructorInitializeCorrectly()
        {
            var compilation = CSharpCompilation.Create("fakecompilation");
            var fakeProject = new MockCompilationProject();
            var fakeFramework = new FrameworkName(".NET Framework, Version=8.0");
            var fakeConfiguration = "fakeConfiguration";

            var resourceResolverInvoked = false;

            var context = new CompilationContext(
                compilation,
                fakeProject,
                fakeFramework,
                fakeConfiguration,
                new List<IMetadataReference>(),
                () =>
                {
                    resourceResolverInvoked = true;
                    return new List<CodeAnalysis.ResourceDescription>();
                });

            Assert.NotNull(context.Modules);
            Assert.Equal(0, context.Modules.Count);
            Assert.Equal(compilation, context.Compilation);
            Assert.Equal(compilation, context.BeforeCompileContext.Compilation);
            Assert.Equal(fakeProject, context.Project);
            Assert.Equal(fakeFramework, context.ProjectContext.TargetFramework);
            Assert.Equal(fakeConfiguration, context.ProjectContext.Configuration);

            Assert.False(resourceResolverInvoked, "Resource resolver should not be invoked");
            Assert.Equal(0, context.Resources.Count);
            Assert.True(resourceResolverInvoked);

            var newCompilation = compilation.Clone();
            context.Compilation = newCompilation;

            Assert.NotEqual(compilation, context.Compilation);
            Assert.NotEqual(compilation, context.BeforeCompileContext.Compilation);
            Assert.Equal(newCompilation, context.Compilation);
            Assert.Equal(newCompilation, context.BeforeCompileContext.Compilation);
        }
Ejemplo n.º 29
0
 public virtual void Compile(CompilationContext context)
 {
     switch (argumentIndex)
     {
         case 0:
             context.Emit(OpCodes.Ldarg_0);
             break;
         case 1:
             context.Emit(OpCodes.Ldarg_1);
             break;
         case 2:
             context.Emit(OpCodes.Ldarg_2);
             break;
         case 3:
             context.Emit(OpCodes.Ldarg_3);
             break;
         default:
             context.Emit(OpCodes.Ldarg, argumentIndex);
             break;
     }
 }
Ejemplo n.º 30
0
        /// <summary>
        /// Executes the diagnostic process.
        /// </summary>
        /// <param name="context">The compilation context.</param>
        public void Execute(CompilationContext context)
        {
            if (context == null || context.Compilation == null)
                return;

            if (context.Result == null)
                context.Result = new CompilationResult();

            foreach (var item in context.Compilation.GetDiagnostics())
            {
                switch (item.Info.Severity)
                {
                    case DiagnosticSeverity.Error:
                        context.Result.AddError(CreateMessage(item));
                        break;

                    case DiagnosticSeverity.Warning:
                        context.Result.AddWarning(CreateMessage(item));
                        break;
                }
            }
        }
Ejemplo n.º 31
0
 private IEnumerable <SymbolInformationOrDocumentSymbol> GetSymbols(CompilationContext context)
 {
     return(context.Compilation.GetEntrypointSemanticModel().Root.AllDeclarations
            .OrderBy(symbol => symbol.DeclaringSyntax.Span.Position)
            .Select(symbol => new SymbolInformationOrDocumentSymbol(CreateDocumentSymbol(symbol, context.LineStarts))));
 }
Ejemplo n.º 32
0
 private DeferredSectionVisitor(CompilationContext context)
     : base(context)
 {
 }
Ejemplo n.º 33
0
 public void Emit(CompilationContext context)
 {
     //TODO: need to change emitted value if it's cast?
     ((ICodeEmitter)Tokens.Last()).Emit(context);
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StaticAnalysisProcess"/> class.
 /// </summary>
 private StaticAnalysisProcess(CompilationContext context)
 {
     this.CompilationContext = context;
 }
Ejemplo n.º 35
0
 public System.Linq.Expressions.Expression FromOutput(IFunction output, Type outputType, CompileFunction compile,
                                                      CompilationContext context)
 {
     throw new NotImplementedException("Outputting an array is not supported yet");
 }
Ejemplo n.º 36
0
 IFunction IFunction.CallInternal(IFunction[] arguments, string output, CompilationContext context) => this;
Ejemplo n.º 37
0
        internal override IEnumerable <AssociativeNode> BuildAst(List <AssociativeNode> inputAstNodes, CompilationContext context)
        {
            AssociativeNode assignment;

            if (null == inputAstNodes || inputAstNodes.Count == 0)
            {
                assignment = AstFactory.BuildAssignment(AstIdentifierForPreview, AstFactory.BuildNullNode());
            }
            else
            {
                assignment = AstFactory.BuildAssignment(AstIdentifierForPreview, inputAstNodes[0]);
            }

            return(new[] { assignment });
        }
Ejemplo n.º 38
0
 protected abstract void EmitSource(CompilationContext context);
Ejemplo n.º 39
0
        internal override IEnumerable <AssociativeNode> BuildAst(List <AssociativeNode> inputAstNodes, CompilationContext context)
        {
            //Do not build if the node is in error.
            if (State == ElementState.Error)
            {
                return(Enumerable.Empty <AssociativeNode>());
            }

            var resultNodes = new List <AssociativeNode>();

            // Define unbound variables if necessary
            if (inputIdentifiers != null &&
                inputAstNodes != null &&
                inputIdentifiers.Count == inputAstNodes.Count)
            {
                var initStatments = inputIdentifiers.Zip(inputAstNodes,
                                                         (ident, rhs) =>
                {
                    var identNode = AstFactory.BuildIdentifier(ident);
                    if (context != CompilationContext.NodeToCode)
                    {
                        MapIdentifiers(identNode);
                    }
                    return(AstFactory.BuildAssignment(identNode, rhs));
                });
                resultNodes.AddRange(initStatments);
            }

            foreach (var astNode in codeStatements.Select(stmnt => NodeUtils.Clone(stmnt.AstNode)))
            {
                if (context != CompilationContext.NodeToCode)
                {
                    MapIdentifiers(astNode);
                }
                resultNodes.Add(astNode as AssociativeNode);
            }

            return(resultNodes);
        }
Ejemplo n.º 40
0
        public CompilationContext Update(IReadOnlyWorkspace workspace, CompilationContext current, ImmutableDictionary <ISourceFile, ISemanticModel> modelLookup, RootConfiguration configuration, LinterAnalyzer linterAnalyzer)
        {
            var syntaxTreeGrouping = SourceFileGroupingBuilder.Rebuild(moduleDispatcher, workspace, current.Compilation.SourceFileGrouping, configuration);

            return(this.CreateContext(syntaxTreeGrouping, modelLookup, configuration, linterAnalyzer));
        }
Ejemplo n.º 41
0
 private void EmitSetTarget(CompilationContext context)
 {
     ((IMemberBuilder)TargetMember).EmitSetter(context);
 }
Ejemplo n.º 42
0
        internal sealed override void Compile(CompilationContext context)
        {
            context.Stack.Push(context.Locals[this.Index]);

            var localIndex = this.Index - context.Signature.ParameterTypes.Length;

            if (localIndex < 0)
            {
                //Referring to a parameter.
                switch (this.Index)
                {
                default:
                    if (this.Index <= byte.MaxValue)
                    {
                        context.Emit(OpCodes.Ldarg_S, checked ((byte)this.Index));
                    }
                    else
                    {
                        context.Emit(OpCodes.Ldarg, checked ((ushort)this.Index));
                    }
                    break;

                case 0: context.Emit(OpCodes.Ldarg_0); break;

                case 1: context.Emit(OpCodes.Ldarg_1); break;

                case 2: context.Emit(OpCodes.Ldarg_2); break;

                case 3: context.Emit(OpCodes.Ldarg_3); break;
                }
            }
            else
            {
                //Referring to a local.
                switch (localIndex)
                {
                default:
                    if (localIndex > 65534)     // https://docs.microsoft.com/en-us/dotnet/api/system.reflection.emit.opcodes.ldloc
                    {
                        throw new CompilerException($"Implementation limit exceeded: maximum accessible local index is 65534, tried to access {localIndex}.");
                    }

                    if (localIndex <= byte.MaxValue)
                    {
                        context.Emit(OpCodes.Ldloc_S, (byte)localIndex);
                    }
                    else
                    {
                        context.Emit(OpCodes.Ldloc, checked ((ushort)localIndex));
                    }
                    break;

                case 0: context.Emit(OpCodes.Ldloc_0); break;

                case 1: context.Emit(OpCodes.Ldloc_1); break;

                case 2: context.Emit(OpCodes.Ldloc_2); break;

                case 3: context.Emit(OpCodes.Ldloc_3); break;
                }
            }
        }
Ejemplo n.º 43
0
 public void Emit(CompilationContext context)
 {
     context.EmitInstruction(new IRSysEx());
 }
Ejemplo n.º 44
0
 public static System.Linq.Expressions.Expression Bind(System.Linq.Expressions.Expression expr, CompilationContext context)
 {
     return(new DeferredSectionVisitor(context).Visit(expr));
 }
Ejemplo n.º 45
0
        static MethodBuilder CreateSelectHelper(HelperMethod helper, CompilationContext context)
        {
            Assert(context != null);

            MethodBuilder builder;

            switch (helper)
            {
            default:
                Fail("Attempted to obtain an unknown helper method.");
                return(null);

            case HelperMethod.SelectInt32:
                builder = context.ExportsBuilder.DefineMethod(
                    "☣ Select Int32",
                    CompilationContext.HelperMethodAttributes,
                    typeof(int),
                    new[]
                {
                    typeof(int),
                    typeof(int),
                    typeof(int),
                }
                    );
                break;

            case HelperMethod.SelectInt64:
                builder = context.ExportsBuilder.DefineMethod(
                    "☣ Select Int64",
                    CompilationContext.HelperMethodAttributes,
                    typeof(long),
                    new[]
                {
                    typeof(long),
                    typeof(long),
                    typeof(int),
                }
                    );
                break;

            case HelperMethod.SelectFloat32:
                builder = context.ExportsBuilder.DefineMethod(
                    "☣ Select Float32",
                    CompilationContext.HelperMethodAttributes,
                    typeof(float),
                    new[]
                {
                    typeof(float),
                    typeof(float),
                    typeof(int),
                }
                    );
                break;

            case HelperMethod.SelectFloat64:
                builder = context.ExportsBuilder.DefineMethod(
                    "☣ Select Float64",
                    CompilationContext.HelperMethodAttributes,
                    typeof(double),
                    new[]
                {
                    typeof(double),
                    typeof(double),
                    typeof(int),
                }
                    );
                break;
            }

            var il = builder.GetILGenerator();

            il.Emit(OpCodes.Ldarg_2);
            var @true = il.DefineLabel();

            il.Emit(OpCodes.Brtrue_S, @true);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ret);
            il.MarkLabel(@true);
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ret);
            return(builder);
        }
 public XmlWriteValueMethodCompiler(CompilationContext context) : base(context)
 {
 }
Ejemplo n.º 47
0
 bool?IType.SatisfiedBy(IFunction value, CompilationContext info) =>
 value is Error ? (bool?)null : value.GetSize(info).HasValue;
Ejemplo n.º 48
0
 public IValue ResolveSubExpression(IValue previous, IScope resolutionScope, CompilationContext compilationContext) =>
 previous switch
 {
Ejemplo n.º 49
0
 internal override IEnumerable <AssociativeNode> BuildAst(List <AssociativeNode> inputAstNodes, CompilationContext context)
 {
     if (context == CompilationContext.NodeToCode)
     {
         var rhs        = AstFactory.BuildStringNode(Value.Replace(@"\", @"\\"));
         var assignment = AstFactory.BuildAssignment(GetAstIdentifierForOutputIndex(0), rhs);
         return(new[] { assignment });
     }
     else
     {
         return(base.BuildAst(inputAstNodes, context));
     }
 }
Ejemplo n.º 50
0
 /// <summary>
 /// Creates a P# static analysis process.
 /// </summary>
 public static StaticAnalysisProcess Create(CompilationContext context)
 {
     return(new StaticAnalysisProcess(context));
 }
Ejemplo n.º 51
0
 internal override IEnumerable <AssociativeNode> BuildAst(List <AssociativeNode> inputAstNodes, CompilationContext context)
 {
     return(Controller.BuildAst(this, inputAstNodes));
 }
Ejemplo n.º 52
0
        private const byte Else = 1; // End of the 'then' block and beginning of 'else' block.

        public static void Emit(byte[] instruction, CompilationContext context)
        {
            Emit(instruction, context, null);
        }
Ejemplo n.º 53
0
 public int GetSizeOfAllLocalVariables(CompilationContext context)
 {
     return 0;
 }
Ejemplo n.º 54
0
 public abstract void Emit(Type sourceType, Type targetType, CompilationContext context);
Ejemplo n.º 55
0
        private static void Emit(byte[] instruction, CompilationContext context, IEnumerable <IOperation> operationsElse)
        {
            // 2X000000
            // X: End type (0 = End, 1 = Else).

            byte terminationType = instruction[TerminationTypeIndex];

            switch (terminationType)
            {
            case End:
                break;

            case Else:
                // Start a new operation block with the 'else' instruction to signal that there is the 'then' block just above it.
                context.BlockStack.Push(new OperationBlock(instruction));
                return;

            default:
                throw new TamperCompilationException($"Unknown conditional termination type {terminationType}");
            }

            // Use the conditional begin instruction stored in the stack.
            var      upperInstruction = context.CurrentBlock.BaseInstruction;
            CodeType codeType         = InstructionHelper.GetCodeType(upperInstruction);

            // Pop the current block of operations from the stack so control instructions
            // for the conditional can be emitted in the upper block.
            IEnumerable <IOperation> operations = context.CurrentOperations;

            context.BlockStack.Pop();

            // If the else operations are already set, then the upper block must not be another end.
            if (operationsElse != null && codeType == CodeType.EndConditionalBlock)
            {
                throw new TamperCompilationException($"Expected an upper 'if' conditional instead of 'end conditional'");
            }

            ICondition condition;

            switch (codeType)
            {
            case CodeType.BeginMemoryConditionalBlock:
                condition = MemoryConditional.Emit(upperInstruction, context);
                break;

            case CodeType.BeginKeypressConditionalBlock:
                condition = KeyPressConditional.Emit(upperInstruction, context);
                break;

            case CodeType.BeginRegisterConditionalBlock:
                condition = RegisterConditional.Emit(upperInstruction, context);
                break;

            case CodeType.EndConditionalBlock:
                terminationType = upperInstruction[TerminationTypeIndex];
                // If there is an end instruction above then it must be an else.
                if (terminationType != Else)
                {
                    throw new TamperCompilationException($"Expected an upper 'else' conditional instead of {terminationType}");
                }
                // Re-run the Emit with the else operations set.
                Emit(instruction, context, operations);
                return;

            default:
                throw new TamperCompilationException($"Conditional end does not match code type {codeType} in Atmosphere cheat");
            }

            // Create a conditional block with the current operations and nest it in the upper
            // block of the stack.

            IfBlock block = new IfBlock(condition, operations, operationsElse);

            context.CurrentOperations.Add(block);
        }
Ejemplo n.º 56
0
 public void PushAddress(CompilationContext context)
 {
     ((IHasAddress)Tokens.Last()).PushAddress(context);
 }
Ejemplo n.º 57
0
 public ExpressionType GetExpressionType(CompilationContext context)
 {
     return ((IHasType)Tokens[0]).GetExpressionType(context);
 }
Ejemplo n.º 58
0
        /// <summary>
        /// Compiles the transient unit. 'PreCompile' should be called first!
        /// </summary>
        internal bool Compile(CompilationContext /*!*/ context, EvalKinds kind)
        {
            Analyzer analyzer = null;

            try
            {
                analyzer = new Analyzer(context);

                // perform pre-analysis on types and functions:
                if (types != null)
                {
                    analyzer.PreAnalyze(types.Values);
                }

                if (functions != null)
                {
                    analyzer.PreAnalyze(functions.Values);
                }

                // perform member analysis on types and functions:
                if (types != null)
                {
                    analyzer.AnalyzeMembers(types.Values);
                }
                if (functions != null)
                {
                    analyzer.AnalyzeMembers(functions.Values);
                }

                if (context.Errors.AnyFatalError)
                {
                    return(false);
                }

                // perform full analysis:
                analyzer.Analyze(sourceUnit);

                if (context.Errors.AnyFatalError)
                {
                    return(false);
                }

                // perform post analysis:
                analyzer.PostAnalyze();
            }
            catch (CompilerException)
            {
                return(false);
            }
            finally
            {
                resolvingScriptContext = null;
                referringType          = null;
            }

            // do not emit anything if there was parse/analysis error:
            if (context.Errors.AnyError)
            {
                return(false);
            }

            DefineBuilders();

            // define constructed types:
            analyzer.DefineConstructedTypeBuilders();

            CodeGenerator cg = new CodeGenerator(context);

            sourceUnit.Emit(cg);
            return(true);
        }
Ejemplo n.º 59
0
 public IFunction ToInput(System.Linq.Expressions.Expression parameter, ICLRBoundaryMap rootTypeMap, CompilationContext info) =>
 new Array1DFunc(parameter);
        internal static TemplateDelegate CompileView(ViewReaderFactory readerFactoryFactory, string templatePath, CompilationContext compilationContext)
        {
            var configuration = compilationContext.Configuration;
            IEnumerable <object> tokens;

            using (var sr = readerFactoryFactory(configuration, templatePath))
            {
                using (var reader = new ExtendedStringReader(sr))
                {
                    tokens = Tokenizer.Tokenize(reader).ToArray();
                }
            }

            var layoutToken = tokens.OfType <LayoutToken>().SingleOrDefault();

            var expressions  = ExpressionBuilder.ConvertTokensToExpressions(tokens, configuration);
            var compiledView = FunctionBuilder.Compile(expressions, compilationContext);

            if (layoutToken == null)
            {
                return(compiledView);
            }

            var fs         = configuration.FileSystem;
            var layoutPath = fs.Closest(templatePath, layoutToken.Value + ".hbs");

            if (layoutPath == null)
            {
                throw new InvalidOperationException($"Cannot find layout '{layoutToken.Value}' for template '{templatePath}'");
            }

            var compiledLayout = CompileView(readerFactoryFactory, layoutPath, new CompilationContext(compilationContext));

            return((in EncodedTextWriter writer, BindingContext context) =>
            {
                var config = context.Configuration;
                using var bindingContext = BindingContext.Create(config, null);
                foreach (var pair in context.ContextDataObject)
                {
                    switch (pair.Key.WellKnownVariable)
                    {
                    case WellKnownVariable.Parent:
                    case WellKnownVariable.Root:
                        continue;
                    }

                    bindingContext.ContextDataObject[pair.Key] = pair.Value;
                }

                using var innerWriter = ReusableStringWriter.Get(config.FormatProvider);
                using var textWriter = new EncodedTextWriter(innerWriter, config.TextEncoder, FormatterProvider.Current, true);
                compiledView(textWriter, context);
                var inner = innerWriter.ToString();

                var viewModel = new LayoutViewModel(inner, context.Value);
                bindingContext.Value = viewModel;

                compiledLayout(writer, bindingContext);
            });