Beispiel #1
0
    static public void Main(string[] args)
    {
        if (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help"))
        {
            Console.WriteLine(usage);
        }
        else
        {
            string dir = Path.Combine(Environment.GetEnvironmentVariable("CSSCRIPT_DIR"), "Lib");

            if (args.Length != 0)
            {
                dir = Path.GetFullPath(CSSEnvironment.GetCacheDirectory(Path.GetFullPath(args[0])));
            }

            foreach (string file in Directory.GetFiles(dir, "*.csc"))
            {
                try
                {
                    File.Delete(file);
                    Console.WriteLine("Cleared: " + file);
                }
                catch
                {
                }
            }
        }
    }
Beispiel #2
0
    static public int Main(string[] args)
    {
        try
        {
            if (args.Length == 0)
            {
                throw new Exception("No script were passed for execution.");
            }

            if (!File.Exists(args[0]))
            {
                throw new Exception("The command line first argument is not a valid file location.");
            }

            string rawScript           = args[0];
            string scriptExtension     = Path.GetExtension(rawScript).ToLower();
            string reconstructedScript = Path.Combine(CSSEnvironment.GetCacheDirectory(rawScript),
                                                      Path.GetFileName(rawScript) + ".reconstructed" + scriptExtension);

            using (StreamReader sr = new StreamReader(rawScript))
            {
                string firstLine = sr.ReadLine();
                if (firstLine.StartsWith("#!"))
                {
                    if (File.GetLastWriteTimeUtc(rawScript) != File.GetLastWriteTimeUtc(reconstructedScript))
                    {
                        using (StreamWriter sw = new StreamWriter(reconstructedScript, false, Encoding.Unicode))
                        {
                            if (scriptExtension == ".vb")
                            {
                                sw.Write("'");
                            }

                            sw.WriteLine("//css_searchdir " + Path.GetDirectoryName(rawScript) + ";");

                            string line;
                            while (null != (line = sr.ReadLine()))
                            {
                                sw.WriteLine(line);
                            }
                        }
                    }

                    File.SetLastWriteTimeUtc(reconstructedScript, File.GetLastWriteTimeUtc(rawScript));

                    args[0] = ToRelativePath(reconstructedScript, Environment.CurrentDirectory);
                }
            }

            AppDomain.CurrentDomain.ExecuteAssembly(scriptEngineFile, null, args);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            return(1);
        }
        return(0);
    }
Beispiel #3
0
 static string ResolveAsmLocation(string file)
 {
     if (CSScript.GlobalSettings.HideAutoGeneratedFiles == Settings.HideOptions.HideAll)
     {
         return(Path.Combine(CSSEnvironment.GetCacheDirectory(CSSEnvironment.PrimaryScriptFile), Path.GetFileName(file)));
     }
     else
     {
         return(Path.Combine(Path.GetDirectoryName(CSSEnvironment.PrimaryScriptFile), file));
     }
 }
Beispiel #4
0
 static string ResolveAsmLocation(string file)
 {
     //System.Diagnostics.Debug.Assert(false);
     if (CSScript.GlobalSettings.HideAutoGeneratedFiles == Settings.HideOptions.HideAll)
     {
         return(Path.Combine(CSSEnvironment.GetCacheDirectory(EntryScript), Path.GetFileName(file)));
     }
     else
     {
         return(Path.Combine(Path.GetDirectoryName(EntryScript), file));
     }
 }
Beispiel #5
0
        static string ResolveOutputLocation(string file)
        {
            string primaryScriptFile = Environment.GetEnvironmentVariable("EntryScript");

            if (primaryScriptFile != null && CSScript.GlobalSettings.HideAutoGeneratedFiles == Settings.HideOptions.HideAll)
            {
                return(Path.Combine(CSSEnvironment.GetCacheDirectory(primaryScriptFile), Path.GetFileName(file)));
            }
            else if (primaryScriptFile != null)
            {
                return(Path.Combine(Path.GetDirectoryName(primaryScriptFile), file));
            }
            else
            {
                return(Path.GetFullPath(file));
            }
        }
Beispiel #6
0
        protected override void Load(ContainerBuilder builder)
        {
            var signatures = new CodeLocal().GetSignatures().ToArray();

            // get methods and shorthand from builder
            _methods   = builder.Properties.ContainsKey("Methods") ? (HashSet <string>)builder.Properties["Methods"] : new HashSet <string>();
            _shortHand = builder.Properties.ContainsKey("ShortHand") ? (ShorthandRoot)builder.Properties["ShortHand"] : new ShorthandRoot();

            RegisterShortHand(signatures);
            RegisterTransform(builder, c => c.Field.Remote ? (ITransform) new CodeRemote(c) : new CodeLocal(c), signatures);

            if (!builder.Properties.ContainsKey("Process"))
            {
                return;
            }

            var process = (Process)builder.Properties["Process"];

            if (process == null)
            {
                return;
            }

            if (process.Entities.Any() && process.GetAllTransforms().Any(t => t.Method == "csscript"))
            {
                if (!_setup)
                {
                    AppDomain.MonitoringIsEnabled      = true;
                    CSScript.EvaluatorConfig.Access    = EvaluatorAccess.Singleton;
                    CSScript.EvaluatorConfig.Engine    = EvaluatorEngine.CodeDom;
                    CSScript.GlobalSettings.SearchDirs = AssemblyDirectory + ";" + Path.Combine(AssemblyDirectory, "plugins");
                    CSScript.CacheEnabled = true;
                    CSSEnvironment.SetScriptTempDir(Path.Combine(AssemblyDirectory, "plugins", "cs-script"));
                    _setup = true;
                }

                var action = new Configuration.Action {
                    Type = "cs-script", Before = false, After = true, Key = "cs-script"
                };
                builder.Register <IAction>((c) => new RemoteUnload(c.Resolve <IContext>(), action)).Named <IAction>("cs-script");
                process.Actions.Add(action);
            }
        }
Beispiel #7
0
    static void TreatWarningAsError2()
    {
        string code = @"using System;
                        public class Calc
                        {
                            static public int Sum(int a, int b) 
                            {
                                #warning test warning
                                return a + b;                    
                            }
                        }";

        try
        {
            string script   = CSSEnvironment.SaveAsTempScript(code);
            string assembly = CSScript.CompileWithConfig(script, null, false, CSScript.GlobalSettings, "/warnaserror");
        }
        catch (CompilerException e)
        {
            ReportCompilerError(e);
        }
    }
Beispiel #8
0
    public int MainImpl(string[] args)
    {
        //System.Diagnostics.Debug.Assert(false);
        string originalFile  = args[0];
        string generatedFile = Path.ChangeExtension(originalFile, ".g.cs");

        ////////////////////////////////////
        //resolve all required file names
        if (args.Length > 1 && !args[1].StartsWith("/primary:"))
        {
            generatedFile = Path.Combine(Path.GetDirectoryName(generatedFile), args[1]);
        }

        if (CSScript.GlobalSettings.HideAutoGeneratedFiles == Settings.HideOptions.HideAll)
        {
            if (Environment.GetEnvironmentVariable("CSScriptDebugging") != null) //running under VS on-flay project
            {
                if (CSSEnvironment.PrimaryScriptFile != null && CSSEnvironment.PrimaryScriptFile != "")
                {
                    generatedFile = Path.Combine(CSSEnvironment.GetCacheDirectory(originalFile), Path.GetFileName(generatedFile));
                }
                else
                {
                    //there will be no CSSEnvironment.PrimaryScriptFile if we are running from VS
                    //but VS will pass is as an extra arg
                    for (int i = 1; i < args.Length; i++)
                    {
                        if (args[i].StartsWith("/primary:"))
                        {
                            string primaryScriptFile = args[i].Substring("/primary:".Length);
                            generatedFile = Path.Combine(CSSEnvironment.GetCacheDirectory(primaryScriptFile), Path.GetFileName(generatedFile));
                            break;
                        }
                    }
                }
            }
            else if (Environment.GetEnvironmentVariable("CSScriptRuntime") != null) //running as a script
            {
                generatedFile = Path.Combine(CSSEnvironment.GetCacheDirectory(CSSEnvironment.PrimaryScriptFile), Path.GetFileName(generatedFile));
            }
        }

        if (!Directory.Exists(Path.GetDirectoryName(generatedFile)))
        {
            Directory.CreateDirectory(Path.GetDirectoryName(generatedFile));
        }

        string oldGeneratedCode = "";

        if (File.Exists(generatedFile))
        {
            using (StreamReader sr = new StreamReader(generatedFile))
                oldGeneratedCode = sr.ReadToEnd();
        }
        else
        {
            using (StreamWriter sw = new StreamWriter(generatedFile)) //create dummy just in case if developer did not specify any macros top be replaced
                sw.WriteLine();
        }

        ////////////////////////////////////
        //parse the file with the macros instructions

        //supportedMacros
        string css_extend_str_enum = "css_extend_str_enum";
        string css_extend_class    = "css_extend_class";

        using (StreamReader sr = new StreamReader(originalFile))
            using (StreamWriter sw = new StreamWriter(generatedFile))
            {
                string line = "";

                string header = "// AUTO-GENERATED FILE; DO NOT MODIFY\r\n" +
                                "using System;\r\n";
                string        footer     = "";
                StringBuilder classCode  = new StringBuilder();
                StringBuilder moduleCode = new StringBuilder();

                string        autoTypeName = null;
                Context       context      = new Context();
                List <string> tokens       = new List <string>();
                while ((line = sr.ReadLine()) != null)
                {
                    line = line.Trim();
                    if (line.StartsWith("* ")) //VS likes to insert "* " when new line is entered inside of /**/
                    {
                        line = line.Substring(1).Trim();
                    }

                    tokens.Clear();
                    tokens.AddRange(line.Split(' '));
                    tokens.RemoveAll(delegate(string item) { return(item.Trim() == ""); });
                    if (tokens.Count >= 3 && tokens[0] == "/*" && tokens[1].StartsWith("css_extend_")) //start of the declaration region (section)
                    {
                        // /* css_extend_class public Log

                        autoTypeName = tokens[tokens.Count - 1];
                        context.autoTypeDeclaration = tokens[1];
                        context.autoTypeName        = autoTypeName;
                        context.autoTypeModifier    = "";
                        for (int i = 2; i < tokens.Count - 1; i++)
                        {
                            context.autoTypeModifier = tokens[i] + " ";
                        }
                        context.macros.Clear();

                        classCode.Length = 0;

                        CompileResult result = OnBeforeSection(context);
                        if (result != null)
                        {
                            if (result.insertionPosition == InsertionPosition.ClassBody)
                            {
                                classCode.AppendLine(result.code);
                            }
                            else if (result.insertionPosition == InsertionPosition.ModuleStart)
                            {
                                header += result.code + "\r\n";
                            }
                            else if (result.insertionPosition == InsertionPosition.ClassStart)
                            {
                                header += result.code + "\r\n";
                            }
                        }

                        string[] nameParts = autoTypeName.Split('.');
                        for (int i = 0; i < nameParts.Length - 1; i++)
                        {
                            classCode.AppendLine("namespace " + nameParts[i]);
                            classCode.AppendLine("{");
                            classCode.AppendLine();
                        }

                        //css_extend_class, css_extend_str_enum
                        if (tokens[1] == css_extend_class)
                        {
                            classCode.AppendLine(context.autoTypeModifier + "partial class " + nameParts[nameParts.Length - 1]);
                        }
                        else if (tokens[1] == css_extend_str_enum)
                        {
                            classCode.AppendLine(context.autoTypeModifier + "enum " + nameParts[nameParts.Length - 1]);
                        }
                        classCode.AppendLine("{");
                    }
                    else if (autoTypeName != null && line.Replace(" ", "").StartsWith("*/")) //end of the declaration region
                    {
                        classCode.AppendLine("}\r\n");
                        string[] nameParts = autoTypeName.Split('.');
                        for (int i = 0; i < nameParts.Length - 1; i++)
                        {
                            classCode.AppendLine("}");
                            classCode.AppendLine();
                        }

                        CompileResult result = OnAfterSection(context);
                        if (result != null)
                        {
                            if (result.insertionPosition == InsertionPosition.ClassBody)
                            {
                                classCode.AppendLine(result.code);
                            }
                            else if (result.insertionPosition == InsertionPosition.ModuleStart)
                            {
                                header += result.code + "\r\n";
                            }
                            else if (result.insertionPosition == InsertionPosition.ClassStart)
                            {
                                header += result.code + "\r\n";
                            }
                        }

                        moduleCode.AppendLine(classCode.ToString());
                        moduleCode.AppendLine();

                        autoTypeName = null;
                    }
                    else if (autoTypeName != null) //line containing macro definition
                    {
                        bool found = false;
                        foreach (string key in macros.Keys)
                        {
                            if (line.StartsWith(key + "(") || line.StartsWith(key + " "))
                            {
                                found = true;
                                string[] macroArgs = ExtractArgs(line.Substring(key.Length));

                                if (!context.macros.ContainsKey(autoTypeName))
                                {
                                    context.macros[autoTypeName] = new List <string[]>();
                                }

                                context.macros[autoTypeName].Add(macroArgs); //save macro definition

                                object[] parameters = new object[] { macroArgs, context };

                                //need to use reflection as methods added/declared by used are unknow
                                CompileResult result = (CompileResult)macros[key].Invoke(this, parameters);

                                if (result.insertionPosition == InsertionPosition.ClassBody)
                                {
                                    classCode.AppendLine(result.code);
                                }
                                else if (result.insertionPosition == InsertionPosition.ModuleStart)
                                {
                                    header += result.code + "\r\n";
                                }
                                else if (result.insertionPosition == InsertionPosition.ClassStart)
                                {
                                    header += result.code + "\r\n";
                                }
                            }
                        }
                        if (!found)
                        {
                            Console.WriteLine("\nerror: the macro \"" + line + "\" cannot be translated.\n");
                            return(1);
                        }
                    }
                }

                moduleCode.Insert(0, header + "\r\n");
                moduleCode.AppendLine(footer);

                //if (oldGeneratedCode != moduleCode.ToString())
                sw.Write(moduleCode.ToString()); //for now do always
            }
        return(0);
    }