Пример #1
0
 public void Setup()
 {
     ProtoCore.Options options = new ProtoCore.Options();
     core = new ProtoCore.Core(options);
     core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core));
     core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core));
 }
Пример #2
0
        private bool LocateAssembly(string assembly, out string assemblyPath)
        {
            ProtoCore.Options options = null;
            if (null == core)
            {
                options = new ProtoCore.Options()
                {
                    RootModulePathName = String.Empty
                }
            }
            ;
            else
            {
                options = core.Options;
            }

            assemblyPath = FileUtils.GetDSFullPathName(assembly, options);
            string dirName = Path.GetDirectoryName(assemblyPath);

            if (!string.IsNullOrEmpty(dirName) && !core.Options.IncludeDirectories.Contains(dirName))
            {
                core.Options.IncludeDirectories.Add(dirName);
            }

            return(File.Exists(assemblyPath));
        }
Пример #3
0
 public void Setup()
 {
     ProtoCore.Options options = new ProtoCore.Options();
     core = new ProtoCore.Core(options);
     core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core));
     core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core));
 }
Пример #4
0
        /// Checks if the string in code block node is a literal or an identifier or has multiple lines of code.
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static SnapshotNodeType AnalyzeString(string code)
        {
            SnapshotNodeType type = SnapshotNodeType.None;

            if (!code.EndsWith(";"))
            {
                code += ";";
            }
            List <ProtoCore.AST.Node> n = new List <ProtoCore.AST.Node>();

            try
            {
                ProtoCore.Options options = new ProtoCore.Options();
                options.RootModulePathName = string.Empty;

                ProtoCore.Core core = new ProtoCore.Core(options);
                core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core));
                core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core));
                core.IsParsingPreloadedAssembly = false;
                core.IsParsingCodeBlockNode     = true;
                core.ParsingMode = ProtoCore.ParseMode.AllowNonAssignment;

                System.IO.MemoryStream memstream       = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(code));
                ProtoCore.DesignScriptParser.Scanner s = new ProtoCore.DesignScriptParser.Scanner(memstream);
                ProtoCore.DesignScriptParser.Parser  p = new ProtoCore.DesignScriptParser.Parser(s, core);

                p.Parse();
                ProtoCore.AST.AssociativeAST.CodeBlockNode codeBlockNode = p.root as ProtoCore.AST.AssociativeAST.CodeBlockNode;
                n = p.GetParsedASTList(codeBlockNode);
            }
            catch (Exception)
            {
                //if syntax return SnapshotNodeType as None
                return(SnapshotNodeType.CodeBlock);
            }

            if (n.Count > 1 || n.Count == 0)
            {
                type = SnapshotNodeType.CodeBlock;
            }
            else if (n[0] is ProtoCore.AST.AssociativeAST.BinaryExpressionNode)
            {
                type = SnapshotNodeType.CodeBlock;
            }
            else if (n[0] is ProtoCore.AST.AssociativeAST.IdentifierNode)
            {
                type = SnapshotNodeType.Identifier;
            }
            else if (n[0] is ProtoCore.AST.AssociativeAST.IntNode || n[0] is ProtoCore.AST.AssociativeAST.DoubleNode || n[0] is ProtoCore.AST.AssociativeAST.StringNode || n[0] is ProtoCore.AST.AssociativeAST.FunctionCallNode || n[0] is ProtoCore.AST.AssociativeAST.RangeExprNode)
            {
                type = SnapshotNodeType.Literal;
            }
            else
            {
                type = SnapshotNodeType.CodeBlock;
            }
            return(type);
        }
Пример #5
0
        /// <summary>
        /// Locates the given file from the search path options and gets the
        /// full file path.
        /// </summary>
        /// <param name="fileName">Name of the file to locate</param>
        /// <param name="options">Options structure for search path, if options
        /// is null it will search only in the executing assembly path or the
        /// current directory.</param>
        /// <returns>Full path for the file if located successfully else the
        /// file name when failed to loate the given file</returns>
        public static string GetDSFullPathName(string fileName, ProtoCore.Options options = null)
        {
            //1.  First search at .exe module directory, in case files of the same name exists in the following directories.
            //    The .exe module directory is of highest priority.
            //    CodeBase is used here because Assembly.Location does not work quite well when the module is shallow-copied in nunit test.
            if (Path.IsPathRooted(fileName))
            {
                if (File.Exists(fileName))
                {
                    return(Path.GetFullPath(fileName));
                }
                fileName = Path.GetFileName(fileName);
            }

            string fullPathName;

            if (GetFullPath(fileName, GetInstallLocation(), out fullPathName))
            {
                return(fullPathName);
            }

            //2. Search relative to the .ds file directory
            string rootModulePath = ".";

            if (null != options && !string.IsNullOrEmpty(options.RootModulePathName))
            {
                rootModulePath = options.RootModulePathName;
            }

            if (GetFullPath(fileName, rootModulePath, out fullPathName))
            {
                return(fullPathName);
            }

            if (null != options)
            {
                //3. Search at include directories.
                //   This will include the import path.
                foreach (string directory in options.IncludeDirectories)
                {
                    fullPathName = Path.Combine(directory, fileName);
                    if (null != fullPathName && File.Exists(fullPathName))
                    {
                        return(fullPathName);
                    }
                }
            }

            //4. Search the absolute path or relative to the current directory
            if (File.Exists(fileName))
            {
                return(Path.GetFullPath(fileName));
            }

            return(fileName);
        }
        public override void Init()
        {
            base.Init();

            var options = new ProtoCore.Options();

            options.RootModulePathName = string.Empty;
            libraryServicesCore        = new ProtoCore.Core(options);
            libraryServicesCore.Compilers.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Compiler(libraryServicesCore));
            libraryServicesCore.Compilers.Add(ProtoCore.Language.kImperative, new ProtoImperative.Compiler(libraryServicesCore));

            libraryServices = new LibraryServices(libraryServicesCore);
        }
Пример #7
0
 public void Setup()
 {
     // Specify some of the requirements of IDE.
     ProtoCore.Options options = new ProtoCore.Options();
     options.ExecutionMode       = ProtoCore.ExecutionMode.Serial;
     options.SuppressBuildOutput = false;
     core = new ProtoCore.Core(options);
     core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core));
     core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core));
     runnerConfig             = new ProtoScript.Config.RunConfiguration();
     runnerConfig.IsParrallel = false;
     fsr = new ProtoScript.Runners.DebugRunner(core);
 }
Пример #8
0
 public void Setup()
 {
     // Specify some of the requirements of IDE.
     ProtoCore.Options options = new ProtoCore.Options();
     options.ExecutionMode = ProtoCore.ExecutionMode.Serial;
     options.SuppressBuildOutput = false;
     core = new ProtoCore.Core(options);
     core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core));
     core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core));
     runnerConfig = new ProtoScript.Config.RunConfiguration();
     runnerConfig.IsParrallel = false;
     fsr = new ProtoScript.Runners.DebugRunner(core);
 }
Пример #9
0
        public void Init()
        {
            string libraryPath = "FFITarget.dll";

            var options = new ProtoCore.Options();

            options.RootModulePathName = string.Empty;

            libraryServicesCore = new ProtoCore.Core(options);
            libraryServicesCore.Compilers.Add(ProtoCore.Language.Associative, new ProtoAssociative.Compiler(libraryServicesCore));
            libraryServicesCore.Compilers.Add(ProtoCore.Language.Imperative, new ProtoImperative.Compiler(libraryServicesCore));

            CompilerUtils.TryLoadAssemblyIntoCore(libraryServicesCore, libraryPath);
        }
Пример #10
0
 public void Setup()
 {
     var options = new ProtoCore.Options();
     options.ExecutionMode = ProtoCore.ExecutionMode.Serial;
     options.SuppressBuildOutput = false;
     core_ = new ProtoCore.Core(options);
     core_.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core_));
     core_.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core_));
     runconfig_ = new ProtoScript.Config.RunConfiguration();
     runconfig_.IsParrallel = false;
     runner_ = new DebugRunner(core_);
     DLLFFIHandler.Register(FFILanguage.CSharp, new CSModuleHelper());
     CLRModuleType.ClearTypes();
 }
Пример #11
0
        public override void Init()
        {
            base.Init();

            var options = new ProtoCore.Options();
            options.RootModulePathName = string.Empty;
            libraryServicesCore = new ProtoCore.Core(options);
            libraryServicesCore.Executives.Add(ProtoCore.Language.kAssociative,
                new ProtoAssociative.Executive(libraryServicesCore));
            libraryServicesCore.Executives.Add(ProtoCore.Language.kImperative,
                new ProtoImperative.Executive(libraryServicesCore));

            libraryServices = new LibraryServices(libraryServicesCore);
        }
Пример #12
0
        public void Setup()
        {
            var options = new ProtoCore.Options();

            options.ExecutionMode       = ProtoCore.ExecutionMode.Serial;
            options.SuppressBuildOutput = false;
            core_ = new ProtoCore.Core(options);
            core_.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core_));
            core_.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core_));
            runconfig_             = new ProtoScript.Config.RunConfiguration();
            runconfig_.IsParrallel = false;
            runner_ = new DebugRunner(core_);
            DLLFFIHandler.Register(FFILanguage.CSharp, new CSModuleHelper());
            CLRModuleType.ClearTypes();
        }
Пример #13
0
 public void Setup()
 {
     // Specify some of the requirements of IDE.
     var options = new ProtoCore.Options();
     options.ExecutionMode = ProtoCore.ExecutionMode.Serial;
     options.SuppressBuildOutput = false;
     core = new ProtoCore.Core(options);
     core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core));
     core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core));
     runnerConfig = new ProtoScript.Config.RunConfiguration();
     runnerConfig.IsParrallel = false;
     fsr = new DebugRunner(core);
     DLLFFIHandler.Register(FFILanguage.CSharp, new CSModuleHelper());
     CLRModuleType.ClearTypes();
 }
Пример #14
0
        private void InitOptions()
        {
            // Build the options required by the core
            Validity.Assert(coreOptions == null);
            coreOptions = new ProtoCore.Options();
            coreOptions.GenerateExprID   = true;
            coreOptions.IsDeltaExecution = true;

            coreOptions.WebRunner     = false;
            coreOptions.ExecutionMode = ProtoCore.ExecutionMode.Serial;
            //coreOptions.DumpByteCode = true;
            //coreOptions.Verbose = true;

            // This should have been set in the consturctor
            Validity.Assert(executionOptions != null);
        }
Пример #15
0
        public void Setup()
        {
            // Specify some of the requirements of IDE.
            var options = new ProtoCore.Options();

            options.ExecutionMode       = ProtoCore.ExecutionMode.Serial;
            options.SuppressBuildOutput = false;
            core = new ProtoCore.Core(options);
            core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core));
            core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core));
            runnerConfig             = new ProtoScript.Config.RunConfiguration();
            runnerConfig.IsParrallel = false;
            fsr = new DebugRunner(core);
            DLLFFIHandler.Register(FFILanguage.CSharp, new CSModuleHelper());
            CLRModuleType.ClearTypes();
        }
Пример #16
0
        public void PreStart(String source, Dictionary<string, Object> context)
        {
            ProtoCore.Options options = new ProtoCore.Options();
            options.ExecutionMode = ProtoCore.ExecutionMode.Serial;


            RunnerCore = new ProtoCore.Core(options);
            RunnerCore.Compilers.Add(ProtoCore.Language.Associative, new ProtoAssociative.Compiler(RunnerCore));
            RunnerCore.Compilers.Add(ProtoCore.Language.Imperative, new ProtoImperative.Compiler(RunnerCore));

            ProtoFFI.DLLFFIHandler.Register(ProtoFFI.FFILanguage.CSharp, new ProtoFFI.CSModuleHelper());

            ExecutionContext = new ProtoCore.CompileTime.Context(source, context);

            Runner = new ProtoScriptRunner();
        }
Пример #17
0
        public void PreStart(String source, Dictionary <string, Object> context)
        {
            ProtoCore.Options options = new ProtoCore.Options();
            options.ExecutionMode = ProtoCore.ExecutionMode.Serial;


            RunnerCore = new ProtoCore.Core(options);
            RunnerCore.Compilers.Add(ProtoCore.Language.Associative, new ProtoAssociative.Compiler(RunnerCore));
            RunnerCore.Compilers.Add(ProtoCore.Language.Imperative, new ProtoImperative.Compiler(RunnerCore));

            ProtoFFI.DLLFFIHandler.Register(ProtoFFI.FFILanguage.CSharp, new ProtoFFI.CSModuleHelper());

            ExecutionContext = new ProtoCore.CompileTime.Context(source, context);

            Runner = new ProtoScriptRunner();
        }
Пример #18
0
        private ProtoCore.Core CompileCodeSnapshot(AutoCompleteWorkData workData)
        {
            if (null != this.scopeIdentifiers)
            {
                this.scopeIdentifiers.Clear();
                this.scopeIdentifiers = null;
            }

            ProtoCore.Options options = new ProtoCore.Options();
            options.RootModulePathName = workData.ScriptPath;
            ProtoCore.Core core = new ProtoCore.Core(options);

            core.CurrentDSFileName = workData.ScriptPath;
            ProtoFFI.DLLFFIHandler.Register(ProtoFFI.FFILanguage.CSharp, new ProtoFFI.CSModuleHelper());

            // Register a message stream if we do have one.
            if (null != this.MessageHandler)
            {
                core.BuildStatus.MessageHandler = this.MessageHandler;
            }

            MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(workData.CodeSnapshot));

            ProtoCore.DesignScriptParser.Scanner s = new ProtoCore.DesignScriptParser.Scanner(stream);
            ProtoCore.DesignScriptParser.Parser  p = new ProtoCore.DesignScriptParser.Parser(s, core);

            try
            {
                p.Parse();
                CoreCodeGen.arrayTypeTable = new ArrayTypeTable();
                AssociativeCodeGen codegen = new AssociativeCodeGen(core);

                codegen.Emit(p.root as ProtoCore.AST.AssociativeAST.CodeBlockNode);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception Caught in CodeGen");
                System.Diagnostics.Debug.WriteLine(ex.Message);
                core = null;
            }
            finally
            {
                // Do necessary clean-up here.
            }

            return(core);
        }
Пример #19
0
        /// <summary>
        /// Execute to gather information about the program
        /// Data is stored in ProtoCore.CompileAndExecutePass.ProgramData
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="programData"></param>
        /// <returns></returns>
        private bool CompileAndExecutePass(string filename, out ProtoCore.CompileAndExecutePass.ProgramData programData)
        {
            ProtoCore.Options options = new ProtoCore.Options();
            ProtoCore.Core    core    = new ProtoCore.Core(options);
            options.ExecutionMode = ProtoCore.ExecutionMode.Serial;
            core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core));
            core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core));
            core.Options.DumpByteCode = true;
            core.Options.Verbose      = true;

            ProtoFFI.DLLFFIHandler.Register(ProtoFFI.FFILanguage.CSharp, new ProtoFFI.CSModuleHelper());
            ExecutionMirror mirror = LoadAndExecute(filename, core);

            programData = core.GetProgramData();

            return(mirror == null ? false : true);
        }
Пример #20
0
        public static bool Compile(string src, string entryFile)
        {
            ProtoCore.Options ops = new ProtoCore.Options();
            ops.RootModulePathName = entryFile;
            if (null != AutoCompletionHelper.searchPaths)
            {
                ops.IncludeDirectories.AddRange(AutoCompletionHelper.searchPaths);
            }

            core = new ProtoCore.Core(ops);

            core.CurrentDSFileName = entryFile;

            CoreCodeGen.ResetInternalStates();
            ProtoFFI.DLLFFIHandler.Register(ProtoFFI.FFILanguage.CSharp, new ProtoFFI.CSModuleHelper());

            // Register a message stream if we do have one.
            if (null != AutoCompletionHelper.MessageHandler)
            {
                core.BuildStatus.MessageHandler = MessageHandler;
            }

            MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(src));

            ProtoCore.DesignScriptParser.Scanner s = new ProtoCore.DesignScriptParser.Scanner(ms);
            ProtoCore.DesignScriptParser.Parser  p = new ProtoCore.DesignScriptParser.Parser(s, core);

            try
            {
                p.Parse();

                CoreCodeGen.arrayTypeTable = new ArrayTypeTable();
                AssociativeCodeGen codegen = new AssociativeCodeGen(core);
                codegen.Emit(p.root as ProtoCore.AST.AssociativeAST.CodeBlockNode);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception Caught in CodeGen");
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return(false);
            }

            return(true);
        }
Пример #21
0
        /// Checks if the string in code block node is a literal or an identifier or has multiple lines of code.
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static SnapshotNodeType AnalyzeString(string code)
        {
            SnapshotNodeType type = SnapshotNodeType.None;
            if (!code.EndsWith(";")) code += ";";
            List<ProtoCore.AST.Node> n = new List<ProtoCore.AST.Node>();

            try
            {
                ProtoCore.Options options = new ProtoCore.Options();
                options.RootModulePathName = string.Empty;

                ProtoCore.Core core = new ProtoCore.Core(options);
                core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core));
                core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core));
                core.IsParsingPreloadedAssembly = false;
                core.IsParsingCodeBlockNode = true;
                core.ParsingMode = ProtoCore.ParseMode.AllowNonAssignment;

                System.IO.MemoryStream memstream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(code));
                ProtoCore.DesignScriptParser.Scanner s = new ProtoCore.DesignScriptParser.Scanner(memstream);
                ProtoCore.DesignScriptParser.Parser p = new ProtoCore.DesignScriptParser.Parser(s, core);

                p.Parse();
                ProtoCore.AST.AssociativeAST.CodeBlockNode codeBlockNode = p.root as ProtoCore.AST.AssociativeAST.CodeBlockNode;
                n = p.GetParsedASTList(codeBlockNode);
            }
            catch (Exception)
            {
                //if syntax return SnapshotNodeType as None
                return SnapshotNodeType.CodeBlock;
            }

            if (n.Count > 1 || n.Count == 0)
                type = SnapshotNodeType.CodeBlock;
            else if (n[0] is ProtoCore.AST.AssociativeAST.BinaryExpressionNode)
                type = SnapshotNodeType.CodeBlock;
            else if (n[0] is ProtoCore.AST.AssociativeAST.IdentifierNode)
                type = SnapshotNodeType.Identifier;
            else if (n[0] is ProtoCore.AST.AssociativeAST.IntNode || n[0] is ProtoCore.AST.AssociativeAST.DoubleNode || n[0] is ProtoCore.AST.AssociativeAST.StringNode || n[0] is ProtoCore.AST.AssociativeAST.FunctionCallNode || n[0] is ProtoCore.AST.AssociativeAST.RangeExprNode)
                type = SnapshotNodeType.Literal;
            else type = SnapshotNodeType.CodeBlock;
            return type;
        }
Пример #22
0
        public ProtoVMState PreStart(String source, Dictionary<string, Object> context)
        {
            ProtoCore.Options options = new ProtoCore.Options();
            options.ExecutionMode = ProtoCore.ExecutionMode.Serial;


            RunnerCore = new ProtoCore.Core(options);
            RunnerCore.Compilers.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Compiler(RunnerCore));
            RunnerCore.Compilers.Add(ProtoCore.Language.kImperative, new ProtoImperative.Compiler(RunnerCore));

            ProtoFFI.DLLFFIHandler.Register(ProtoFFI.FFILanguage.CSharp, new ProtoFFI.CSModuleHelper());

            //Validity.Assert(null == ExecutionContext);
            ExecutionContext = new ProtoCore.CompileTime.Context(source, context);

            //Validity.Assert(null == Runner);
            Runner = new ProtoScriptRunner();

            // TODO Jun: Implement run and halt at the first instruction
            //ProtoCore.DSASM.Mirror.ExecutionMirror mirror = null; // runner.Execute(executionContext, RunnerCore);

            return new ProtoVMState(RunnerCore, runtimeCore);
        }
Пример #23
0
        public ProtoVMState PreStart(String source, Dictionary <string, Object> context)
        {
            ProtoCore.Options options = new ProtoCore.Options();
            options.ExecutionMode = ProtoCore.ExecutionMode.Serial;


            RunnerCore = new ProtoCore.Core(options);
            RunnerCore.Compilers.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Compiler(RunnerCore));
            RunnerCore.Compilers.Add(ProtoCore.Language.kImperative, new ProtoImperative.Compiler(RunnerCore));

            ProtoFFI.DLLFFIHandler.Register(ProtoFFI.FFILanguage.CSharp, new ProtoFFI.CSModuleHelper());

            //Validity.Assert(null == ExecutionContext);
            ExecutionContext = new ProtoCore.CompileTime.Context(source, context);

            //Validity.Assert(null == Runner);
            Runner = new ProtoScriptRunner();

            // TODO Jun: Implement run and halt at the first instruction
            //ProtoCore.DSASM.Mirror.ExecutionMirror mirror = null; // runner.Execute(executionContext, RunnerCore);

            return(new ProtoVMState(RunnerCore, runtimeCore));
        }
Пример #24
0
        private void InitOptions()
        {

            // Build the options required by the core
            Validity.Assert(coreOptions == null);
            coreOptions = new ProtoCore.Options();
            coreOptions.GenerateExprID = true;
            coreOptions.IsDeltaExecution = true;
            coreOptions.BuildOptErrorAsWarning = true;
            
            coreOptions.WebRunner = false;
            coreOptions.ExecutionMode = ProtoCore.ExecutionMode.Serial;
            //coreOptions.DumpByteCode = true;
            //coreOptions.Verbose = true;

            // This should have been set in the consturctor
            Validity.Assert(executionOptions != null); 
        }
Пример #25
0
        public void Init()
        {
            string libraryPath = "FFITarget.dll";

            var options = new ProtoCore.Options();
            options.RootModulePathName = string.Empty;

            libraryServicesCore = new ProtoCore.Core(options);
            libraryServicesCore.Compilers.Add(ProtoCore.Language.Associative, new ProtoAssociative.Compiler(libraryServicesCore));
            libraryServicesCore.Compilers.Add(ProtoCore.Language.Imperative, new ProtoImperative.Compiler(libraryServicesCore));

            CompilerUtils.TryLoadAssemblyIntoCore(libraryServicesCore, libraryPath);
        }
Пример #26
0
        private ProtoCore.Core CompileCodeSnapshot(AutoCompleteWorkData workData)
        {
            if (null != this.scopeIdentifiers)
            {
                this.scopeIdentifiers.Clear();
                this.scopeIdentifiers = null;
            }

            ProtoCore.Options options = new ProtoCore.Options();
            options.RootModulePathName = workData.ScriptPath;
            ProtoCore.Core core = new ProtoCore.Core(options);

            core.CurrentDSFileName = workData.ScriptPath;
            ProtoFFI.DLLFFIHandler.Register(ProtoFFI.FFILanguage.CSharp, new ProtoFFI.CSModuleHelper());

            // Register a message stream if we do have one.
            if (null != this.MessageHandler)
                core.BuildStatus.MessageHandler = this.MessageHandler;

            MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(workData.CodeSnapshot));
            ProtoCore.DesignScriptParser.Scanner s = new ProtoCore.DesignScriptParser.Scanner(stream);
            ProtoCore.DesignScriptParser.Parser p = new ProtoCore.DesignScriptParser.Parser(s, core);

            try
            {
                p.Parse();
                CoreCodeGen.arrayTypeTable = new ArrayTypeTable();
                AssociativeCodeGen codegen = new AssociativeCodeGen(core);

                codegen.Emit(p.root as ProtoCore.AST.AssociativeAST.CodeBlockNode);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception Caught in CodeGen");
                System.Diagnostics.Debug.WriteLine(ex.Message);
                core = null;
            }
            finally
            {
                // Do necessary clean-up here.
            }

            return core;
        }
Пример #27
0
        private static void BuildCore(bool isCodeBlockNode = false, bool isPreloadedAssembly = false)
        {
            if (core == null)
            {
                ProtoCore.Options options = new ProtoCore.Options();
                options.RootModulePathName = rootModulePath;
                core = new ProtoCore.Core(options);
                core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core));
                core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core));

            }
            else
            {
                //core.ResetDeltaExecution();
                core.ResetForPrecompilation();

            }
            core.IsParsingPreloadedAssembly = isPreloadedAssembly;
            core.IsParsingCodeBlockNode = isCodeBlockNode;
            core.ParsingMode = ProtoCore.ParseMode.AllowNonAssignment;
        }
Пример #28
0
        public static List<SnapshotNode> NodeToCodeBlocks(List<SnapshotNode> inputs, GraphToDSCompiler.GraphCompiler originalGC)
        {
            List<SnapshotNode> codeBlocks = new List<SnapshotNode>();
            GraphToDSCompiler.GraphCompiler newGC = GraphCompiler.CreateInstance();

            newGC.SetCore(core);
            GraphToDSCompiler.SynchronizeData newSyncData = new SynchronizeData();
            newSyncData.AddedNodes = inputs;
            newSyncData.ModifiedNodes = new List<SnapshotNode>();
            newSyncData.RemovedNodes = new List<uint>();
            GraphToDSCompiler.GraphBuilder GB = new GraphBuilder(newSyncData, newGC);

            #region fix connection for multi-line CBN
            /*for multi-line code blocks*/
            List<Node> completeList = originalGC.Graph.nodeList;
            List<uint> originalNodeUIDList = new List<uint>();
            foreach (Node oriGcNode in completeList)
            {
                originalNodeUIDList.Add(oriGcNode.Guid);
            }

            GB.AddNodesToAST();

            //List<SnapshotNode> inputsCopy = new List<SnapshotNode>(inputs);
            for (int i = 0; i < inputs.Count; i++)
            {
                SnapshotNode inputSnapshotNode = inputs[i];
                for (int j = 0; j < inputSnapshotNode.InputList.Count; j++)
                {
                    Connection inputConnection = inputSnapshotNode.InputList[j];
                    if (!originalNodeUIDList.Contains(inputConnection.OtherNode))
                    {
                        Connection correctedInputConnection = new Connection();
                        correctedInputConnection.LocalName = inputConnection.LocalName;
                        correctedInputConnection.LocalIndex = inputConnection.LocalIndex;
                        correctedInputConnection.IsImplicit = inputConnection.IsImplicit;
                        correctedInputConnection.OtherIndex = inputConnection.OtherIndex;
                        if (newGC.codeBlockUIDMap.ContainsKey(inputConnection.OtherNode))
                        {
                            correctedInputConnection.OtherNode = newGC.codeBlockUIDMap[inputConnection.OtherNode][inputConnection.OtherIndex];
                        }
                        else
                        {
                            correctedInputConnection.OtherNode = originalGC.codeBlockUIDMap[inputConnection.OtherNode][inputConnection.OtherIndex];
                        }
                        inputSnapshotNode.InputList.Remove(inputConnection);
                        inputSnapshotNode.InputList.Insert(j, correctedInputConnection);
                    }
                }
                for (int j = 0; j < inputSnapshotNode.OutputList.Count; j++)
                {
                    Connection outputConnection = inputSnapshotNode.OutputList[j];
                    if (!originalNodeUIDList.Contains(outputConnection.OtherNode))                       // if the other node is split
                    {
                        Connection correctedInputConnection = new Connection();
                        correctedInputConnection.LocalName = outputConnection.LocalName;
                        correctedInputConnection.LocalIndex = outputConnection.LocalIndex;
                        correctedInputConnection.IsImplicit = outputConnection.IsImplicit;
                        correctedInputConnection.OtherIndex = outputConnection.OtherIndex;
                        if (newGC.codeBlockUIDMap.ContainsKey(outputConnection.OtherNode))
                        {
                            correctedInputConnection.OtherNode = newGC.GetUidOfRHSIdentifierInCodeBlock(
                                outputConnection.OtherNode, outputConnection.OtherIndex, outputConnection.LocalName);
                            //correctedInputConnection.OtherNode = newGC.codeBlockUIDMap[outputConnection.OtherNode][outputConnection.OtherIndex];
                        }
                        else
                        {
                            correctedInputConnection.OtherNode = originalGC.codeBlockUIDMap[outputConnection.OtherNode][outputConnection.OtherIndex];
                        }
                        inputSnapshotNode.OutputList.Remove(outputConnection);
                        inputSnapshotNode.OutputList.Insert(j, correctedInputConnection);
                    }
                }
            }
            GB.nodesToAdd = inputs;
            GB.MakeConnectionsForAddedNodes_NodeToCode(GB.nodesToAdd);
            newGC.PrintGraph();
            #endregion

            //GB.BuildGraphForCodeBlock();

            List<uint> nodesToBeAdded = new List<uint>();
            List<Node> nodesToBeReplaced = new List<Node>();

            //adding children node from the originalGC to the newGC needed for the newGC to generate code
            foreach (Node n in completeList)
            {
                foreach (Node child in n.GetChildren())
                {
                    if (newGC.Graph.GetNode(child.Guid) != null)
                    {
                        if (child.Name != newGC.Graph.GetNode(child.Guid).Name)
                        {
                            nodesToBeReplaced.Add(child);
                        }
                    }
                }
            }

            foreach (uint n in nodesToBeAdded)
            {
                Node n1 = completeList.FirstOrDefault(q => q.Guid == n);
                //n1.children.Clear();
                nodesToBeReplaced.Add(n1);
                //newSyncData.RemovedNodes.Add(n);
            }

            List<uint> nodeToCodeUIDs = new List<uint>();
            foreach (SnapshotNode ssn in inputs)
                nodeToCodeUIDs.Add(ssn.Id);
            newGC.nodeToCodeUIDs = nodeToCodeUIDs;

            /*create output snapshot nodes*/
            List<Connection> inputNodeInputConnections = new List<Connection>();
            List<Connection> inputNodeOutputConnections = new List<Connection>();
            foreach (SnapshotNode ssn in inputs)
            {
                foreach (Connection inputConnection in ssn.InputList)
                {
                    if (!nodeToCodeUIDs.Contains(inputConnection.OtherNode))
                        inputNodeInputConnections.Add(inputConnection);
                }
                foreach (Connection outputConnection in ssn.OutputList)
                {
                    if (!nodeToCodeUIDs.Contains(outputConnection.OtherNode))
                        inputNodeOutputConnections.Add(outputConnection);
                }
            }

            newGC.ReplaceNodesFromAList(nodesToBeReplaced);
            newSyncData.AddedNodes = new List<SnapshotNode>();
            newSyncData.ModifiedNodes = new List<SnapshotNode>();
            newSyncData.RemovedNodes = new List<uint>();
            GB = new GraphBuilder(newSyncData, newGC);
            //string result = GB.BuildGraphDAG();
            List<SnapshotNode> nodeToCodeBlocks = GB.PrintCodeForSelectedNodes(originalGC, inputs);

            /*for now, only connected nodes are supported: return all connections that are not internal connections (connections between the selected nodes)*/
            //uint id = 0;
            //foreach (string content in toCode)
            //{
            //    SnapshotNode ssn = new SnapshotNode();
            //    ssn.Type = SnapshotNodeType.CodeBlock;
            //    ssn.Content = content;
            //    ssn.Id = id++;
            //    ssn.InputList = new List<Connection>();
            //    //stupid stub
            //    foreach (Connection inputConnection in inputNodeInputConnections)
            //    {
            //        Connection newInputConnection = new Connection();
            //        newInputConnection.OtherNode = inputConnection.OtherNode;
            //        newInputConnection.OtherIndex = inputConnection.OtherIndex;
            //        newInputConnection.IsImplicit = inputConnection.IsImplicit;
            //        string[] tokens = newGC.Graph.GetNode(inputConnection.OtherNode).Name.Split('=');
            //        newInputConnection.LocalName = tokens[0];
            //        ssn.InputList.Add(newInputConnection);
            //    }
            //    //ssn.InputList = inputNodeInputConnections;
            //    ssn.OutputList = new List<Connection>();
            //    foreach (Connection outputConnection in inputNodeOutputConnections)
            //    {
            //        Connection newOutputConnection = new Connection();
            //        newOutputConnection.OtherNode = outputConnection.OtherNode;
            //        newOutputConnection.OtherIndex = outputConnection.OtherIndex;
            //        newOutputConnection.IsImplicit = outputConnection.IsImplicit;
            //        //string[] tokens = originalGC.Graph.GetNode(outputConnection.OtherNode).Name.Split('=');
            //        newOutputConnection.LocalName = outputConnection.LocalName;
            //        ssn.OutputList.Add(newOutputConnection);
            //    }
            //    //ssn.OutputList = inputNodeOutputConnections;
            //    codeBlocks.Add(ssn);
            //}

            /*update the original GC*/
            foreach (SnapshotNode inputNode in inputs)
            {
                if (originalNodeUIDList.Contains(inputNode.Id))
                    originalGC.RemoveNodes(inputNode.Id, false);
                else
                {
                    foreach (KeyValuePair<uint, Dictionary<int, uint>> kvp in originalGC.codeBlockUIDMap)
                    {
                        if (kvp.Value.ContainsValue(inputNode.Id))
                        {
                            originalGC.RemoveNodes(kvp.Key, false);
                        }
                    }
                }
            }
            foreach (Node node in newGC.Graph.nodeList)
            {
                node.Name = node.Name.TrimEnd(';') + ";";
            }
            originalGC.Graph.nodeList.Union<Node>(newGC.Graph.nodeList);
            //originalGC = newGC;
            /**/

            return nodeToCodeBlocks;
            //return codeBlocks;
        }

        /// <summary>
        /// This is called to Parse individual assignment statements in Codeblock nodes in GraphUI
        /// and return the resulting ProtoAST node
        /// </summary>
        /// <param name="statement"></param>
        public static ProtoCore.AST.Node Parse(string statement, out ProtoCore.AST.AssociativeAST.CodeBlockNode commentNode)
        {
            commentNode = null;
            BuildCore(true);

            Validity.Assert(core != null);
            Validity.Assert(statement != null);

            if (string.IsNullOrEmpty(statement))
                return null;

            System.IO.MemoryStream memstream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(statement));
            ProtoCore.DesignScriptParser.Scanner s = new ProtoCore.DesignScriptParser.Scanner(memstream);
            ProtoCore.DesignScriptParser.Parser p = new ProtoCore.DesignScriptParser.Parser(s, core);

            p.Parse();
            commentNode = p.commentNode;

            return p.root;
        }

        public static List<ProtoCore.AST.Node> ParseCodeBlock(string code)
        {
            Validity.Assert(code != null);

            if (string.IsNullOrEmpty(code))
                return null;

            // TODO: Change the logic to ignore Import statements in this case using parser - pratapa
            // Check if this will work with modifier blocks as well
            /*string[] stmts = code.Split(';');
            string source = "";
            for (int i=0; i < stmts.Length; ++i)
            {
                if (!stmts[i].Contains("import"))
                    source += stmts[i] + ";";
            }*/

            ProtoCore.Options options = new ProtoCore.Options();
            ProtoCore.Core core = new ProtoCore.Core(options);
            core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core));
            core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core));

            System.IO.MemoryStream memstream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(code));
            ProtoCore.DesignScriptParser.Scanner s = new ProtoCore.DesignScriptParser.Scanner(memstream);
            ProtoCore.DesignScriptParser.Parser p = new ProtoCore.DesignScriptParser.Parser(s, core);

            p.Parse();
            ProtoCore.AST.AssociativeAST.CodeBlockNode cbn = p.root as ProtoCore.AST.AssociativeAST.CodeBlockNode;

            Validity.Assert(cbn != null);
            return p.GetParsedASTList(cbn);
        }
Пример #29
0
        public bool CompileToVHDL(string topLevelModule, string filename)
        {
            // Execute and gather program data
            ProtoCore.CompileAndExecutePass.ProgramData programData = null;
            bool compileAndExecuteSuceeded = CompileAndExecutePass(filename, out programData);

            Validity.Assert(compileAndExecuteSuceeded == true);
            Validity.Assert(programData != null);

            ProtoCore.Options options = new ProtoCore.Options();
            options.CompilationTarget = ProtoCore.DSDefinitions.CompileTarget.VHDL;

            // Generate a new core and pass it the data gathered from the previous pass
            ProtoCore.Core core = new ProtoCore.Core(options);
            core.SetProgramData(programData);

            options.ExecutionMode = ProtoCore.ExecutionMode.Serial;
            core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core));
            core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core));
            core.Executives.Add(ProtoCore.Language.kVHDL, new ProtoVHDL.Executive(core));
            core.Options.DumpByteCode = true;
            core.Options.Verbose      = true;

            core.VhdlCore = new ProtoCore.VHDL.VHDLCore(topLevelModule);

            System.IO.StreamReader reader = null;
            try
            {
                reader = new System.IO.StreamReader(filename, Encoding.UTF8, true);
            }
            catch (System.IO.IOException)
            {
                throw new Exception("Cannot open file " + filename);
            }

            string strSource = reader.ReadToEnd();

            reader.Dispose();

            core.Options.RootModulePathName = ProtoCore.Utils.FileUtils.GetFullPathName(filename);
            core.CurrentDSFileName          = core.Options.RootModulePathName;
            core.ExecMode = ProtoCore.DSASM.InterpreterMode.kNormal;

            bool buildSucceeded = false;

            try
            {
                //defining the global Assoc block that wraps the entire .ds source file
                ProtoCore.LanguageCodeBlock globalBlock = new ProtoCore.LanguageCodeBlock();
                globalBlock.language = ProtoCore.Language.kVHDL;
                globalBlock.body     = strSource;

                //the wrapper block can be given a unique id to identify it as the global scope
                globalBlock.id = ProtoCore.LanguageCodeBlock.OUTERMOST_BLOCK_ID;

                //passing the global Assoc wrapper block to the compiler
                ProtoCore.CompileTime.Context context = new ProtoCore.CompileTime.Context();
                ProtoCore.Language            id      = globalBlock.language;
                int blockID = 0;
                core.Executives[id].Compile(out blockID, null, globalBlock, context);

                core.BuildStatus.ReportBuildResult();
                buildSucceeded = core.BuildStatus.BuildSucceeded;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            return(buildSucceeded);
        }
Пример #30
0
        public bool RunScript(string dsPath)
        {
            if (string.IsNullOrEmpty(GeometryFactoryName))
                throw new Exception("GeometryFactory not set!");

            if (string.IsNullOrEmpty(PersistenceManagerName))
                throw new Exception("PersistenceManager not set!");

            if (!File.Exists(dsPath))
                throw new FileNotFoundException(dsPath + " Does not exist");

            bool success = false;
            System.IO.StringWriter stringStream = new StringWriter();
            executionLog = new StringBuilder();
            ProtoCore.Core core = null;
            try
            {
                var options = new ProtoCore.Options();
                string assemblyLocation = System.Reflection.Assembly.GetExecutingAssembly().Location;
                string incDir = Path.GetDirectoryName(assemblyLocation);
                options.IncludeDirectories.Add(incDir);

                core = new ProtoCore.Core(options);
                core.BuildStatus.SetStream(stringStream);
                core.Options.RootModulePathName = ProtoCore.Utils.FileUtils.GetFullPathName(dsPath);
                core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core));
                core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core));
                core.Configurations.Add(Autodesk.DesignScript.Interfaces.ConfigurationKeys.GeometryFactory, GeometryFactoryName);
                core.Configurations.Add(Autodesk.DesignScript.Interfaces.ConfigurationKeys.PersistentManager, PersistenceManagerName);
                ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner();
                ExecutionMirror mirror = fsr.LoadAndExecute(dsPath, core);
                executionLog.AppendLine("Script executed successfully.");

                executionLog.AppendLine();
                executionLog.AppendLine("=================================CoreDump=================================");
                string coreDump = null;
                try
                {
                    coreDump = mirror.GetCoreDump();
                    executionLog.AppendLine();
                    executionLog.AppendLine(coreDump);
                    success = true;
                }
                catch (System.Exception ex)
                {
                    executionLog.AppendLine(ex.Message);
                    executionLog.AppendLine(ex.StackTrace);

                    success = false;
                }
                finally
                {
                    executionLog.AppendLine("=================================CoreDump=================================");
                }
                
            }
            catch (System.Exception ex)
            {
                success = false;
                executionLog.AppendLine("Fail to execute script.");
                executionLog.AppendLine("Exceptions:");
                executionLog.AppendLine(ex.Message);
                executionLog.AppendLine("StackTrace:");
                executionLog.AppendLine(ex.StackTrace);
            }
            finally
            {
                if (core != null)
                {
                    core.BuildStatus.SetStream(null);
                    core.Cleanup();
                }
            }

            return success;
        }
Пример #31
0
using System;
Пример #32
0
        public static List<SnapshotNode> NodeToCodeBlocks(List<SnapshotNode> inputs, GraphToDSCompiler.GraphCompiler originalGC)
        {
            List<SnapshotNode> codeBlocks = new List<SnapshotNode>();
            GraphToDSCompiler.GraphCompiler newGC = GraphCompiler.CreateInstance();

            newGC.SetCore(core);
            GraphToDSCompiler.SynchronizeData newSyncData = new SynchronizeData();
            newSyncData.AddedNodes = inputs;
            newSyncData.ModifiedNodes = new List<SnapshotNode>();
            newSyncData.RemovedNodes = new List<uint>();
            GraphToDSCompiler.GraphBuilder GB = new GraphBuilder(newSyncData, newGC);

            #region fix connection for multi-line CBN
            /*for multi-line code blocks*/
            List<Node> completeList = originalGC.Graph.nodeList;
            List<uint> originalNodeUIDList = new List<uint>();
            foreach (Node oriGcNode in completeList)
            {
                originalNodeUIDList.Add(oriGcNode.Guid);
            }

            GB.AddNodesToAST();

            //List<SnapshotNode> inputsCopy = new List<SnapshotNode>(inputs);
            for (int i = 0; i < inputs.Count; i++)
            {
                SnapshotNode inputSnapshotNode = inputs[i];
                for (int j = 0; j < inputSnapshotNode.InputList.Count; j++)
                {
                    Connection inputConnection = inputSnapshotNode.InputList[j];
                    if (!originalNodeUIDList.Contains(inputConnection.OtherNode))
                    {
                        Connection correctedInputConnection = new Connection();
                        correctedInputConnection.LocalName = inputConnection.LocalName;
                        correctedInputConnection.LocalIndex = inputConnection.LocalIndex;
                        correctedInputConnection.IsImplicit = inputConnection.IsImplicit;
                        correctedInputConnection.OtherIndex = inputConnection.OtherIndex;
                        if (newGC.codeBlockUIDMap.ContainsKey(inputConnection.OtherNode))
                        {
                            correctedInputConnection.OtherNode = newGC.codeBlockUIDMap[inputConnection.OtherNode][inputConnection.OtherIndex];
                        }
                        else
                        {
                            correctedInputConnection.OtherNode = originalGC.codeBlockUIDMap[inputConnection.OtherNode][inputConnection.OtherIndex];
                        }
                        inputSnapshotNode.InputList.Remove(inputConnection);
                        inputSnapshotNode.InputList.Insert(j, correctedInputConnection);
                    }
                }
                for (int j = 0; j < inputSnapshotNode.OutputList.Count; j++)
                {
                    Connection outputConnection = inputSnapshotNode.OutputList[j];
                    if (!originalNodeUIDList.Contains(outputConnection.OtherNode))                       // if the other node is split
                    {
                        Connection correctedInputConnection = new Connection();
                        correctedInputConnection.LocalName = outputConnection.LocalName;
                        correctedInputConnection.LocalIndex = outputConnection.LocalIndex;
                        correctedInputConnection.IsImplicit = outputConnection.IsImplicit;
                        correctedInputConnection.OtherIndex = outputConnection.OtherIndex;
                        if (newGC.codeBlockUIDMap.ContainsKey(outputConnection.OtherNode))
                        {
                            correctedInputConnection.OtherNode = newGC.GetUidOfRHSIdentifierInCodeBlock(
                                outputConnection.OtherNode, outputConnection.OtherIndex, outputConnection.LocalName);
                            //correctedInputConnection.OtherNode = newGC.codeBlockUIDMap[outputConnection.OtherNode][outputConnection.OtherIndex];
                        }
                        else
                        {
                            correctedInputConnection.OtherNode = originalGC.codeBlockUIDMap[outputConnection.OtherNode][outputConnection.OtherIndex];
                        }
                        inputSnapshotNode.OutputList.Remove(outputConnection);
                        inputSnapshotNode.OutputList.Insert(j, correctedInputConnection);
                    }
                }
            }
            GB.nodesToAdd = inputs;
            GB.MakeConnectionsForAddedNodes_NodeToCode(GB.nodesToAdd);
            newGC.PrintGraph();
            #endregion

            //GB.BuildGraphForCodeBlock();

            List<uint> nodesToBeAdded = new List<uint>();
            List<Node> nodesToBeReplaced = new List<Node>();

            //adding children node from the originalGC to the newGC needed for the newGC to generate code
            foreach (Node n in completeList)
            {
                foreach (Node child in n.GetChildren())
                {
                    if (newGC.Graph.GetNode(child.Guid) != null)
                    {
                        if (child.Name != newGC.Graph.GetNode(child.Guid).Name)
                        {
                            nodesToBeReplaced.Add(child);
                        }
                    }
                }
            }

            foreach (uint n in nodesToBeAdded)
            {
                Node n1 = completeList.FirstOrDefault(q => q.Guid == n);
                //n1.children.Clear();
                nodesToBeReplaced.Add(n1);
                //newSyncData.RemovedNodes.Add(n);
            }

            List<uint> nodeToCodeUIDs = new List<uint>();
            foreach (SnapshotNode ssn in inputs)
                nodeToCodeUIDs.Add(ssn.Id);
            newGC.nodeToCodeUIDs = nodeToCodeUIDs;

            /*create output snapshot nodes*/
            List<Connection> inputNodeInputConnections = new List<Connection>();
            List<Connection> inputNodeOutputConnections = new List<Connection>();
            foreach (SnapshotNode ssn in inputs)
            {
                foreach (Connection inputConnection in ssn.InputList)
                {
                    if (!nodeToCodeUIDs.Contains(inputConnection.OtherNode))
                        inputNodeInputConnections.Add(inputConnection);
                }
                foreach (Connection outputConnection in ssn.OutputList)
                {
                    if (!nodeToCodeUIDs.Contains(outputConnection.OtherNode))
                        inputNodeOutputConnections.Add(outputConnection);
                }
            }

            newGC.ReplaceNodesFromAList(nodesToBeReplaced);
            newSyncData.AddedNodes = new List<SnapshotNode>();
            newSyncData.ModifiedNodes = new List<SnapshotNode>();
            newSyncData.RemovedNodes = new List<uint>();
            GB = new GraphBuilder(newSyncData, newGC);
            //string result = GB.BuildGraphDAG();
            List<SnapshotNode> nodeToCodeBlocks = GB.PrintCodeForSelectedNodes(originalGC, inputs);

            /*for now, only connected nodes are supported: return all connections that are not internal connections (connections between the selected nodes)*/
            //uint id = 0;
            //foreach (string content in toCode)
            //{
            //    SnapshotNode ssn = new SnapshotNode();
            //    ssn.Type = SnapshotNodeType.CodeBlock;
            //    ssn.Content = content;
            //    ssn.Id = id++;
            //    ssn.InputList = new List<Connection>();
            //    //stupid stub
            //    foreach (Connection inputConnection in inputNodeInputConnections)
            //    {
            //        Connection newInputConnection = new Connection();
            //        newInputConnection.OtherNode = inputConnection.OtherNode;
            //        newInputConnection.OtherIndex = inputConnection.OtherIndex;
            //        newInputConnection.IsImplicit = inputConnection.IsImplicit;
            //        string[] tokens = newGC.Graph.GetNode(inputConnection.OtherNode).Name.Split('=');
            //        newInputConnection.LocalName = tokens[0];
            //        ssn.InputList.Add(newInputConnection);
            //    }
            //    //ssn.InputList = inputNodeInputConnections;
            //    ssn.OutputList = new List<Connection>();
            //    foreach (Connection outputConnection in inputNodeOutputConnections)
            //    {
            //        Connection newOutputConnection = new Connection();
            //        newOutputConnection.OtherNode = outputConnection.OtherNode;
            //        newOutputConnection.OtherIndex = outputConnection.OtherIndex;
            //        newOutputConnection.IsImplicit = outputConnection.IsImplicit;
            //        //string[] tokens = originalGC.Graph.GetNode(outputConnection.OtherNode).Name.Split('=');
            //        newOutputConnection.LocalName = outputConnection.LocalName;
            //        ssn.OutputList.Add(newOutputConnection);
            //    }
            //    //ssn.OutputList = inputNodeOutputConnections;
            //    codeBlocks.Add(ssn);
            //}

            /*update the original GC*/
            foreach (SnapshotNode inputNode in inputs)
            {
                if (originalNodeUIDList.Contains(inputNode.Id))
                    originalGC.RemoveNodes(inputNode.Id, false);
                else
                {
                    foreach (KeyValuePair<uint, Dictionary<int, uint>> kvp in originalGC.codeBlockUIDMap)
                    {
                        if (kvp.Value.ContainsValue(inputNode.Id))
                        {
                            originalGC.RemoveNodes(kvp.Key, false);
                        }
                    }
                }
            }
            foreach (Node node in newGC.Graph.nodeList)
            {
                node.Name = node.Name.TrimEnd(';') + ";";
            }
            originalGC.Graph.nodeList.Union<Node>(newGC.Graph.nodeList);
            //originalGC = newGC;
            /**/

            return nodeToCodeBlocks;
            //return codeBlocks;
        }

        /// <summary>
        /// This is called to Parse individual assignment statements in Codeblock nodes in GraphUI
        /// and return the resulting ProtoAST node
        /// </summary>
        /// <param name="statement"></param>
        public static ProtoCore.AST.Node Parse(string statement, out ProtoCore.AST.AssociativeAST.CodeBlockNode commentNode)
        {
            commentNode = null;
            BuildCore(true);

            Validity.Assert(core != null);
            Validity.Assert(statement != null);

            if (string.IsNullOrEmpty(statement))
                return null;

            System.IO.MemoryStream memstream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(statement));
            ProtoCore.DesignScriptParser.Scanner s = new ProtoCore.DesignScriptParser.Scanner(memstream);
            ProtoCore.DesignScriptParser.Parser p = new ProtoCore.DesignScriptParser.Parser(s, core);

            p.Parse();
            commentNode = p.commentNode;

            return p.root;
        }

        public static bool Parse(Guid nodeGUID, ref string code, 
                                 out List<ProtoCore.AST.Node> parsedNodes, 
                                 out IEnumerable<ProtoCore.BuildData.ErrorEntry> errors,
                                 out IEnumerable<ProtoCore.BuildData.WarningEntry> warnings, 
                                 List<String> unboundIdentifiers, 
                                 out List<String> tempIdentifiers)
        {
            tempIdentifiers = new List<string>();

            List<String> compiledCode = new List<String>();
            parsedNodes = null;
            //-----------------------------------------------------------------------------------
            //--------------------------------Correct the code-----------------------------------
            //-----------------------------------------------------------------------------------
            // Use the compile expression to format the code by adding the required %t temp vars
            // needed for non assignment statements
            CompileExpression(code, out compiledCode);

            string codeToParse = "";
            for (int i = 0; i < compiledCode.Count; i++)
            {
                string tempVariableName = string.Format("temp_{0}_", i) + nodeGUID.ToString().Replace("-", "_");
                tempIdentifiers.Add(tempVariableName);

                string singleExpression = compiledCode[i];
                singleExpression = singleExpression.Replace("%t", tempVariableName);
                codeToParse += singleExpression;
            }

            code = codeToParse;

            //Catch the errors thrown by compile expression, namely function modiferstack and class decl found
            if (core.BuildStatus.ErrorCount > 0)
            {
                errors = core.BuildStatus.Errors;
                warnings = core.BuildStatus.Warnings;
                parsedNodes = null;
                return false;
            }

            // Parse and compile the code to get the result AST nodes as well as
            // any errors or warnings that were caught by the comiler
            ProtoCore.BuildStatus buildStatus;
            var tempUnboundIdentifiers = new Dictionary<int, List<VariableLine>>();
            List<ProtoCore.AST.Node> nodeList = new List<ProtoCore.AST.Node>();

            ParseCodeBlockNodeStatements(codeToParse, out tempUnboundIdentifiers, out nodeList, out buildStatus);
            errors = buildStatus.Errors;
            warnings = buildStatus.Warnings;

            //Get the unboundIdentifiers from the warnings
            foreach (KeyValuePair<int, List<VariableLine>> kvp in tempUnboundIdentifiers)
            {
                foreach (VariableLine vl in kvp.Value)
                {
                    if (!unboundIdentifiers.Contains(vl.variable))
                    {
                        unboundIdentifiers.Add(vl.variable);
                    }
                }
            }

            // Assign the 'out' variables
            // Use the parse function to get the parsed nodes to return to the
            // user
            if (nodeList != null)
            {
                parsedNodes = new List<ProtoCore.AST.Node>();
                ProtoCore.AST.AssociativeAST.CodeBlockNode cNode;
                parsedNodes = ParserUtils.GetAstNodes(Parse(codeToParse, out cNode));
            }
            else
            {
                parsedNodes = null;
            }

            return true;
        }

        public static List<ProtoCore.AST.Node> ParseCodeBlock(string code)
        {
            Validity.Assert(code != null);

            if (string.IsNullOrEmpty(code))
                return null;

            // TODO: Change the logic to ignore Import statements in this case using parser - pratapa
            // Check if this will work with modifier blocks as well
            /*string[] stmts = code.Split(';');
            string source = "";
            for (int i=0; i < stmts.Length; ++i)
            {
                if (!stmts[i].Contains("import"))
                    source += stmts[i] + ";";
            }*/

            ProtoCore.Options options = new ProtoCore.Options();
            ProtoCore.Core core = new ProtoCore.Core(options);
            core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core));
            core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core));

            System.IO.MemoryStream memstream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(code));
            ProtoCore.DesignScriptParser.Scanner s = new ProtoCore.DesignScriptParser.Scanner(memstream);
            ProtoCore.DesignScriptParser.Parser p = new ProtoCore.DesignScriptParser.Parser(s, core);

            p.Parse();
            ProtoCore.AST.AssociativeAST.CodeBlockNode cbn = p.root as ProtoCore.AST.AssociativeAST.CodeBlockNode;

            Validity.Assert(cbn != null);
            return p.GetParsedASTList(cbn);
        }
Пример #33
0
        private static bool LocateAssembly(string assembly, out string assemblyPath)
        {
            ProtoCore.Options options = null;
            if (null == core)
                options = new ProtoCore.Options() { RootModulePathName = GraphUtilities.rootModulePath };
            else
                options = core.Options;

            assemblyPath = FileUtils.GetDSFullPathName(assembly, options);
            string dirName = Path.GetDirectoryName(assemblyPath);
            if(!string.IsNullOrEmpty(dirName) && !core.Options.IncludeDirectories.Contains(dirName))
                core.Options.IncludeDirectories.Add(dirName);

            return File.Exists(assemblyPath);
        }
Пример #34
0
        private static void BuildCore(bool isCodeBlockNode = false, bool isPreloadedAssembly = false)
        {
            // Reuse the core for every succeeding run
            // TODO Jun: Check with UI - what instances need a new core and what needs reuse
            if (core == null || resetCore)
            {
                resetCore = false;
                ProtoCore.Options options = new ProtoCore.Options();
                options.RootModulePathName = rootModulePath;
                core = new ProtoCore.Core(options);
                core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core));
                core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core));

            }
            else
            {
                //core.ResetDeltaExecution();
                core.ResetForPrecompilation();

            }
            core.IsParsingPreloadedAssembly = isPreloadedAssembly;
            core.IsParsingCodeBlockNode = isCodeBlockNode;
            core.ParsingMode = ProtoCore.ParseMode.AllowNonAssignment;
        }
Пример #35
0
        public bool RunScript(string dsPath)
        {
            if (string.IsNullOrEmpty(GeometryFactoryName))
            {
                throw new Exception("GeometryFactory not set!");
            }

            if (string.IsNullOrEmpty(PersistenceManagerName))
            {
                throw new Exception("PersistenceManager not set!");
            }

            if (!File.Exists(dsPath))
            {
                throw new FileNotFoundException(dsPath + " Does not exist");
            }

            bool success = false;

            System.IO.StringWriter stringStream = new StringWriter();
            executionLog = new StringBuilder();
            ProtoCore.Core        core        = null;
            ProtoCore.RuntimeCore runtimeCore = null;
            try
            {
                var    options          = new ProtoCore.Options();
                string assemblyLocation = System.Reflection.Assembly.GetExecutingAssembly().Location;
                string incDir           = Path.GetDirectoryName(assemblyLocation);
                options.IncludeDirectories.Add(incDir);

                core = new ProtoCore.Core(options);
                core.BuildStatus.SetStream(stringStream);
                core.Options.RootModulePathName = ProtoCore.Utils.FileUtils.GetFullPathName(dsPath);
                core.Compilers.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Compiler(core));
                core.Compilers.Add(ProtoCore.Language.kImperative, new ProtoImperative.Compiler(core));

                core.Configurations.Add(Autodesk.DesignScript.Interfaces.ConfigurationKeys.GeometryFactory, GeometryFactoryName);
                core.Configurations.Add(Autodesk.DesignScript.Interfaces.ConfigurationKeys.PersistentManager, PersistenceManagerName);
                ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner();

                ExecutionMirror mirror = fsr.LoadAndExecute(dsPath, core, out runtimeCore);
                executionLog.AppendLine("Script executed successfully.");

                executionLog.AppendLine();
                executionLog.AppendLine("=================================CoreDump=================================");
                string coreDump = null;
                try
                {
                    coreDump = mirror.GetCoreDump();
                    executionLog.AppendLine();
                    executionLog.AppendLine(coreDump);
                    success = true;
                }
                catch (System.Exception ex)
                {
                    executionLog.AppendLine(ex.Message);
                    executionLog.AppendLine(ex.StackTrace);

                    success = false;
                }
                finally
                {
                    executionLog.AppendLine("=================================CoreDump=================================");
                }
            }
            catch (System.Exception ex)
            {
                success = false;
                executionLog.AppendLine("Fail to execute script.");
                executionLog.AppendLine("Exceptions:");
                executionLog.AppendLine(ex.Message);
                executionLog.AppendLine("StackTrace:");
                executionLog.AppendLine(ex.StackTrace);
            }
            finally
            {
                if (core != null)
                {
                    core.BuildStatus.SetStream(null);
                    runtimeCore.Cleanup();
                }
            }

            return(success);
        }
Пример #36
0
        /*
        proc RewriteCodeBlock(Node codeblock)
		
		    // Create new codeblocks for every line of code in the current codeblock CodeBlock[] newBlockList = new CodeBlock[node.lines.length]
            for n = 0 to node.lines.length
	            newBlockList[n].code = node.lines[n]
	            newBlockList[n].uid = generateUID(codeblock.uid)
            end
		
		    // At this point, determine which parents of the current codeblock node need to be connected to each splitted node

		    // Iterate through each parent of the current code block
		    foreach parentNode in codeblock.parents 

			    // Iterate through each child of the parent
			    for n = 0 to parentNode.children.length
			
				    // Check if the child is this codeblock
				    if parentNode.children[n] is equal to codeblock

                        // index ‘n’ is the current output slot of the codeblock		
                        newBlockList[n].parent.push(parentNode)

					    // Rewire the parent’s child to this new codeblock
					    parentNode.children[n] = newBlockList[n]

				    end
				    n++;
			    end
		    end			
        end

         */


        /*private List<Block> RewriteCodeBlock(Block codeblock)
        {
            Validity.Assert(codeblock != null);

            if (codeblock.Name == null || codeblock.Name.Length <= 0)
            {
                return null;
            }


            // Comment Jun: Im just trying to find the number of times ';' occurs
            // Make this more efficient by turning this into a function in a utils class
            string dummy = codeblock.Name.Replace(";", "");
            if ((codeblock.Name.Length - dummy.Length) <= 1)
            {
                // Single line codeblocks need not be split
                return null;
            }

            string[] token = new string[1];
            token[0] = ProtoCore.DSASM.Constants.termline;
            StringSplitOptions opt = new StringSplitOptions();
            string[] contents = codeblock.Name.Split(token, opt);
            int length = contents.Length;


            // The map of the new uid and its associated connecting slot
            Dictionary<int, uint> slotIndexToUIDMap = new Dictionary<int, uint>();

            // Create new codeblocks for every line of code in the current codeblock CodeBlock[] newBlockList = new CodeBlock[node.lines.length]
            List<Block> newBlockList = new List<Block>();
            for (int n = 0; n < length; n++)
            {
                // TODO Jun: Check with IDE why the semicolon is inconsitent
                string code = contents[n];
                if (code.Length > 0 && code[0] != ';')
                {
                    uint newGuid = GraphUtilities.GenerateUID();

                    List<AssignmentStatement> assignmentData = new List<AssignmentStatement>();
                    if (codeblock.assignmentData.Count > 0)
                    {
                        // This assignemnt data list must contain only 1 element
                        // This element is associated witht he current line in the codeblock
                        assignmentData.Add(codeblock.assignmentData[n]);
                    }
                    
                    Block newBlock = new Block(code, newGuid, assignmentData);
                    newBlock.splitFomUint = codeblock.Guid;
                    newBlockList.Add(newBlock);
                    slotIndexToUIDMap.Add(n, newGuid);
                }
            }

            // At this point, determine which parents of the current codeblock node need to be connected to each splitted node

            // Iterate through each parent of the current code block
            List<Node> parents = codeblock.GetParents();
            foreach (Node parentNode in parents)
            {
                // Iterate through each child of the parent
                for (int childIndex = 0; childIndex < parentNode.children.Count; childIndex++)
                {
                    Node child = null;
                    bool foundIndex = parentNode.children.TryGetValue(childIndex, out child);

                    if (foundIndex)
                    {
                        // Check if the child is this codeblock
                        if (child.Guid == codeblock.Guid)
                        {
                            int fromIndex = parentNode.childConnections[childIndex].from;

                            // Set the new codeblock's parent
                            newBlockList[fromIndex].AddParent(parentNode);

                            // Rewire the parent’s child to this new codeblock
                            parentNode.RemoveChild(childIndex);

                            parentNode.AddChild(newBlockList[fromIndex], childIndex, fromIndex);
                        }
                    }
                }
            }
            if (codeBlockUIDMap.ContainsKey(codeblock.Guid))
            {
                codeBlockUIDMap[codeblock.Guid] = slotIndexToUIDMap;
            }
            else
            {
                codeBlockUIDMap.Add(codeblock.Guid, slotIndexToUIDMap);
            }
            return newBlockList;
        }*/

        private List<ProtoCore.AST.Node> ParseCodeBlock(string code)
        {
            Validity.Assert(code != null);

            if (string.IsNullOrEmpty(code))
                return null;

            ProtoCore.Options options = new ProtoCore.Options();
            ProtoCore.Core core = new ProtoCore.Core(options);
            core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core));
            core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core));

            System.IO.MemoryStream memstream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(code));
            ProtoCore.DesignScriptParser.Scanner s = new ProtoCore.DesignScriptParser.Scanner(memstream);
            ProtoCore.DesignScriptParser.Parser p = new ProtoCore.DesignScriptParser.Parser(s, core);

            p.Parse();
            ProtoCore.AST.AssociativeAST.CodeBlockNode cbn = p.root as ProtoCore.AST.AssociativeAST.CodeBlockNode;

            Validity.Assert(cbn != null);
            return p.GetParsedASTList(cbn);
        }
Пример #37
0
        public void Setup()
        {
            // Specify some of the requirements of IDE.
            var options = new ProtoCore.Options();
            options.ExecutionMode = ProtoCore.ExecutionMode.Serial;

            core = new ProtoCore.Core(options);
            core.Compilers.Add(ProtoCore.Language.Associative, new ProtoAssociative.Compiler(core));
            core.Compilers.Add(ProtoCore.Language.Imperative, new ProtoImperative.Compiler(core));

            fsr = new DebugRunner(core);

            DLLFFIHandler.Register(FFILanguage.CSharp, new CSModuleHelper());
            CLRModuleType.ClearTypes();
        }
Пример #38
0
        public static List<ProtoCore.AST.Node> ParseCodeBlock(string code)
        {
            Validity.Assert(code != null);

            if (string.IsNullOrEmpty(code))
                return null;

            // TODO: Change the logic to ignore Import statements in this case using parser - pratapa
            // Check if this will work with modifier blocks as well
            /*string[] stmts = code.Split(';');
            string source = "";
            for (int i=0; i < stmts.Length; ++i)
            {
                if (!stmts[i].Contains("import"))
                    source += stmts[i] + ";";
            }*/


            ProtoCore.Options options = new ProtoCore.Options();
            ProtoCore.Core core = new ProtoCore.Core(options);
            core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core));
            core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core));

            System.IO.MemoryStream memstream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(code));
            ProtoCore.DesignScriptParser.Scanner s = new ProtoCore.DesignScriptParser.Scanner(memstream);
            ProtoCore.DesignScriptParser.Parser p = new ProtoCore.DesignScriptParser.Parser(s, core);

            p.Parse();
            ProtoCore.AST.AssociativeAST.CodeBlockNode cbn = p.root as ProtoCore.AST.AssociativeAST.CodeBlockNode;

            Validity.Assert(cbn != null);
            return p.GetParsedASTList(cbn);
        }