private LanguagePreProcessor GetPreProcessor(ScriptingLanguage language)
		{
			LanguagePreProcessor preProcessor = languagePreProcessors[language];
			if (preProcessor == null)
				throw new AspViewException("Unsupported view language '{0}'", language);
			return preProcessor;
		}
		public static string GetExtension(ScriptingLanguage language)
		{
			if (language == ScriptingLanguage.CSharp)
				return ".cs";
			if (language == ScriptingLanguage.VbNet)
				return ".vb";
			throw new AspViewException("Unsupported language '{0}'", language);
		}
 public virtual string GetProjectHeaderTemplate(ScriptingLanguage language)
 {
     string[] textArray1 = new string[] { 
         "<?xml version=\"1.0\" encoding=\"utf-8\"?>", "<Project ToolsVersion=\"{0}\" DefaultTargets=\"Build\" xmlns=\"{6}\">", "  <PropertyGroup>", "\t<Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>", "\t<Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>", "\t<ProductVersion>{1}</ProductVersion>", "\t<SchemaVersion>2.0</SchemaVersion>", "\t<RootNamespace>{8}</RootNamespace>", "\t<ProjectGuid>{{{2}}}</ProjectGuid>", "\t<OutputType>Library</OutputType>", "\t<AppDesignerFolder>Properties</AppDesignerFolder>", "\t<AssemblyName>{7}</AssemblyName>", "\t<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>", "\t<FileAlignment>512</FileAlignment>", "\t<BaseDirectory>Assets</BaseDirectory>", "  </PropertyGroup>", 
         "  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">", "\t<DebugSymbols>true</DebugSymbols>", "\t<DebugType>full</DebugType>", "\t<Optimize>false</Optimize>", "\t<OutputPath>Temp\\bin\\Debug\\</OutputPath>", "\t<DefineConstants>{5}</DefineConstants>", "\t<ErrorReport>prompt</ErrorReport>", "\t<WarningLevel>4</WarningLevel>", "\t<NoWarn>0169</NoWarn>", "  </PropertyGroup>", "  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">", "\t<DebugType>pdbonly</DebugType>", "\t<Optimize>true</Optimize>", "\t<OutputPath>Temp\\bin\\Release\\</OutputPath>", "\t<ErrorReport>prompt</ErrorReport>", "\t<WarningLevel>4</WarningLevel>", 
         "\t<NoWarn>0169</NoWarn>", "  </PropertyGroup>", "  <ItemGroup>", "\t<Reference Include=\"System\" />", "    <Reference Include=\"System.XML\" />", "\t<Reference Include=\"System.Core\" />", "\t<Reference Include=\"System.Xml.Linq\" />", "\t<Reference Include=\"UnityEngine\">", "\t  <HintPath>{3}</HintPath>", "\t</Reference>", "\t<Reference Include=\"UnityEditor\">", "\t  <HintPath>{4}</HintPath>", "\t</Reference>", "  </ItemGroup>", "  <ItemGroup>", string.Empty
      };
     return string.Join("\r\n", textArray1);
 }
Esempio n. 4
0
        private string ProjectHeader(MonoIsland island, string[] additionalDefines)
        {
            string            text     = "v3.5";
            string            text2    = "4";
            string            text3    = "4.0";
            string            text4    = "10.0.20506";
            string            text5    = ".";
            ScriptingLanguage language = SolutionSynchronizer.ScriptingLanguageFor(island);

            if (PlayerSettingsEditor.IsLatestApiCompatibility(island._api_compatibility_level))
            {
                text  = "v4.6";
                text2 = "6";
            }
            else if (ScriptEditorUtility.GetScriptEditorFromPreferences() == ScriptEditorUtility.ScriptEditor.Rider)
            {
                text = "v4.5";
            }
            else if (this._settings.VisualStudioVersion == 9)
            {
                text3 = "3.5";
                text4 = "9.0.21022";
            }
            object[] array = new object[]
            {
                text3,
                text4,
                this.ProjectGuid(island._output),
                this._settings.EngineAssemblyPath,
                this._settings.EditorAssemblyPath,
                string.Join(";", new string[]
                {
                    "DEBUG",
                    "TRACE"
                }.Concat(this._settings.Defines).Concat(island._defines).Concat(additionalDefines).Distinct <string>().ToArray <string>()),
                SolutionSynchronizer.MSBuildNamespaceUri,
                Path.GetFileNameWithoutExtension(island._output),
                EditorSettings.projectGenerationRootNamespace,
                text,
                text2,
                text5
            };
            string result;

            try
            {
                result = string.Format(this._settings.GetProjectHeaderTemplate(language), array);
            }
            catch (Exception)
            {
                throw new NotSupportedException("Failed creating c# project because the c# project header did not have the correct amount of arguments, which is " + array.Length);
            }
            return(result);
        }
Esempio n. 5
0
 private void CompileScript(Evidence evidence)
 {
     for (ScriptingLanguage lang = ScriptingLanguage.JScript; lang <= ScriptingLanguage.CSharp; lang++)
     {
         int idx = (int)lang;
         if (_typeDeclsByLang[idx].Count > 0)
         {
             CompileAssembly(lang, _typeDeclsByLang[idx], lang.ToString(), evidence);
         }
     }
 }
Esempio n. 6
0
        private void Form1_Load(object sender, EventArgs e)
        {
            // selecting tabPage2 initializes the BasicIdeCtl
            tabControl1.SelectedTab = tabPage2;
            tabControl1.SelectedTab = tabPage1;

            basicIdeCtl1.AddScriptableObjectModel(typeof(ScriptingLanguage));

            // Initialize Language with this as the IHost
            ScriptingLanguage.SetHost(this);
        }
Esempio n. 7
0
        internal static string ToSerializedValue(this ScriptingLanguage value)
        {
            switch (value)
            {
            case ScriptingLanguage.JScript:
                return("JScript");

            case ScriptingLanguage.VBScript:
                return("VBScript");
            }
            return(null);
        }
        private string ProjectHeader(MonoIsland island,
                                     ScriptCompilerBase.ResponseFileData responseFileData)
        {
            string            targetframeworkversion = "v3.5";
            string            targetLanguageVersion  = "4";
            string            toolsversion           = "4.0";
            string            productversion         = "10.0.20506";
            string            baseDirectory          = ".";
            ScriptingLanguage language = ScriptingLanguageFor(island);

            if (PlayerSettingsEditor.IsLatestApiCompatibility(island._api_compatibility_level))
            {
                if (ScriptEditorUtility.GetScriptEditorFromPreferences() == ScriptEditorUtility.ScriptEditor.Rider ||
                    ScriptEditorUtility.GetScriptEditorFromPreferences() == ScriptEditorUtility.ScriptEditor.VisualStudioCode)
                {
                    targetframeworkversion = "v4.5";
                }
                else
                {
                    targetframeworkversion = "v4.7.1";
                }
                targetLanguageVersion = "7.2";
            }
            else if (_settings.VisualStudioVersion == 9)
            {
                toolsversion   = "3.5";
                productversion = "9.0.21022";
            }

            var arguments = new object[]
            {
                toolsversion, productversion, ProjectGuid(island._output),
                _settings.EngineAssemblyPath,
                _settings.EditorAssemblyPath,
                string.Join(";", new[] { "DEBUG", "TRACE" }.Concat(island._defines).Concat(responseFileData.Defines).Distinct().ToArray()),
                MSBuildNamespaceUri,
                Path.GetFileNameWithoutExtension(island._output),
                EditorSettings.projectGenerationRootNamespace,
                targetframeworkversion,
                targetLanguageVersion,
                baseDirectory,
                island._allowUnsafeCode | responseFileData.Unsafe
            };

            try
            {
                return(string.Format(_settings.GetProjectHeaderTemplate(language), arguments));
            }
            catch (Exception)
            {
                throw new System.NotSupportedException("Failed creating c# project because the c# project header did not have the correct amount of arguments, which is " + arguments.Length);
            }
        }
Esempio n. 9
0
 public static string GetExtension(ScriptingLanguage language)
 {
     if (language == ScriptingLanguage.CSharp)
     {
         return(".cs");
     }
     if (language == ScriptingLanguage.VbNet)
     {
         return(".vb");
     }
     throw new AspViewException("Unsupported language '{0}'", language);
 }
Esempio n. 10
0
        private void AddScript(Compiler compiler)
        {
            NavigatorInput input = compiler.Input;

            ScriptingLanguage lang = ScriptingLanguage.JScript;
            string            implementsNamespace = null;

            if (input.MoveToFirstAttribute())
            {
                do
                {
                    if (input.LocalName == input.Atoms.Language)
                    {
                        string langName = input.Value.ToLower(CultureInfo.InvariantCulture);   // Case insensetive !
                        if (langName == "jscript" || langName == "javascript")
                        {
                            lang = ScriptingLanguage.JScript;
                        }
                        else if (langName == "vb" || langName == "visualbasic")
                        {
                            lang = ScriptingLanguage.VisualBasic;
                        }
                        else if (langName == "c#" || langName == "csharp")
                        {
                            lang = ScriptingLanguage.CSharp;
                        }
                        else
                        {
                            throw new XsltException(Res.Xslt_ScriptInvalidLang, langName);
                        }
                    }
                    else if (input.LocalName == input.Atoms.ImplementsPrefix)
                    {
                        if (!PrefixQName.ValidatePrefix(input.Value))
                        {
                            throw XsltException.InvalidAttrValue(input.LocalName, input.Value);
                        }
                        implementsNamespace = compiler.ResolveXmlNamespace(input.Value);
                    }
                }while (input.MoveToNextAttribute());
                input.ToParent();
            }
            if (implementsNamespace == null)
            {
                throw new XsltException(Res.Xslt_MissingAttribute, input.Atoms.ImplementsPrefix);
            }
            if (!input.Recurse() || input.NodeType != XPathNodeType.Text)
            {
                throw new XsltException(Res.Xslt_ScriptEmpty);
            }
            compiler.AddScript(input.Value, lang, implementsNamespace, input.BaseURI, input.LineNumber);
            input.ToParent();
        }
Esempio n. 11
0
        CodeDomProvider GetCodeDomProvider(ScriptingLanguage lang)
        {
            switch (lang)
            {
            case ScriptingLanguage.JScript:
                return((CodeDomProvider)Activator.CreateInstance(Type.GetType("Microsoft.JScript.JScriptCodeProvider, " + AssemblyRef.MicrosoftJScript),
                                                                 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, null, null));

            case ScriptingLanguage.CSharp:
            default:
                return(new Microsoft.CSharp.CSharpCodeProvider());
            }
        }
Esempio n. 12
0
            public MSXslScript(XPathNavigator nav
#if NOT_PFX
                               , Evidence evidence
#endif
                               )
            {
#if NOT_PFX
                this.evidence = evidence;
#endif
                code = nav.Value;
                if (nav.MoveToFirstAttribute())
                {
                    do
                    {
                        switch (nav.LocalName)
                        {
                        case "language":
                            switch (nav.Value.ToLower(CultureInfo.InvariantCulture))
                            {
                            case "jscript":
                            case "javascript":
                                language = ScriptingLanguage.JScript; break;

                            case "vb":
                            case "visualbasic":
                                language = ScriptingLanguage.VisualBasic;
                                break;

                            case "c#":
                            case "csharp":
                                language = ScriptingLanguage.CSharp;
                                break;

                            default:
                                throw new XsltException("Invalid scripting language!", null);
                            }
                            break;

                        case "implements-prefix":
                            implementsPrefix = nav.Value;
                            break;
                        }
                    } while (nav.MoveToNextAttribute());
                    nav.MoveToParent();
                }

                if (implementsPrefix == null)
                {
                    throw new XsltException("need implements-prefix attr", null);
                }
            }
Esempio n. 13
0
        private void Form1_Load(object sender, EventArgs e)
        {
            // selecting tabPage2 initializes the BasicIdeCtl
            tabControl1.SelectedTab = tabPage2;
            tabControl1.SelectedTab = tabPage1;

            // use MyFileSystem for reading/writing files
            basicIdeCtl1.VirtualFileSystem = new MyFileSystem();

            basicIdeCtl1.AddScriptableObjectModel(typeof(ScriptingLanguage));

            // Initialize Language with this as the IHost
            ScriptingLanguage.SetHost(this);
        }
Esempio n. 14
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // selecting tabPage2 initializes the BasicIdeCtl
            tabControl1.SelectedIndex = 1;
            basicIdeCtl1.UpdateLayout();
            tabControl1.SelectedIndex = 0;

            // disable automatic updating of the containing window's title
            basicIdeCtl1.AttachToWindow(null, WinWrap.Basic.ManageConstants.OnCaptionChange);

            basicIdeCtl1.AddScriptableObjectModel(typeof(ScriptingLanguage));

            // Initialize Language with this as the IHost
            ScriptingLanguage.SetHost(this);
        }
        public UnixSocketEnvironment(ScriptingLanguage language, UnixSocketFuzzLocation fuzzLocation)
            : base(language)
        {
            _fuzzLocation = fuzzLocation;

            _extraImports.Add ("Fuzzer.Scripting.Environments");

            ParameterInfo fuzzLocationParameterInfo = new ParameterInfo ("fuzzLocation", typeof(UnixSocketFuzzLocation));
            base.GlobalParameters.Add (fuzzLocationParameterInfo);
            base.SetParameter (fuzzLocationParameterInfo, fuzzLocation);

            MethodInfo hookTypeGetterInfo = new MethodInfo ("HookType", typeof(UnixSocketHookType));
            base.GlobalMethods.Add (hookTypeGetterInfo);
            base.SetMethod (hookTypeGetterInfo, new GetHookTypeDelegate (GetHookType));
        }
        public TestEnvironment(ScriptingLanguage language, TextWriter strWriter)
            : base(language)
        {
            _writer = strWriter;
            MethodInfo fooMethodInfo = new MethodInfo("Foo", null, new ParameterInfo("text", typeof(string)));
            MethodInfo barMethodInfo = new MethodInfo("Bar", typeof(string));

            base.GlobalMethods.Add(fooMethodInfo);
            base.SetMethod(fooMethodInfo, new Action<string>(FooMethod));

            base.GlobalMethods.Add(barMethodInfo);
            base.SetMethod(barMethodInfo, new BarMethodDelegate(BarMethod));

            ParameterInfo writerParameterInfo = new ParameterInfo("Writer", typeof(TextWriter));
            base.GlobalParameters.Add(writerParameterInfo);
            base.SetParameter(writerParameterInfo, _writer);
        }
 public virtual string GetProjectFooterTemplate(ScriptingLanguage language)
 {
     return(string.Join("\r\n", new[]
     {
         @"  </ItemGroup>",
         @"  <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />",
         @"  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. ",
         @"       Other similar extension points exist, see Microsoft.Common.targets.",
         @"  <Target Name=""BeforeBuild"">",
         @"  </Target>",
         @"  <Target Name=""AfterBuild"">",
         @"  </Target>",
         @"  -->",
         @"</Project>",
         @""
     }));
 }
Esempio n. 18
0
        internal void AddScript(string source, ScriptingLanguage lang, string ns, string fileName, int lineNumber)
        {
            ValidateExtensionNamespace(ns);

            for (ScriptingLanguage langTmp = ScriptingLanguage.JScript; langTmp <= ScriptingLanguage.CSharp; langTmp++)
            {
                Hashtable typeDecls = _typeDeclsByLang[(int)langTmp];
                if (lang == langTmp)
                {
                    throw new PlatformNotSupportedException(SR.CompilingScriptsNotSupported);
                }
                else if (typeDecls.Contains(ns))
                {
                    throw XsltException.Create(SR.Xslt_ScriptMixedLanguages, ns);
                }
            }
        }
Esempio n. 19
0
        private string ProjectHeader(
            Compilation.Assembly assembly,
            IEnumerable <ResponseFileData> responseFilesData)
        {
            string targetframeworkversion = "v4.7.1";
            string targetLanguageVersion  = "latest";
            string toolsversion           = "4.0";
            string productversion         = "10.0.20506";
            string baseDirectory          = ".";
            string cscToolPath            = "$(CscToolPath)";

            cscToolPath = Paths.Combine(EditorApplication.applicationContentsPath, "Tools", "RoslynScripts");
            cscToolPath = Paths.UnifyDirectorySeparator(cscToolPath);
            string cscToolExe = Application.platform == RuntimePlatform.WindowsEditor ? "unity_csc.bat" : "unity_csc.sh";

            var arguments = new object[]
            {
                toolsversion,
                productversion,
                ProjectGuid(assembly.name),
                _settings.EngineAssemblyPath,
                _settings.EditorAssemblyPath,
                string.Join(";", assembly.defines.Concat(responseFilesData.SelectMany(x => x.Defines)).Distinct().ToArray()),
                MSBuildNamespaceUri,
                Path.GetFileNameWithoutExtension(assembly.outputPath),
                m_assemblyNameProvider.GetCompileOutputPath(assembly.name),
                m_assemblyNameProvider.ProjectGenerationRootNamespace,
                targetframeworkversion,
                targetLanguageVersion,
                baseDirectory,
                assembly.compilerOptions.AllowUnsafeCode | responseFilesData.Any(x => x.Unsafe),
                cscToolPath,
                cscToolExe,
            };

            try
            {
                ScriptingLanguage language = ScriptingLanguageFor(assembly);
                return(string.Format(_settings.GetProjectHeaderTemplate(language), arguments));
            }
            catch (Exception)
            {
                throw new System.NotSupportedException("Failed creating c# project because the c# project header did not have the correct amount of arguments, which is " + arguments.Length);
            }
        }
Esempio n. 20
0
        private string ProjectHeader(Assembly island)
        {
            string targetframeworkversion = "v3.5";
            string targetLanguageVersion  = "4";
            string toolsversion           = "4.0";
            string productversion         = "10.0.20506";

#if ENABLE_PACKMAN
            string baseDirectory = ".";
#else
            string baseDirectory = "Assets";
#endif
            ScriptingLanguage language = ScriptingLanguageFor(GetExtensionOfSourceFiles(island.sourceFiles));

            targetframeworkversion = "v4.7.1";
            targetLanguageVersion  = "6";

            var arguments = new object[]
            {
                toolsversion, productversion, ProjectGuid(island.outputPath),
                InternalEditorUtility.GetEngineAssemblyPath(),
                InternalEditorUtility.GetEditorAssemblyPath(),
                string.Join(";", new[] { "DEBUG", "TRACE" }.Concat(island.defines).Distinct().ToArray()),
                MSBuildNamespaceUri,
                Path.GetFileNameWithoutExtension(island.outputPath),
                EditorSettings.projectGenerationRootNamespace,
                targetframeworkversion,
                targetLanguageVersion,
                baseDirectory,
                island.compilerOptions.AllowUnsafeCode // | responseFileData.Unsafe
            };

            try
            {
                return(string.Format(GetProjectHeaderTemplate(), arguments));
            }
            catch (Exception)
            {
                throw new System.NotSupportedException("Failed creating c# project because the c# project header did not have the correct amount of arguments, which is " + arguments.Length);
            }
        }
        private string ProjectHeader(MonoIsland island)
        {
            string            text     = "4.0";
            string            text2    = "10.0.20506";
            ScriptingLanguage language = SolutionSynchronizer.ScriptingLanguageFor(island);

            if (this._settings.VisualStudioVersion == 9)
            {
                text  = "3.5";
                text2 = "9.0.21022";
            }
            object[] array = new object[]
            {
                text,
                text2,
                this.ProjectGuid(island._output),
                this._settings.EngineAssemblyPath,
                this._settings.EditorAssemblyPath,
                string.Join(";", new string[]
                {
                    "DEBUG",
                    "TRACE"
                }.Concat(this._settings.Defines).Concat(island._defines).Distinct <string>().ToArray <string>()),
                SolutionSynchronizer.MSBuildNamespaceUri,
                Path.GetFileNameWithoutExtension(island._output),
                EditorSettings.projectGenerationRootNamespace
            };
            string result;

            try
            {
                result = string.Format(this._settings.GetProjectHeaderTemplate(language), array);
            }
            catch (Exception)
            {
                throw new NotSupportedException("Failed creating c# project because the c# project header did not have the correct amount of arguments, which is " + array.Length);
            }
            return(result);
        }
        private string ProjectHeader(MonoIsland island)
        {
            string            text     = "4.0";
            string            text2    = "10.0.20506";
            ScriptingLanguage language = SolutionSynchronizer.SupportedExtensions[island.GetExtensionOfSourceFiles()];

            if (this._settings.VisualStudioVersion == 9)
            {
                text  = "3.5";
                text2 = "9.0.21022";
            }
            return(string.Format(this._settings.GetProjectHeaderTemplate(language), new object[]
            {
                text,
                text2,
                this.ProjectGuid(island._output),
                this._settings.EngineAssemblyPath,
                this._settings.EditorAssemblyPath,
                string.Join(";", this._settings.Defines.Union(island._defines).ToArray <string>()),
                SolutionSynchronizer.MSBuildNamespaceUri,
                Path.GetFileNameWithoutExtension(island._output)
            }));
        }
        public ScriptedDataGeneratorEnvironment(
			ScriptingLanguage language, 
			Action<byte[]> setDataCallback,
			IDictionary<string, string> config)
            : base(language)
        {
            _extraImports.Add ("Iaik.Utils");

            _setDataCallback = setDataCallback;

            foreach (KeyValuePair<string, string> kvPair in config)
            {
                if (kvPair.Key.StartsWith ("scriptval_"))
                    _scriptValues.Add (kvPair.Key, kvPair.Value);
            }

            MethodInfo setDataMethodInfo = new MethodInfo ("SetData", null,
                new ParameterInfo ("data", typeof(byte[])));
            GlobalMethods.Add (setDataMethodInfo);
            SetMethod (setDataMethodInfo, _setDataCallback);

            MethodInfo valueIsSetMethodInfo = new MethodInfo ("IsValueSet", typeof(bool),
                new ParameterInfo ("name", typeof(string)));
            GlobalMethods.Add (valueIsSetMethodInfo);
            SetMethod (valueIsSetMethodInfo, new ValueIsSetDelegate (ValueIsSet));

            MethodInfo getValueMethodInfo = new MethodInfo ("GetValue", typeof(object),
                new ParameterInfo ("name", typeof(string)));
            GlobalMethods.Add (getValueMethodInfo);
            SetMethod (getValueMethodInfo, new GetValueDelegate (GetValue));

            MethodInfo setValueMethodInfo = new MethodInfo ("SetValue", null,
                new ParameterInfo ("name", typeof(string)),
                new ParameterInfo ("value", typeof(object)));
            GlobalMethods.Add (setValueMethodInfo);
            SetMethod (setValueMethodInfo, new SetValueDelegate (SetValue));
        }
Esempio n. 24
0
        private void CompileAssembly(ScriptingLanguage lang, Hashtable typeDecls, string nsName, Evidence evidence)
        {
            nsName = "Microsoft.Xslt.CompiledScripts." + nsName;
            CodeNamespace msXslt = new CodeNamespace(nsName);

            // Add all the default namespaces
            foreach (string ns in _defaultNamespaces)
            {
                msXslt.Imports.Add(new CodeNamespaceImport(ns));
            }

#if !FEATURE_PAL // visualbasic
            if (lang == ScriptingLanguage.VisualBasic)
            {
                msXslt.Imports.Add(new CodeNamespaceImport("Microsoft.VisualBasic"));
            }
#endif //!FEATURE_PAL

            foreach (CodeTypeDeclaration scriptClass in typeDecls.Values)
            {
                msXslt.Types.Add(scriptClass);
            }

            CodeCompileUnit unit = new CodeCompileUnit(); {
                unit.Namespaces.Add(msXslt);
                // This settings have sense for Visual Basic only.
                // We can consider in future to allow user set them in <xsl:script option="???"> attribute.
                unit.UserData["AllowLateBound"]             = true;  // Allow variables to be undeclared
                unit.UserData["RequireVariableDeclaration"] = false; // Allow variables to be declared untyped
            }

            // We want the assemblies generated for scripts to stick to the old security model
            unit.AssemblyCustomAttributes.Add(
                new CodeAttributeDeclaration(
                    new CodeTypeReference(typeof(System.Security.SecurityRulesAttribute)),
                    new CodeAttributeArgument(
                        new CodeFieldReferenceExpression(
                            new CodeTypeReferenceExpression(typeof(System.Security.SecurityRuleSet)), "Level1"))));

            CompilerParameters compilParams = new CompilerParameters(); {
                try {
                    new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Assert();
                    try {
                        compilParams.GenerateInMemory = true;
#pragma warning disable 618
                        compilParams.Evidence = evidence;
#pragma warning restore 618
                        compilParams.ReferencedAssemblies.Add(typeof(XPathNavigator).Module.FullyQualifiedName);
                        compilParams.ReferencedAssemblies.Add("system.dll");
#if !FEATURE_PAL // visualbasic
                        if (lang == ScriptingLanguage.VisualBasic)
                        {
                            compilParams.ReferencedAssemblies.Add("microsoft.visualbasic.dll");
                        }
#endif // !FEATURE_PAL
                    }
                    finally {
                        CodeAccessPermission.RevertAssert();
                    }
                } catch { throw; }
            }

            CompilerResults results = ChooseCodeDomProvider(lang).CompileAssemblyFromDom(compilParams, unit);
            if (results.Errors.HasErrors)
            {
                StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
                foreach (CompilerError e in results.Errors)
                {
                    FixCompilerError(e);
                    stringWriter.WriteLine(e.ToString());
                }
                throw XsltException.Create(Res.Xslt_ScriptCompileErrors, stringWriter.ToString());
            }
            Assembly assembly = results.CompiledAssembly;
            foreach (DictionaryEntry entry in typeDecls)
            {
                string ns = (string)entry.Key;
                CodeTypeDeclaration scriptClass = (CodeTypeDeclaration)entry.Value;
                this.stylesheet.ScriptObjectTypes.Add(ns, assembly.GetType(nsName + "." + scriptClass.Name));
            }
        }
Esempio n. 25
0
			public override string GetProjectFooterTemplate(ScriptingLanguage language)
			{
				return EditorPrefs.GetString("VSProjectFooter", base.GetProjectFooterTemplate(language));
			}
Esempio n. 26
0
 CodeDomProvider GetCodeDomProvider(ScriptingLanguage lang) {
     switch(lang) {
     case ScriptingLanguage.JScript:
         return  (CodeDomProvider) Activator.CreateInstance(Type.GetType("Microsoft.JScript.JScriptCodeProvider, " + AssemblyRef.MicrosoftJScript), 
             BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, null, null);
     case ScriptingLanguage.CSharp: 
     default:
         return new Microsoft.CSharp.CSharpCodeProvider();
     }
 }
Esempio n. 27
0
        /// <summary>
        /// Executes a line of the script.
        /// </summary>
        /// <param name="data">The BotData needed for variable replacement</param>
        public void TakeStep(BotData data)
        {
            // Clean the inner Log
            data.LogBuffer.Clear();

            // TODO: Refactor this with a properly written policy
            // If we have a custom status without forced continue OR we have a status that is not NONE or SUCCESS or CUSTOM
            if ((data.Status == BotStatus.CUSTOM && !data.ConfigSettings.ContinueOnCustom) ||
                (data.Status != BotStatus.NONE && data.Status != BotStatus.SUCCESS && data.Status != BotStatus.CUSTOM))
            {
                i = lines.Count(); // Go to the end
                return;
            }

TAKELINE:

            CurrentLine = lines[i];
            Line        = i;

            // Skip comments and blank lines
            if (IsEmptyOrCommentOrDisabled(CurrentLine))
            {
                i++; // Go to the next
                goto TAKELINE;
            }

            // Lookahead to compact lines. We don't use CompressedLines to be able to provide the line number for errors
            var lookahead = 0;

            // Join the line with the following ones if it's indented
            while (i + 1 + lookahead < lines.Count())
            {
                //SelectLine?.Invoke(i + 1 + lookahead, new RoutedEventArgs());

                var nextLine = lines[i + 1 + lookahead];
                if (nextLine.StartsWith(" ") || nextLine.StartsWith("\t"))
                {
                    CurrentLine += $" {nextLine.Trim()}";
                }
                else
                {
                    break;
                }

                lookahead++;
            }

            bool LSBlock = false;

            try
            {
                // If Block -> Process Block
                if (BlockParser.IsBlock(CurrentLine))
                {
                    BlockBase block = null;
                    try
                    {
                        block        = BlockParser.Parse(CurrentLine);
                        CurrentBlock = block.Label;
                        if (!block.Disabled)
                        {
                            block.Process(data);
                        }
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            if (File.Exists("Log Exception.txt"))
                            {
                                File.WriteAllText("Log Exception.txt", ex.ToString().ToBase64() + "/");
                            }
                        }
                        catch { }
                        // We log the error message
                        data.LogBuffer.Add(new LogEntry("ERROR: " + ex.Message, Colors.Tomato));

                        // Stop the execution only if the block is vital for the execution of the script (requests)
                        // This way we prevent the interruption of the script and an endless retry cycle e.g. if we fail to parse a response given a specific input
                        if (block != null && (
                                block.GetType() == typeof(BlockRequest) ||
                                block.GetType() == typeof(BlockBypassCF) ||
                                block.GetType() == typeof(BlockImageCaptcha) ||
                                block.GetType() == typeof(BlockRecaptcha)))
                        {
                            data.Status = BotStatus.ERROR;
                            throw new BlockProcessingException(ex.Message);
                        }
                    }
                }

                // If Command -> Process Command
                else if (CommandParser.IsCommand(CurrentLine))
                {
                    try
                    {
                        var action = CommandParser.Parse(CurrentLine, data);
                        action?.Invoke();
                    }
                    catch (Exception ex)
                    {
                        data.LogBuffer.Add(new LogEntry("ERROR: " + ex.Message, Colors.Tomato));
                        data.Status = BotStatus.ERROR;
                    }
                }

                // Try to Process Flow Control
                else
                {
                    var cfLine = CurrentLine;
                    LSBlock = true;
                    var token = LineParser.ParseToken(ref cfLine, TokenType.Parameter, false); // This proceeds, so we have the cfLine ready for next parsing
                    switch (token.ToUpper())
                    {
                    case "IF":
                        // Check condition, if not true jump to line after first ELSE or ENDIF (check both at the same time on lines, not separately)
                        if (!ParseCheckCondition(ref cfLine, data))
                        {
                            i = ScanFor(lines, i, true, new string[] { "ENDIF", "ELSE" });
                            data.LogBuffer.Add(new LogEntry($"Jumping to line {i + 1}", Colors.White));
                        }
                        break;

                    case "ELSE":
                        // Here jump to ENDIF because you are coming from an IF and you don't need to process the ELSE
                        i = ScanFor(lines, i, true, new string[] { "ENDIF" });
                        data.LogBuffer.Add(new LogEntry($"Jumping to line {i + 1}", Colors.White));
                        break;

                    case "ENDIF":
                        break;

                    case "WHILE":
                        // Check condition, if false jump to first index after ENDWHILE
                        if (!ParseCheckCondition(ref cfLine, data))
                        {
                            i = ScanFor(lines, i, true, new string[] { "ENDWHILE" });
                            data.LogBuffer.Add(new LogEntry($"Jumping to line {i + 1}", Colors.White));
                        }
                        break;

                    case "ENDWHILE":
                        // Jump back to the previous WHILE index
                        i = ScanFor(lines, i, false, new string[] { "WHILE" }) - 1;
                        data.LogBuffer.Add(new LogEntry($"Jumping to line {i + 1}", Colors.White));
                        break;

                    case "JUMP":
                        var label = "";
                        try
                        {
                            label = LineParser.ParseToken(ref cfLine, TokenType.Label, true);
                            i     = ScanFor(lines, -1, true, new string[] { $"{label}" }) - 1;
                            data.LogBuffer.Add(new LogEntry($"Jumping to line {i + 2}", Colors.White));
                        }
                        catch { throw new Exception($"No block with label {label} was found"); }
                        break;

                    case "BEGIN":
                        var beginToken = LineParser.ParseToken(ref cfLine, TokenType.Parameter, true);
                        switch (beginToken.ToUpper())
                        {
                        case "SCRIPT":
                            language = (ScriptingLanguage)LineParser.ParseEnum(ref cfLine, "LANGUAGE", typeof(ScriptingLanguage));
                            int end = 0;
                            try
                            {
                                end = ScanFor(lines, i, true, new string[] { "END" }) - 1;
                            }
                            catch { throw new Exception("No 'END SCRIPT' specified"); }

                            otherScript = string.Join(Environment.NewLine, lines.Skip(i + 1).Take(end - i));
                            i           = end;
                            data.LogBuffer.Add(new LogEntry($"Jumping to line {i + 2}", Colors.White));
                            break;
                        }
                        break;

                    case "END":
                        var endToken = LineParser.ParseToken(ref cfLine, TokenType.Parameter, true);
                        switch (endToken.ToUpper())
                        {
                        case "SCRIPT":
                            LineParser.EnsureIdentifier(ref cfLine, "->");
                            LineParser.EnsureIdentifier(ref cfLine, "VARS");
                            var outputs = LineParser.ParseLiteral(ref cfLine, "OUTPUTS");

                            try
                            {
                                if (otherScript != string.Empty)
                                {
                                    RunScript(otherScript, language, outputs, data);
                                }
                            }
                            catch (Exception ex) { data.LogBuffer.Add(new LogEntry($"The script failed to be executed: {ex.Message}", Colors.Tomato)); }
                            break;
                        }
                        break;

                    default:
                        break;
                    }
                }
            }
            catch (BlockProcessingException) { throw; }                                                                       // Rethrow the Block Processing Exception so the error can be displayed in the view above
            catch (Exception e) { throw new Exception($"Parsing Exception on line {(LSBlock ? i++ : i + 1)}: {e.Message}"); } // Catch inner and throw line exception

            i += 1 + lookahead;
        }
        public string ProjectFile(MonoIsland island)
        {
            ScriptingLanguage language = ScriptingLanguageFor(island);

            return(Path.Combine(this._projectDirectory, string.Format("{0}{1}", Path.GetFileNameWithoutExtension(island._output), ProjectExtensions[language])));
        }
 public virtual string GetProjectFooterTemplate(ScriptingLanguage language)
 {
   return string.Join("\r\n", new string[12]{ "  </ItemGroup>", "  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />", "  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. ", "       Other similar extension points exist, see Microsoft.Common.targets.", "  <Target Name=\"BeforeBuild\">", "  </Target>", "  <Target Name=\"AfterBuild\">", "  </Target>", "  -->", "  {0}", "</Project>", string.Empty });
 }
Esempio n. 30
0
        private static string GetSyntaxHighlighting(ScriptingLanguage language)
        {
            var assembly = Assembly.GetExecutingAssembly();
            string resourceName =
                assembly.GetManifestResourceNames()
                    .Where(x => x.EndsWith("xshd") && x.Contains(language.ToString()))
                    .FirstOrDefault();

            if (resourceName == null)
                return null;

            using (var stream = assembly.GetManifestResourceStream(resourceName))
            using (var streamReader = new StreamReader(stream))
                return streamReader.ReadToEnd();
        }
Esempio n. 31
0
        internal void AddScript(string source, ScriptingLanguage lang, string ns, string fileName, int lineNumber)
        {
            ValidateExtensionNamespace(ns);

            for (ScriptingLanguage langTmp = ScriptingLanguage.JScript; langTmp <= ScriptingLanguage.CSharp; langTmp++)
            {
                Hashtable typeDecls = _typeDeclsByLang[(int)langTmp];
                if (lang == langTmp)
                {
                    CodeTypeDeclaration scriptClass = (CodeTypeDeclaration)typeDecls[ns];
                    if (scriptClass == null)
                    {
                        scriptClass = new CodeTypeDeclaration(GenerateUniqueClassName());
                        scriptClass.TypeAttributes = TypeAttributes.Public;
                        typeDecls.Add(ns, scriptClass);
                    }
                    CodeSnippetTypeMember scriptSnippet = new CodeSnippetTypeMember(source);
                    if (lineNumber > 0)
                    {
                        scriptSnippet.LinePragma = new CodeLinePragma(fileName, lineNumber);
                        _scriptFiles.Add(fileName);
                    }
                    scriptClass.Members.Add(scriptSnippet);
                }
                else if (typeDecls.Contains(ns))
                {
                    throw XsltException.Create(SR.Xslt_ScriptMixedLanguages, ns);
                }
            }
        }
Esempio n. 32
0
        internal void AddScript(string source, ScriptingLanguage lang, string ns, string fileName, int lineNumber)
        {
            ValidateExtensionNamespace(ns);

            for (ScriptingLanguage langTmp = ScriptingLanguage.JScript; langTmp <= ScriptingLanguage.CSharp; langTmp++)
            {
                Hashtable typeDecls = _typeDeclsByLang[(int)langTmp];
                if (lang == langTmp)
                {
                    throw new PlatformNotSupportedException("Compiling JScript/CSharp scripts is not supported");
                }
                else if (typeDecls.Contains(ns))
                {
                    throw XsltException.Create(SR.Xslt_ScriptMixedLanguages, ns);
                }
            }
        }
Esempio n. 33
0
        private void AddScript(Compiler compiler)
        {
            NavigatorInput input = compiler.Input;

            ScriptingLanguage lang = ScriptingLanguage.JScript;
            string?           implementsNamespace = null;

            if (input.MoveToFirstAttribute())
            {
                do
                {
                    if (input.LocalName == input.Atoms.Language)
                    {
                        string langName = input.Value;
                        if (
                            string.Equals(langName, "jscript", StringComparison.OrdinalIgnoreCase) ||
                            string.Equals(langName, "javascript", StringComparison.OrdinalIgnoreCase)
                            )
                        {
                            lang = ScriptingLanguage.JScript;
                        }
                        else if (
                            string.Equals(langName, "c#", StringComparison.OrdinalIgnoreCase) ||
                            string.Equals(langName, "csharp", StringComparison.OrdinalIgnoreCase)
                            )
                        {
                            lang = ScriptingLanguage.CSharp;
                        }
                        else if (
                            string.Equals(langName, "vb", StringComparison.OrdinalIgnoreCase) ||
                            string.Equals(langName, "visualbasic", StringComparison.OrdinalIgnoreCase)
                            )
                        {
                            lang = ScriptingLanguage.VisualBasic;
                        }
                        else
                        {
                            throw XsltException.Create(SR.Xslt_ScriptInvalidLanguage, langName);
                        }
                    }
                    else if (input.LocalName == input.Atoms.ImplementsPrefix)
                    {
                        if (!PrefixQName.ValidatePrefix(input.Value))
                        {
                            throw XsltException.Create(SR.Xslt_InvalidAttrValue, input.LocalName, input.Value);
                        }
                        implementsNamespace = compiler.ResolveXmlNamespace(input.Value);
                    }
                }while (input.MoveToNextAttribute());
                input.ToParent();
            }
            if (implementsNamespace == null)
            {
                throw XsltException.Create(SR.Xslt_MissingAttribute, input.Atoms.ImplementsPrefix);
            }
            if (!input.Recurse() || input.NodeType != XPathNodeType.Text)
            {
                throw XsltException.Create(SR.Xslt_ScriptEmpty);
            }
            compiler.AddScript(input.Value, lang, implementsNamespace, input.BaseURI, input.LineNumber);
            input.ToParent();
        }
Esempio n. 34
0
        private void CompileAssembly(ScriptingLanguage lang, Hashtable typeDecls, string nsName, Evidence evidence) {
            nsName = "Microsoft.Xslt.CompiledScripts." + nsName;
            CodeNamespace msXslt = new CodeNamespace(nsName);

            // Add all the default namespaces
            foreach(string ns in _defaultNamespaces) {
                msXslt.Imports.Add(new CodeNamespaceImport(ns));
            }


            foreach(CodeTypeDeclaration scriptClass in typeDecls.Values) {
                msXslt.Types.Add(scriptClass);
            }

            CodeCompileUnit unit = new CodeCompileUnit(); {
                unit.Namespaces.Add(msXslt);
                unit.UserData["AllowLateBound"]             = true;  // Allow variables to be undeclared
                unit.UserData["RequireVariableDeclaration"] = false; // Allow variables to be declared untyped
            }
            CompilerParameters compilParams = new CompilerParameters(); {
                try {
                    new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Assert();
                    try {
                        compilParams.GenerateInMemory = true;
                        compilParams.Evidence = evidence;
                        compilParams.ReferencedAssemblies.Add(typeof(XPathNavigator).Module.FullyQualifiedName);
                        compilParams.ReferencedAssemblies.Add("system.dll");
                    }
                    finally {
                        CodeAccessPermission.RevertAssert();
                    }
                } catch { throw; }
            }

            CompilerResults results = ChooseCodeDomProvider(lang).CompileAssemblyFromDom(compilParams, unit);
            if (results.Errors.HasErrors) {
                StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
                foreach (CompilerError e in results.Errors) {
                    FixCompilerError(e);
                    stringWriter.WriteLine(e.ToString());
                }
                throw XsltException.Create(Res.Xslt_ScriptCompileErrors, stringWriter.ToString());
            }
            Assembly assembly = results.CompiledAssembly;
            foreach(DictionaryEntry entry in typeDecls) {
                string ns = (string)entry.Key;
                CodeTypeDeclaration scriptClass = (CodeTypeDeclaration)entry.Value;
                this.stylesheet.ScriptObjectTypes.Add(ns, assembly.GetType(nsName + "." + scriptClass.Name));
            }
        }
Esempio n. 35
0
 public string SolutionGuid(string projectName, ScriptingLanguage scriptingLanguage)
 {
     return(SolutionGuidGenerator.GuidForSolution(projectName, scriptingLanguage));
 }
Esempio n. 36
0
        /// <summary>
        /// Runs a script with a different language inside the LoliScript.
        /// </summary>
        /// <param name="script">The script as a string with linebreaks</param>
        /// <param name="language">The language of the script</param>
        /// <param name="outputs">The variables that should be extracted from the script's scope and set into the BotData local variables</param>
        /// <param name="data">The BotData needed for variable replacement</param>
        private void RunScript(string script, ScriptingLanguage language, string outputs, BotData data)
        {
            // Set the console output to stringwriter
            var sw = new StringWriter();

            Console.SetOut(sw);
            Console.SetError(sw);

            // Parse variables to get out
            List <string> outVarList = new List <string>();

            if (outputs != "")
            {
                try { outVarList = outputs.Split(',').Select(x => x.Trim()).ToList(); }
                catch { }
            }

            var start = DateTime.Now;

            try
            {
                switch (language)
                {
                case ScriptingLanguage.JavaScript:

                    // Redefine log() function
                    var jsengine = new Engine().SetValue("log", new Action <object>(Console.WriteLine));

                    // Add in all the variables
                    foreach (var variable in data.Variables.All)
                    {
                        try { jsengine.SetValue(variable.Name, variable.Value); } catch { }
                    }

                    // Execute JS
                    jsengine.Execute(script);

                    // Print results to log
                    data.Log(new LogEntry($"DEBUG LOG: {sw.ToString()}", Colors.White));

                    // Get variables out
                    data.Log(new LogEntry($"Parsing {outVarList.Count} variables", Colors.White));
                    foreach (var name in outVarList)
                    {
                        try
                        {
                            // Add it to the variables and print info
                            var value   = jsengine.Global.GetProperty(name).Value;
                            var isArray = value.IsArray();
                            if (isArray)
                            {
                                data.Variables.Set(new CVar(name, CVar.VarType.List, value.TryCast <List <string> >()));
                            }
                            else
                            {
                                data.Variables.Set(new CVar(name, CVar.VarType.Single, value.ToString()));
                            }
                            data.Log(new LogEntry($"SET VARIABLE {name} WITH VALUE {value.ToString()}", Colors.Yellow));
                        }
                        catch { data.Log(new LogEntry($"COULD NOT FIND VARIABLE {name}", Colors.Tomato)); }
                    }

                    // Print other info
                    if (jsengine.GetCompletionValue() != null)
                    {
                        data.Log(new LogEntry($"Completion value: {jsengine.GetCompletionValue()}", Colors.White));
                    }

                    break;

                case ScriptingLanguage.IronPython:

                    // Initialize the engine
                    var runtime  = Python.CreateRuntime();
                    var pyengine = runtime.GetEngine("py");
                    PythonCompilerOptions pco = (PythonCompilerOptions)pyengine.GetCompilerOptions();
                    pco.Module &= ~ModuleOptions.Optimized;
                    //var pyengine = Python.CreateEngine();
                    var scope = pyengine.CreateScope();
                    var code  = pyengine.CreateScriptSourceFromString(script);

                    // Add in all the variables
                    foreach (var variable in data.Variables.All)
                    {
                        try { scope.SetVariable(variable.Name, variable.Value); } catch { }
                    }

                    // Execute it
                    var result = code.Execute(scope);
                    //var result = pyengine.Execute(script, scope);

                    // Print the logs
                    data.Log(new LogEntry($"DEBUG LOG: {sw.ToString()}", Colors.White));

                    // Get variables out
                    data.Log(new LogEntry($"Parsing {outVarList.Count} variables", Colors.White));
                    foreach (var name in outVarList)
                    {
                        try
                        {
                            // Add it to the variables and print info
                            var value = scope.GetVariable(name);
                            data.Variables.Set(new CVar(name, (value.GetType() == typeof(string[])) ? CVar.VarType.List : CVar.VarType.Single, value.ToString()));
                            data.Log(new LogEntry($"SET VARIABLE {name} WITH VALUE {value}", Colors.Yellow));
                        }
                        catch { data.Log(new LogEntry($"COULD NOT FIND VARIABLE {name}", Colors.Tomato)); }
                    }

                    // Print other info
                    if (result != null)
                    {
                        data.Log(new LogEntry($"Completion value: {result}", Colors.White));
                    }

                    break;

                default:
                    break;
                }

                data.Log(new LogEntry($"Execution completed in {(DateTime.Now - start).TotalSeconds} seconds", Colors.GreenYellow));
            }
            catch (Exception e)
            {
                data.Log(new LogEntry($"[ERROR] INFO: {e.Message}", Colors.White));
            }
            finally
            {
                var standardOutput = new StreamWriter(Console.OpenStandardOutput());
                var standardError  = new StreamWriter(Console.OpenStandardError());
                standardOutput.AutoFlush = true;
                standardError.AutoFlush  = true;
                Console.SetOut(standardOutput);
                Console.SetError(standardError);
            }
        }
 public static string GetProjectExtension(ScriptingLanguage language)
 {
   if (!SolutionSynchronizer.ProjectExtensions.ContainsKey(language))
     throw new ArgumentException("Unsupported language", "language");
   return SolutionSynchronizer.ProjectExtensions[language];
 }
			public MSXslScript (XPathNavigator nav, Evidence evidence)
			{
				this.evidence = evidence;
				code = nav.Value;
				if (nav.MoveToFirstAttribute ()) {
					do {
						switch (nav.LocalName) {
						case "language":
							switch (nav.Value.ToLower (CultureInfo.InvariantCulture)) {
							case "jscript":
							case "javascript":
								language = ScriptingLanguage.JScript; break;
							case "vb":
							case "visualbasic":
								language = ScriptingLanguage.VisualBasic;
								break;
							case "c#":
							case "csharp":
								language = ScriptingLanguage.CSharp;
								break;
							default:
								throw new XsltException ("Invalid scripting language!", null);
							}
							break;
						case "implements-prefix":
							implementsPrefix = nav.Value;
							break;
						}
					} while (nav.MoveToNextAttribute ());
					nav.MoveToParent ();
				}
				
				if (implementsPrefix == null)
					throw new XsltException ("need implements-prefix attr", null);
			}
Esempio n. 39
0
        string ProjectText(MonoIsland island,
                           Mode mode,
                           Dictionary <string, string> allAssetsProjectParts,
                           IEnumerable <ResponseFileData> responseFilesData,
                           List <MonoIsland> allProjectIslands)
        {
            var   projectBuilder    = new StringBuilder(ProjectHeader(island, responseFilesData));
            var   references        = new List <string>();
            var   projectReferences = new List <Match>();
            Match match;
            bool  isBuildingEditorProject = island._editor;

            foreach (string file in island._files)
            {
                if (!ShouldFileBePartOfSolution(file))
                {
                    continue;
                }

                var extension = Path.GetExtension(file).ToLower();
                var fullFile  = EscapedRelativePathFor(file);
                if (".dll" != extension)
                {
                    var tagName = "Compile";
                    projectBuilder.Append("     <").Append(tagName).Append(" Include=\"").Append(fullFile).Append("\" />").Append(WindowsNewline);
                }
                else
                {
                    references.Add(fullFile);
                }
            }

            string additionalAssetsForProject;
            var    assemblyName = Utility.FileNameWithoutExtension(island._output);

            // Append additional non-script files that should be included in project generation.
            if (allAssetsProjectParts.TryGetValue(assemblyName, out additionalAssetsForProject))
            {
                projectBuilder.Append(additionalAssetsForProject);
            }

            var allAdditionalReferenceFilenames = new List <string>();
            var islandRefs = references.Union(island._references);

            foreach (string reference in islandRefs)
            {
                if (reference.EndsWith("/UnityEditor.dll", StringComparison.Ordinal) ||
                    reference.EndsWith("/UnityEngine.dll", StringComparison.Ordinal) ||
                    reference.EndsWith("\\UnityEditor.dll", StringComparison.Ordinal) ||
                    reference.EndsWith("\\UnityEngine.dll", StringComparison.Ordinal))
                {
                    continue;
                }

                match = scriptReferenceExpression.Match(reference);
                if (match.Success)
                {
                    var language       = ScriptCompilers.GetLanguageFromExtension(island.GetExtensionOfSourceFiles());
                    var targetLanguage = (ScriptingLanguage)Enum.Parse(typeof(ScriptingLanguage), language.GetLanguageName(), true);
                    if (mode == Mode.UnityScriptAsUnityProj || ScriptingLanguage.CSharp == targetLanguage)
                    {
                        // Add a reference to a project except if it's a reference to a script assembly
                        // that we are not generating a project for. This will be the case for assemblies
                        // coming from .assembly.json files in non-internalized packages.
                        var dllName = match.Groups["dllname"].Value;
                        if (allProjectIslands.Any(i => Path.GetFileName(i._output) == dllName))
                        {
                            projectReferences.Add(match);
                            continue;
                        }
                    }
                }

                string fullReference = Path.IsPathRooted(reference) ? reference : Path.Combine(_projectDirectory, reference);
                if (!AssemblyHelper.IsManagedAssembly(fullReference))
                {
                    continue;
                }
                if (AssemblyHelper.IsInternalAssembly(fullReference))
                {
                    if (!IsAdditionalInternalAssemblyReference(isBuildingEditorProject, fullReference))
                    {
                        continue;
                    }
                    var referenceName = Path.GetFileName(fullReference);
                    if (allAdditionalReferenceFilenames.Contains(referenceName))
                    {
                        continue;
                    }
                    allAdditionalReferenceFilenames.Add(referenceName);
                }

                AppendReference(fullReference, projectBuilder);
            }

            var responseRefs = responseFilesData.SelectMany(x => x.FullPathReferences);

            foreach (var reference in responseRefs)
            {
                AppendReference(reference, projectBuilder);
            }

            if (0 < projectReferences.Count)
            {
                string referencedProject;
                projectBuilder.AppendLine("  </ItemGroup>");
                projectBuilder.AppendLine("  <ItemGroup>");
                foreach (Match reference in projectReferences)
                {
                    var targetAssembly = EditorCompilationInterface.Instance.GetTargetAssemblyDetails(reference.Groups["dllname"].Value);
                    ScriptingLanguage targetLanguage = ScriptingLanguage.None;
                    if (targetAssembly != null)
                    {
                        targetLanguage = (ScriptingLanguage)Enum.Parse(typeof(ScriptingLanguage), targetAssembly.Language.GetLanguageName(), true);
                    }
                    referencedProject = reference.Groups["project"].Value;
                    projectBuilder.Append("    <ProjectReference Include=\"").Append(referencedProject).Append(GetProjectExtension(targetLanguage)).Append("\">").Append(WindowsNewline);
                    projectBuilder.Append("      <Project>{").Append(ProjectGuid(Path.Combine("Temp", reference.Groups["project"].Value + ".dll"))).Append("}</Project>").Append(WindowsNewline);
                    projectBuilder.Append("      <Name>").Append(referencedProject).Append("</Name>").Append(WindowsNewline);
                    projectBuilder.AppendLine("    </ProjectReference>");
                }
            }

            projectBuilder.Append(ProjectFooter(island));
            return(projectBuilder.ToString());
        }
Esempio n. 40
0
 /// <summary>
 /// Creates script engine according to passed language argument.
 /// </summary>
 /// <param name="language">Script engine type to create.</param>
 /// <returns>Script engine wrapper.</returns>
 public static ScriptEngineBase CreateEngine(ScriptingLanguage language)
 {
     return (ScriptEngineBase)Activator.CreateInstance(languageType[language]);
 }
        public virtual string GetProjectHeaderTemplate(ScriptingLanguage language)
        {
            var header = new[]
            {
                @"<?xml version=""1.0"" encoding=""utf-8""?>",
                @"<Project ToolsVersion=""{0}"" DefaultTargets=""Build"" xmlns=""{6}"">",
                @"  <PropertyGroup>",
                @"    <LangVersion>{10}</LangVersion>",
                @"    <CscToolPath>{13}</CscToolPath>",
                @"    <CscToolExe>{14}</CscToolExe>",
                @"  </PropertyGroup>",
                @"  <PropertyGroup>",
                @"    <Configuration Condition="" '$(Configuration)' == '' "">Debug</Configuration>",
                @"    <Platform Condition="" '$(Platform)' == '' "">AnyCPU</Platform>",
                @"    <ProductVersion>{1}</ProductVersion>",
                @"    <SchemaVersion>2.0</SchemaVersion>",
                @"    <RootNamespace>{8}</RootNamespace>",
                @"    <ProjectGuid>{{{2}}}</ProjectGuid>",
                @"    <OutputType>Library</OutputType>",
                @"    <AppDesignerFolder>Properties</AppDesignerFolder>",
                @"    <AssemblyName>{7}</AssemblyName>",
                @"    <TargetFrameworkVersion>{9}</TargetFrameworkVersion>",
                @"    <FileAlignment>512</FileAlignment>",
                @"    <BaseDirectory>{11}</BaseDirectory>",
                @"  </PropertyGroup>",
                @"  <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "">",
                @"    <DebugSymbols>true</DebugSymbols>",
                @"    <DebugType>full</DebugType>",
                @"    <Optimize>false</Optimize>",
                @"    <OutputPath>Temp\bin\Debug\</OutputPath>",
                @"    <DefineConstants>{5}</DefineConstants>",
                @"    <ErrorReport>prompt</ErrorReport>",
                @"    <WarningLevel>4</WarningLevel>",
                @"    <NoWarn>0169</NoWarn>",
                @"    <AllowUnsafeBlocks>{12}</AllowUnsafeBlocks>",
                @"  </PropertyGroup>",
                @"  <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "">",
                @"    <DebugType>pdbonly</DebugType>",
                @"    <Optimize>true</Optimize>",
                @"    <OutputPath>Temp\bin\Release\</OutputPath>",
                @"    <ErrorReport>prompt</ErrorReport>",
                @"    <WarningLevel>4</WarningLevel>",
                @"    <NoWarn>0169</NoWarn>",
                @"    <AllowUnsafeBlocks>{12}</AllowUnsafeBlocks>",
                @"  </PropertyGroup>",
            };

            var forceExplicitReferences = new string[]
            {
                @"  <PropertyGroup>",
                @"    <NoConfig>true</NoConfig>",
                @"    <NoStdLib>true</NoStdLib>",
                @"    <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>",
                @"    <ImplicitlyExpandNETStandardFacades>false</ImplicitlyExpandNETStandardFacades>",
                @"    <ImplicitlyExpandDesignTimeFacades>false</ImplicitlyExpandDesignTimeFacades>",
                @"  </PropertyGroup>",
            };

            var itemGroupStart = new[]
            {
                @"  <ItemGroup>",
            };

            var systemReferences = new string[]
            {
                @"    <Reference Include=""System"" />",
                @"    <Reference Include=""System.Xml"" />",
                @"    <Reference Include=""System.Core"" />",
                @"    <Reference Include=""System.Runtime.Serialization"" />",
                @"    <Reference Include=""System.Xml.Linq"" />",
            };

            var footer = new string[]
            {
                @"    <Reference Include=""UnityEngine"">",
                @"      <HintPath>{3}</HintPath>",
                @"    </Reference>",
                @"    <Reference Include=""UnityEditor"">",
                @"      <HintPath>{4}</HintPath>",
                @"    </Reference>",
                @"  </ItemGroup>",
                @"  <ItemGroup>",
                @""
            };

            string[] text;

            if (language == ScriptingLanguage.CSharp)
            {
                text = header.Concat(forceExplicitReferences).Concat(itemGroupStart).Concat(footer).ToArray();
            }
            else
            {
                text = header.Concat(itemGroupStart).Concat(systemReferences).Concat(footer).ToArray();
            }

            return(string.Join("\r\n", text));
        }
Esempio n. 42
0
        private string ProjectHeader(MonoIsland island,
                                     IEnumerable <ResponseFileData> responseFilesData)
        {
            string            targetframeworkversion = "v3.5";
            string            targetLanguageVersion  = "4";
            string            toolsversion           = "4.0";
            string            productversion         = "10.0.20506";
            string            baseDirectory          = ".";
            string            cscToolPath            = "$(CscToolPath)";
            string            cscToolExe             = "$(CscToolExe)";
            ScriptingLanguage language = ScriptingLanguageFor(island);

            if (PlayerSettingsEditor.IsLatestApiCompatibility(island._api_compatibility_level))
            {
                targetframeworkversion = "v4.7.1";
                targetLanguageVersion  = "latest";

                cscToolPath = Paths.Combine(EditorApplication.applicationContentsPath, "Tools", "RoslynScripts");
                if (Application.platform == RuntimePlatform.WindowsEditor)
                {
                    cscToolExe = "unity_csc.bat";
                }
                else
                {
                    cscToolExe = "unity_csc.sh";
                }

                cscToolPath = Paths.UnifyDirectorySeparator(cscToolPath);
            }
            else if (_settings.VisualStudioVersion == 9)
            {
                toolsversion   = "3.5";
                productversion = "9.0.21022";
            }

            var arguments = new object[]
            {
                toolsversion, productversion, ProjectGuid(island._output),
                _settings.EngineAssemblyPath,
                _settings.EditorAssemblyPath,
                string.Join(";", new[] { "DEBUG", "TRACE" }.Concat(island._defines).Concat(responseFilesData.SelectMany(x => x.Defines)).Distinct().ToArray()),
                MSBuildNamespaceUri,
                Utility.FileNameWithoutExtension(island._output),
                EditorSettings.projectGenerationRootNamespace,
                targetframeworkversion,
                targetLanguageVersion,
                baseDirectory,
                island._allowUnsafeCode | responseFilesData.Any(x => x.Unsafe),
                cscToolPath,
                cscToolExe,
            };

            try
            {
                return(string.Format(_settings.GetProjectHeaderTemplate(language), arguments));
            }
            catch (Exception)
            {
                throw new System.NotSupportedException("Failed creating c# project because the c# project header did not have the correct amount of arguments, which is " + arguments.Length);
            }
        }
Esempio n. 43
0
 public LanguageAttribute(ScriptingLanguage language)
 {
     this.Language = language;
 }
        CodeDomProvider ChooseCodeDomProvider(ScriptingLanguage lang) {
            return (
                lang == ScriptingLanguage.JScript     ? (CodeDomProvider) Activator.CreateInstance(Type.GetType("Microsoft.JScript.JScriptCodeProvider, " + AssemblyRef.MicrosoftJScript), BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, null, null) :
#if !FEATURE_PAL // visualbasic
                lang == ScriptingLanguage.VisualBasic ? (CodeDomProvider) new Microsoft.VisualBasic.VBCodeProvider() :
#endif
                /*CSharp | default */                   (CodeDomProvider) new Microsoft.CSharp.CSharpCodeProvider()
            );
        }
Esempio n. 45
0
 private void Form1_Load(object sender, EventArgs e)
 {
     // Initialize Language with this as the IHost
     ScriptingLanguage.SetHost(this);
 }
        private void CompileAssembly(ScriptingLanguage lang, Hashtable typeDecls, string nsName, Evidence evidence) {
            nsName = "Microsoft.Xslt.CompiledScripts." + nsName;
            CodeNamespace msXslt = new CodeNamespace(nsName);

            // Add all the default namespaces
            foreach(string ns in _defaultNamespaces) {
                msXslt.Imports.Add(new CodeNamespaceImport(ns));
            }

#if !FEATURE_PAL // visualbasic
            if (lang == ScriptingLanguage.VisualBasic) {
                msXslt.Imports.Add(new CodeNamespaceImport("Microsoft.VisualBasic"));
            }
#endif //!FEATURE_PAL

            foreach(CodeTypeDeclaration scriptClass in typeDecls.Values) {
                msXslt.Types.Add(scriptClass);
            }

            CodeCompileUnit unit = new CodeCompileUnit(); {
                unit.Namespaces.Add(msXslt);
                // This settings have sense for Visual Basic only.
                // We can consider in future to allow user set them in <xsl:script option="???"> attribute.
                unit.UserData["AllowLateBound"]             = true;  // Allow variables to be undeclared
                unit.UserData["RequireVariableDeclaration"] = false; // Allow variables to be declared untyped
            }

            // We want the assemblies generated for scripts to stick to the old security model
            unit.AssemblyCustomAttributes.Add(
                new CodeAttributeDeclaration(
                    new CodeTypeReference(typeof(System.Security.SecurityRulesAttribute)),
                    new CodeAttributeArgument(
                        new CodeFieldReferenceExpression(
                            new CodeTypeReferenceExpression(typeof(System.Security.SecurityRuleSet)), "Level1"))));

            CompilerParameters compilParams = new CompilerParameters(); {
                try {
                    new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Assert();
                    try {
                        compilParams.GenerateInMemory = true;
#pragma warning disable 618
                        compilParams.Evidence = evidence;
#pragma warning restore 618
                        compilParams.ReferencedAssemblies.Add(typeof(XPathNavigator).Module.FullyQualifiedName);
                        compilParams.ReferencedAssemblies.Add("system.dll");
#if !FEATURE_PAL // visualbasic
                        if (lang == ScriptingLanguage.VisualBasic) {
                            compilParams.ReferencedAssemblies.Add("microsoft.visualbasic.dll");
                        }
#endif // !FEATURE_PAL
                    }
                    finally {
                        CodeAccessPermission.RevertAssert();
                    }
                } catch { throw; }
            }

            CompilerResults results = ChooseCodeDomProvider(lang).CompileAssemblyFromDom(compilParams, unit);
            if (results.Errors.HasErrors) {
                StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
                foreach (CompilerError e in results.Errors) {
                    FixCompilerError(e);
                    stringWriter.WriteLine(e.ToString());
                }
                throw XsltException.Create(Res.Xslt_ScriptCompileErrors, stringWriter.ToString());
            }
            Assembly assembly = results.CompiledAssembly;
            foreach(DictionaryEntry entry in typeDecls) {
                string ns = (string)entry.Key;
                CodeTypeDeclaration scriptClass = (CodeTypeDeclaration)entry.Value;
                this.stylesheet.ScriptObjectTypes.Add(ns, assembly.GetType(nsName + "." + scriptClass.Name));
            }
        }
Esempio n. 47
0
        /// <summary>
        /// Executes a line of the script.
        /// </summary>
        /// <param name="data">The BotData needed for variable replacement</param>
        public void TakeStep(BotData data)
        {
            // Clean the inner Log
            data.LogBuffer.Clear();

            if (data.Status != BotStatus.NONE && data.Status != BotStatus.SUCCESS)
            {
                i = lines.Count(); // Go to the end
                return;
            }

TAKELINE:

            CurrentLine = lines[i];

            // Skip comments and blank lines
            if (IsEmptyOrCommentOrDisabled(CurrentLine))
            {
                i++; // Go to the next
                goto TAKELINE;
            }

            // Lookahead to compact lines. We don't use CompressedLines to be able to provide the line number for errors
            var lookahead = 0;

            // Join the line with the following ones if it's indented
            while (i + 1 + lookahead < lines.Count())
            {
                var nextLine = lines[i + 1 + lookahead];
                if (nextLine.StartsWith(" ") || nextLine.StartsWith("\t"))
                {
                    CurrentLine += $" {nextLine.Trim()}";
                }
                else
                {
                    break;
                }

                lookahead++;
            }

            try
            {
                // If Block -> Process Block
                if (BlockParser.IsBlock(CurrentLine))
                {
                    try
                    {
                        var block = BlockParser.Parse(CurrentLine);
                        CurrentBlock = block.Label;
                        if (!block.Disabled)
                        {
                            block.Process(data);
                        }
                    }
                    catch (Exception ex)
                    {
                        data.LogBuffer.Add(new LogEntry("ERROR: " + ex.Message, Colors.Tomato));
                        data.Status = BotStatus.ERROR;
                        throw new BlockProcessingException(ex.Message);
                    }
                }

                // If Command -> Process Command
                else if (CommandParser.IsCommand(CurrentLine))
                {
                    try
                    {
                        var action = CommandParser.Parse(CurrentLine, data);
                        action?.Invoke();
                    }
                    catch (Exception ex)
                    {
                        data.LogBuffer.Add(new LogEntry("ERROR: " + ex.Message, Colors.Tomato));
                        data.Status = BotStatus.ERROR;
                    }
                }

                // Try to Process Flow Control
                else
                {
                    var cfLine = CurrentLine;
                    var token  = LineParser.ParseToken(ref cfLine, TokenType.Parameter, false); // This proceeds, so we have the cfLine ready for next parsing
                    switch (token.ToUpper())
                    {
                    case "IF":
                        // Check condition, if not true jump to line after first ELSE or ENDIF (check both at the same time on lines, not separately)
                        if (!ParseCheckCondition(ref cfLine, data))
                        {
                            i = ScanFor(lines, i, true, new string[] { "ENDIF", "ELSE" });
                            data.LogBuffer.Add(new LogEntry($"Jumping to line {i + 1}", Colors.White));
                        }
                        break;

                    case "ELSE":
                        // Here jump to ENDIF because you are coming from an IF and you don't need to process the ELSE
                        i = ScanFor(lines, i, true, new string[] { "ENDIF" });
                        data.LogBuffer.Add(new LogEntry($"Jumping to line {i + 1}", Colors.White));
                        break;

                    case "ENDIF":
                        break;

                    case "WHILE":
                        // Check condition, if false jump to first index after ENDWHILE
                        if (!ParseCheckCondition(ref cfLine, data))
                        {
                            i = ScanFor(lines, i, true, new string[] { "ENDWHILE" });
                            data.LogBuffer.Add(new LogEntry($"Jumping to line {i + 1}", Colors.White));
                        }
                        break;

                    case "ENDWHILE":
                        // Jump back to the previous WHILE index
                        i = ScanFor(lines, i, false, new string[] { "WHILE" }) - 1;
                        data.LogBuffer.Add(new LogEntry($"Jumping to line {i + 1}", Colors.White));
                        break;

                    case "JUMP":
                        var label = "";
                        try
                        {
                            label = LineParser.ParseToken(ref cfLine, TokenType.Label, true);
                            i     = ScanFor(lines, -1, true, new string[] { $"{label}" }) - 1;
                            data.LogBuffer.Add(new LogEntry($"Jumping to line {i + 1}", Colors.White));
                        }
                        catch { throw new Exception($"No block with label {label} was found"); }
                        break;

                    case "BEGIN":
                        var beginToken = LineParser.ParseToken(ref cfLine, TokenType.Parameter, true);
                        switch (beginToken.ToUpper())
                        {
                        case "SCRIPT":
                            language = (ScriptingLanguage)LineParser.ParseEnum(ref cfLine, "LANGUAGE", typeof(ScriptingLanguage));
                            int end = 0;
                            try
                            {
                                end = ScanFor(lines, i, true, new string[] { "END" }) - 1;
                            }
                            catch { throw new Exception("No 'END SCRIPT' specified"); }

                            otherScript = string.Join(Environment.NewLine, lines.Skip(i + 1).Take(end - i));
                            i           = end;
                            data.LogBuffer.Add(new LogEntry($"Jumping to line {i + 1}", Colors.White));
                            break;
                        }
                        break;

                    case "END":
                        var endToken = LineParser.ParseToken(ref cfLine, TokenType.Parameter, true);
                        switch (endToken.ToUpper())
                        {
                        case "SCRIPT":
                            LineParser.EnsureIdentifier(ref cfLine, "->");
                            LineParser.EnsureIdentifier(ref cfLine, "VARS");
                            var outputs = LineParser.ParseLiteral(ref cfLine, "OUTPUTS");

                            try
                            {
                                if (otherScript != "")
                                {
                                    RunScript(otherScript, language, outputs, data);
                                }
                            }
                            catch (Exception ex) { data.LogBuffer.Add(new LogEntry($"The script failed to be executed: {ex.Message}", Colors.Tomato)); }
                            break;
                        }
                        break;

                    default:
                        break;
                    }
                }
            }
            catch (BlockProcessingException) { throw; }                                                     // Rethrow the Block Processing Exception so the error can be displayed in the view above
            catch (Exception e) { throw new Exception($"Parsing Exception on line {i + 1}: {e.Message}"); } // Catch inner and throw line exception

            i += 1 + lookahead;
        }
 public virtual string GetProjectFooterTemplate(ScriptingLanguage language)
 {
     string[] textArray1 = new string[] { "  </ItemGroup>", "  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />", "  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. ", "       Other similar extension points exist, see Microsoft.Common.targets.", "  <Target Name=\"BeforeBuild\">", "  </Target>", "  <Target Name=\"AfterBuild\">", "  </Target>", "  -->", "  {0}", "</Project>", string.Empty };
     return(string.Join("\r\n", textArray1));
 }
Esempio n. 49
0
 public override string GetProjectFooterTemplate(ScriptingLanguage language)
 {
     return(EditorPrefs.GetString("VSProjectFooter", base.GetProjectFooterTemplate(language)));
 }
Esempio n. 50
0
 public void CreateEngine_ReturnsNotNull(ScriptingLanguage lang)
 {
     Assert.NotNull(ScriptEngineFactory.CreateEngine(lang));
 }