internal static IDynamic Eval(IEnvironment environment, IArgs args) { var x = args[0]; if (x.TypeCode != LanguageTypeCode.String) { return(x); } var compiler = new CompilerService(environment); var context = environment.Context; var e = compiler.CompileEvalCode(x.ConvertToString().BaseValue, context.Strict); using (var c = environment.EnterContext()) { c.ThisBinding = context.ThisBinding; c.LexicalEnviroment = context.LexicalEnviroment; c.VariableEnviroment = context.VariableEnviroment; if (e.Strict) { var s = context.LexicalEnviroment.NewDeclarativeEnvironment(); c.LexicalEnviroment = s; c.VariableEnviroment = s; } return(e.Code(environment, environment.EmptyArgs)); } }
public void VariableDeclarationTest() { // GIVEN var source = @" function max(a: number, b: number): number do function temp: number do skip; end; return temp(); end; var a: number = 10 + 10; do var b: number = max(a + a, false); end; "; var compilerService = new CompilerService(); var analyzer = new SemanticParser(compilerService); // WHEN var node = ParseWithAbstractTreeVisitor(Compiler, source); analyzer.Visit(node as CompilationUnit); // THEN Assert.NotNull(compilerService.FindVariable("a")); Assert.AreEqual(0, compilerService.Errors.Count); Assert.AreEqual(0, compilerService.Warnings.Count); }
private IRuntimeContextInstance LoadAndCreate(CompilerService compiler, Environment.ICodeSource code, ExternalContextData externalContext) { var moduleHandle = CreateModuleFromSource(compiler, code, externalContext); var loadedHandle = _engine.LoadModuleImage(moduleHandle); return(_engine.NewObject(loadedHandle.Module, externalContext)); }
public Process CreateProcess(IHostApplication host, ICodeSource src, CompilerService compilerSvc) { SetGlobalEnvironment(host, src); var module = _engine.LoadModuleImage(compilerSvc.CreateModule(src)); return(InitProcess(host, src, ref module)); }
private void btnFindError_Click(object sender, EventArgs e) { txtCompileStatus.Text = "Compiling..."; var inputSchema = GenerateSchema(grInput); var outputSchema = GenerateSchema(grOutput); var tempFile = Path.GetTempFileName(); var result = CompilerService.GenerateCodeAndCompile(tempFile, inputSchema, outputSchema, GetCode()); File.Delete(tempFile); txtCompileStatus.Text = string.Empty; // Check for errors if (result.CompilerResult.Errors.Count > 0) { foreach (CompilerError CompErr in result.CompilerResult.Errors) { //lblCompileStatus.ForeColor = Color.Red; txtCompileStatus.ForeColor = Color.Red; txtCompileStatus.Text = txtCompileStatus.Text + "Line number " + (CompErr.Line - result.CodeLine) + " Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";" + Environment.NewLine; } return; } else { //Successful Compile //lblCompileStatus.ForeColor = Color.Green; txtCompileStatus.ForeColor = Color.Green; txtCompileStatus.Text = "Success!"; } }
public ExpressionFactory(CompilerService compilerService) { if (compilerService == null) ThrowHelper.ThrowArgumentNullException(() => compilerService); _operators = new Dictionary<string, OperatorNode>() { {"+", new AdditionOperatorNode()}, {"-", new SubtractionOperatorNode()}, {"*", new MultiplicationOperatorNode()}, {"/", new DivisionOperatorNode()}, {"<", new LessThanOperatorNode()}, {">", new GreaterThanOperatorNode()}, {"<=", new LessThanOrEqualOperatorNode()}, {">=", new GreaterThanOrEqualOperatorNode()}, {"==", new EqualityOperatorNode()}, {"!=", new InequalityOperatorNode()}, {"and", new ConjunctionBinaryOperatorNode()}, {"or", new DisjunctionOperatorNode()}, {"not", new NegationOperatorNode()}, }; CompilerService = compilerService; CompilerService.ExpressionFactory = this; }
public void Test() { Properties.CommandLineProperties.Add("Version", "0.0.0.0"); CompilerService.ExecuteBuildTask(Assembly.GetExecutingAssembly().Location, typeof(BuildTask).Name, new List <string>()); }
private void DocumentSaved(object sender, TextDocumentFileActionEventArgs e) { if (e.FileActionType == FileActionTypes.ContentSavedToDisk) { CompilerService.Process(e.FilePath); } }
private void DocumentSaved(object sender, TextDocumentFileActionEventArgs e) { if (e.FileActionType == FileActionTypes.ContentSavedToDisk) { // Check if filename is absolute because when debugging, script files are sometimes dynamically created. if (string.IsNullOrEmpty(e.FilePath) || !Path.IsPathRooted(e.FilePath)) { return; } var item = WebCompilerPackage._dte.Solution.FindProjectItem(e.FilePath); if (item != null && item.ContainingProject != null) { string configFile = item.ContainingProject.GetConfigFile(); ErrorList.CleanErrors(e.FilePath); if (File.Exists(configFile)) { CompilerService.SourceFileChanged(configFile, e.FilePath); } } } }
public void AttachFromString(CompilerService compiler, string text, string typeName) { var code = _engine.Loader.FromString(text); ThrowIfTypeExist(typeName, code); LoadAndRegister(typeof(AttachedScriptsFactory), compiler, typeName, code); }
public ScriptModuleHandle CreateModuleFromSource(CompilerService compiler, Environment.ICodeSource code, ExternalContextData externalContext) { return(new ScriptModuleHandle() { Module = CompileModuleFromSource(compiler, code, externalContext) }); }
public ModuleHandle AttachFromString(CompilerService compiler, string text, string typeName) { ThrowIfTypeExist(typeName); var code = _engine.Loader.FromString(text); return(LoadAndRegister(typeof(AttachedScriptsFactory), compiler, typeName, code)); }
public ConstantLiteralFactory(CompilerService compilerService) { if (compilerService == null) ThrowHelper.ThrowArgumentNullException(() => compilerService); CompilerService = compilerService; CompilerService.ConstantLiteralFactory = this; }
private IRuntimeContextInstance LoadAndCreate(CompilerService compiler, Environment.ICodeSource code) { compiler.DefineVariable("ЭтотОбъект", SymbolType.ContextProperty); var moduleHandle = compiler.CreateModule(code); var loadedHandle = _engine.LoadModuleImage(moduleHandle); return(_engine.NewObject(loadedHandle.Module)); }
public StatementFactory(CompilerService compilerService) { if (compilerService == null) ThrowHelper.ThrowArgumentNullException(() => compilerService); CompilerService = compilerService; CompilerService.StatementFactory = this; }
private void DocumentSaved(object sender, TextDocumentFileActionEventArgs e) { if (e.FileActionType == FileActionTypes.ContentSavedToDisk) { string file = e.FilePath.Replace(Constants.DEFAULTS_FILENAME, Constants.CONFIG_FILENAME); CompilerService.Process(file, force: true); } }
public IActionResult UploadMultipartResource(string projectid, [FromForm] ApplicationUploadModel req, IFormFile file = null) { try { if (req == null) { return(BadRequest("Request object can not be null")); } byte[] byteArrayStream = null; if (file != null) { Stream stream = Request.Body; byteArrayStream = Kitsune.API2.EnvConstants.Constants.ReadInputStream(file); } req.ProjectId = projectid; var projectDetailsRequestModel = new GetProjectDetailsRequestModel { ProjectId = req.ProjectId, ExcludeResources = false, UserEmail = req.UserEmail }; var compilerService = new CompilerService(); var updatePageRequest = new CreateOrUpdateResourceRequestModel { Errors = null, SourcePath = req.SourcePath.Trim(), ProjectId = req.ProjectId, UserEmail = req.UserEmail, PageType = req._PageType, ResourceType = req._ResourceType, Configuration = !string.IsNullOrEmpty(req.Configuration) ? JsonConvert.DeserializeObject <Dictionary <string, object> >(req.Configuration) : null, ByteArrayStream = byteArrayStream }; var validationResult = updatePageRequest.Validate(); if (validationResult.Any()) { return(BadRequest(validationResult)); } if (MongoConnector.CreateOrUpdateResource(updatePageRequest)) { return(Ok(new ResourceCompilationResult { Success = true })); } return(BadRequest()); } catch (Exception ex) { return(BadRequest(ex)); } }
/// <summary> /// When overridden in a derived class, executes the task. /// </summary> /// <returns> /// true if the task successfully executed; otherwise, false. /// </returns> public override bool Execute() { try { // Get arguments var args = GenerateArguments(); if (null == args) { // If we get no result, the derived class should have set the log messages. return(false); } else { if (0 == args.Length) { // If we get no parameters, we don't need to call the compiler. return(true); } else { // Show arguments (low level) var builder = new CommandLineBuilder(); foreach (var arg in args) { if (arg.StartsWith("--")) { builder.AppendSwitch(arg); } else { builder.AppendFileNameIfNotNull(arg); } } Log.LogCommandLine(MessageImportance.Normal, builder.ToString()); // Invoke return(CompilerService.Execute(args, Log)); } } } catch (AggregateException agex) { foreach (var ex in agex.Flatten().InnerExceptions) { ErrorLog.DumpError(ex); Log.LogErrorFromException(ex); } return(false); } catch (Exception ex) { ErrorLog.DumpError(ex); Log.LogErrorFromException(ex); return(false); } }
private static ExtendedCompileResult CompileComponent(string inputPath, CliCompileOptions cliOptions) { var compiler = new CompilerService(); var resources = new MappedDirectoryResourceProvider(cliOptions.DefaultIconPath); // Icon paths are specified as: // --icon resourceName fileName // --icon wire_32 wire_32.png wire_64 wire_64.png for (int i = 0; i < cliOptions.IconPaths.Count; i += 2) resources.Mappings.Add(cliOptions.IconPaths[i], cliOptions.IconPaths[i + 1]); var options = new CompileOptions() { CertificateThumbprint = cliOptions.CertificateThumbprint }; if (cliOptions.Sign && cliOptions.CertificateThumbprint == null) options.CertificateThumbprint = SelectCertificate(); string outputPath = GetOutputPath(inputPath, cliOptions); var outputDirectory = Path.GetDirectoryName(outputPath); if (!Directory.Exists(outputDirectory)) Directory.CreateDirectory(outputDirectory); ComponentCompileResult result; using (var input = File.OpenRead(inputPath)) using (var output = File.OpenWrite(outputPath)) { result = compiler.Compile(input, output, resources, options); } var extendedResult = new ExtendedCompileResult(result) { Input = inputPath }; if (result.Success) { Console.WriteLine("{0} -> {1}", Path.GetFullPath(inputPath), Path.GetFullPath(outputPath)); extendedResult.Output = outputPath; } // Generate preview if (cliOptions.Preview != null) { string previewPath = GetPreviewPath(inputPath, cliOptions); string previewDirectory = Path.GetDirectoryName(previewPath); if (!Directory.Exists(previewDirectory)) Directory.CreateDirectory(previewDirectory); var preview = PreviewRenderer.GetSvgPreview(result.Description, null, true); File.WriteAllBytes(previewPath, preview); } return extendedResult; }
public void CompileAssemblyFromTemplate() { var model = GetCacheTemplateFromProductRepository(); var classFile = TemplateService.GenerateCacheCode(model); var assembly = CompilerService.GenerateAssemblyFromCode(typeof(IProductRepository).Assembly, model.Name, classFile); var type = assembly.GetTypes().FirstOrDefault(); Assert.Contains(model.Name, assembly.GetTypes().Select(x => x.Name)); }
public void CompileMultipleAssemblies() { var model = GetCacheTemplateFromProductRepository(); var classFile = TemplateService.GenerateCacheCode(model); var assembly1 = CompilerService.GenerateAssemblyFromCode(typeof(IProductRepository).Assembly, model.Name, classFile); var assembly2 = CompilerService.GenerateAssemblyFromCode(typeof(IProductRepository).Assembly, model.Name, classFile); Assert.NotEqual(assembly1.GetHashCode(), assembly2.GetHashCode()); }
public void HandleBarsIsSupported() { var result = CompilerService.IsSupported(".HANDLEBARS"); Assert.IsTrue(result); result = CompilerService.IsSupported(".hbs"); Assert.IsTrue(result); }
public void IdentifyOperations() { var compiler = new CompilerService(null, null); var elements = compiler.IdentifyElements(SNIPPETS.Op1_Op2).Select(Extensions.ToFullName).ToArray(); Assert.AreEqual(2, elements.Length); Assert.AreEqual("SNIPPET.Op2", elements[1]); }
private void DefineConstants(CompilerService compilerSvc) { var definitions = GetWorkingConfig()["preprocessor.define"]?.Split(',') ?? new string[0]; foreach (var val in definitions) { compilerSvc.DefinePreprocessorValue(val); } }
public IActionResult UploadTemplate(string projectid, [FromBody] CompileResourceRequest req) { try { if (req == null) { return(BadRequest("Request object can not be null")); } req.ProjectId = projectid; var projectDetailsRequestModel = new GetProjectDetailsRequestModel { ProjectId = req.ProjectId, ExcludeResources = false, UserEmail = req.UserEmail }; var compileResult = CompilerHelper.CompileProjectResource(req); var compilerService = new CompilerService(); var updatePageRequest = new CreateOrUpdateResourceRequestModel { Errors = null, FileContent = req.FileContent, SourcePath = req.SourcePath.Trim(), ClassName = req.ClassName, ProjectId = req.ProjectId, UserEmail = req.UserEmail, UrlPattern = req.UrlPattern, IsStatic = req.IsStatic, IsDefault = req.IsDefault, PageType = req.PageType, KObject = req.KObject, ResourceType = null, Configuration = !string.IsNullOrEmpty(req.Configuration) ? JsonConvert.DeserializeObject <Dictionary <string, object> >(req.Configuration) : null, }; var validationResult = updatePageRequest.Validate(); if (validationResult.Any()) { return(BadRequest(validationResult)); } if (MongoConnector.CreateOrUpdateResource(updatePageRequest)) { return(Ok(compileResult)); } return(BadRequest()); } catch (Exception ex) { return(BadRequest(ex)); } }
internal static void RunFile(string location, string[] args, string[] assembliesLocation) { PrintLnC($"{location} Compiling...", ConsoleColor.White); var fileName = Path.GetFileNameWithoutExtension(location); _ = new CompilerService() .Build(fileName, location, Path.GetExtension(".cs") == ".cs", assembliesLocation) .Run(args); }
public static void Main(string[] args) { string code = "using System; namespace ashok{ public class MyClass{ public static void Main(string[] args){ Console.WriteLine(\"Hola...Working :D\"); } } }"; var compileService = new CompilerService(); var result = compileService.Compile(code); Console.WriteLine(result.Success); Console.WriteLine(result.Result); Console.ReadKey(); }
public Process CreateProcess(IHostApplication host, ICodeSource src, CompilerService compilerSvc) { SetGlobalEnvironment(host, src); Initialize(); _engine.DebugController?.OnMachineReady(_engine.Machine); _engine.DebugController?.WaitForDebugEvent(DebugEventType.BeginExecution); var module = _engine.LoadModuleImage(compilerSvc.CreateModule(src)); return(InitProcess(host, ref module)); }
public void AttachByPath(CompilerService compiler, string path, string typeName) { if (!Utils.IsValidIdentifier(typeName)) throw RuntimeException.InvalidArgumentValue(); var code = _engine.Loader.FromFile(path); ThrowIfTypeExist(typeName, code); LoadAndRegister(typeof(AttachedScriptsFactory), compiler, typeName, code); }
public SkiaSharpFiddleController(ISkiaSharpFiddleView view) { _view = view; _compiler = new CompilerService(); DrawingWidth = DefaultDrawingWidth; DrawingHeight = DefaultDrawingHeight; CompilationMessages = new List <CompilationMessage>(); view.SetController(this); }
private void StartCompile() { string output = CompilerService.ExecuteBuildTask(_buildAssembly, _classToRun, null); if (output != string.Empty) { Defaults.Logger.WriteError("", output); } // var runner = new Runner(Targets.SelectedItem.ToString(), _buildAssembly); // runner.Run(); }
public CompilerViewModel() { GetUidCommand = new Command(async(args) => { await CompilerService.DoGetUIDRequest(); }); PostCodeCommand = new Command(async(args) => { var html = await CompilerService.DoPostCodeRequest(args as string) as string; Result = html; MessagingCenter.Send <CompilerViewModel>(this, "CompileActivityEnded"); }); }
public void AttachByPath(CompilerService compiler, string path, string typeName) { if (!Utils.IsValidIdentifier(typeName)) { throw RuntimeException.InvalidArgumentValue(); } var code = _engine.Loader.FromFile(path); ThrowIfTypeExist(typeName, code); LoadAndRegister(typeof(AttachedScriptsFactory), compiler, typeName, code); }
public ScriptModuleHandle CreateModuleFromSource(CompilerService compiler, Environment.ICodeSource code, ExternalContextData externalContext) { compiler.DefineVariable("ЭтотОбъект", SymbolType.ContextProperty); if (externalContext != null) { foreach (var item in externalContext) { compiler.DefineVariable(item.Key, SymbolType.ContextProperty); } } return(compiler.CreateModule(code)); }
private ModuleHandle LoadAndRegister(Type type, CompilerService compiler, string typeName, Environment.ICodeSource code) { compiler.DefineVariable("ЭтотОбъект", SymbolType.ContextProperty); var moduleHandle = compiler.CreateModule(code); var loadedHandle = _engine.LoadModuleImage(moduleHandle); _loadedModules.Add(typeName, loadedHandle.Module); TypeManager.RegisterType(typeName, type); return(moduleHandle); }
public ModuleImage CompileModuleFromSource(CompilerService compiler, Environment.ICodeSource code, ExternalContextData externalContext) { compiler.DefineVariable("ЭтотОбъект", "ThisObject", SymbolType.ContextProperty); if (externalContext != null) { foreach (var item in externalContext) { compiler.DefineVariable(item.Key, null, SymbolType.ContextProperty); } } return(compiler.Compile(code)); }
public InterpreterContext(CompilerService compilerService) { if (compilerService == null) ThrowHelper.ThrowArgumentNullException(() => compilerService); CompilerService = compilerService; _variables = new Stack<Dictionary<string, VariableContext>>(); _functions = new Stack<Dictionary<string, FunctionContextBase>>(); _macros = new Stack<Dictionary<string, MacroContextBase>>(); _types = new Stack<Dictionary<string, TypeContextBase>>(); InitializeFunctions(); PushBlock(); }
public void WrongAdditionTypeTest() { // GIVEN var source = MultiLine( "false + false;" ); var compilerService = new CompilerService(); var analyzer = new ExpressionTypeAnalyzer(compilerService); // WHEN var node = ParseWithAbstractTreeVisitor(Compiler, source); var type = analyzer.VisitChild(node); // THEN Assert.AreEqual(2, compilerService.Errors.Count); }
public void TestCompile() { var assembly = Assembly.GetExecutingAssembly(); string testComponentResource = assembly.GetManifestResourceNames().First(r => r.EndsWith("TestComponent.xml")); var compiler = new CompilerService(); var output = new MemoryStream(); ComponentCompileResult result; using (var input = assembly.GetManifestResourceStream(testComponentResource)) { result = compiler.Compile(input, output, Mock.Of<IResourceProvider>(), new CompileOptions()); } Assert.That(result.Success); Assert.That(result.ComponentName, Is.EqualTo("Wire")); }
public override IObject Construct(IEnvironment environment, IArgs args) { string formalParametersString, functionBody; if (args.IsEmpty) { formalParametersString = ""; functionBody = ""; } else if (args.Count == 1) { formalParametersString = ""; functionBody = args[0].ConvertToString().BaseValue; } else { var sb = new StringBuilder(); var limit = args.Count - 1; for (int i = 0; i < limit; i++) { if (sb.Length > 0) { sb.Append(","); } sb.Append(args[i].ConvertToString().BaseValue); } formalParametersString = sb.ToString(); functionBody = args[limit].ConvertToString().BaseValue; } var compiler = new CompilerService(environment); var executableCode = compiler.CompileFunctionCode(functionBody, environment.Context.Strict); var formalParameters = compiler.CompileFormalParameterList(formalParametersString); var func = environment.CreateFunction(executableCode, formalParameters, environment.GlobalEnvironment); return func; }
public void InterpreterTest() { // GIVEN var source = @" var person: any = 0; person.name = 'John Doe'; person.age = 24; writeline(person.name); function max(a: number, b: number) : number do writeline('call function max'); if (a > b) result = a; else result = b; end; end; function min(a: number, b: number) : number do writeline('call function min'); if (a < b) result = a; else result = b; end; end; var j : number = 0; foreach (var i : number in [1,2,3,4,5,6]) do j = max(3 * i, min(4 * i, 5 * i)); writeline(j + '. Hello World!'); end; "; var compilerService = new CompilerService(); var analyzer = new CodeInterpreter(compilerService); // WHEN var node = ParseWithAbstractTreeVisitor(Compiler, source); analyzer.VisitChild(node as CompilationUnit); // THEN }
private IRuntimeContextInstance LoadAndCreate(CompilerService compiler, Environment.ICodeSource code) { compiler.DefineVariable("ЭтотОбъект", SymbolType.ContextProperty); var moduleHandle = compiler.CreateModule(code); var loadedHandle = _engine.LoadModuleImage(moduleHandle); return _engine.NewObject(loadedHandle.Module); }
public IRuntimeContextInstance LoadFromString(CompilerService compiler, string text) { var code = _engine.Loader.FromString(text); return LoadAndCreate(compiler, code); }
public IRuntimeContextInstance LoadFromPath(CompilerService compiler, string path) { var code = _engine.Loader.FromFile(path); return LoadAndCreate(compiler, code); }
public ModuleWriter(CompilerService compilerService) { _compiler = compilerService; }
public void MacroDeclarationTest() { // GIVEN var source = @" macro convertToWhile(tree : { * > foreach }) do end; implicit macro inline(tree: { * > while[body] }) do foreach (var t : any in tree) do writeline(find(t, '{ if[condition] }')); end; end; foreach (var i : Number in [1,2,3,4]) do writeline(i); end; var i : number = 0; var n : number = 100; var sum : number = 0; while (i < n) do sum := sum + 2 * i; i := i + 1; end; while (false) do var i : number = 1; end; if (24 > 42) skip; end; if (24 > 42) skip; end; if (24 > 42) skip; end; "; var compilerService = new CompilerService(); var analyzer = new MacroInterpreter(compilerService); // WHEN var node = ParseWithAbstractTreeVisitor(Compiler, source); analyzer.VisitChild(node as CompilationUnit); // THEN }
private IRuntimeContextInstance LoadAndCreate(CompilerService compiler, Environment.ICodeSource code, ExternalContextData externalContext) { compiler.DefineVariable("ЭтотОбъект", SymbolType.ContextProperty); if(externalContext != null) { foreach (var item in externalContext) { compiler.DefineVariable(item.Key, SymbolType.ContextProperty); } } var moduleHandle = compiler.CreateModule(code); var loadedHandle = _engine.LoadModuleImage(moduleHandle); return _engine.NewObject(loadedHandle.Module, externalContext); }
public Process CreateProcess(IHostApplication host, ICodeSource src, CompilerService compilerSvc) { SetGlobalEnvironment(host, src); var module = _engine.LoadModuleImage(compilerSvc.CreateModule(src)); return InitProcess(host, src, ref module); }
public IRuntimeContextInstance LoadFromPath(CompilerService compiler, string path) { return LoadFromPath(compiler, path, null); }
internal static IDynamic Eval(IEnvironment environment, IArgs args) { var x = args[0]; if (x.TypeCode != LanguageTypeCode.String) { return x; } var compiler = new CompilerService(environment); var context = environment.Context; var e = compiler.CompileEvalCode(x.ConvertToString().BaseValue, context.Strict); using (var c = environment.EnterContext()) { c.ThisBinding = context.ThisBinding; c.LexicalEnviroment = context.LexicalEnviroment; c.VariableEnviroment = context.VariableEnviroment; if (e.Strict) { var s = context.LexicalEnviroment.NewDeclarativeEnvironment(); c.LexicalEnviroment = s; c.VariableEnviroment = s; } return e.Code(environment, environment.EmptyArgs); } }
private void LoadAndRegister(Type type, CompilerService compiler, string typeName, Environment.ICodeSource code) { if(_loadedModules.ContainsKey(typeName)) { return; } compiler.DefineVariable("ЭтотОбъект", SymbolType.ContextProperty); var moduleHandle = compiler.CreateModule(code); var loadedHandle = _engine.LoadModuleImage(moduleHandle); _loadedModules.Add(typeName, loadedHandle.Module); using(var md5Hash = MD5.Create()) { var hash = GetMd5Hash(md5Hash, code.Code); _fileHashes.Add(typeName, hash); } TypeManager.RegisterType(typeName, type); }