Esempio n. 1
0
 public void PublishError(PluginLib.CompileError error)
 {
     IDEView.inst().Dispatcher.Invoke(delegate()
     {
         CompileErrors.Add(error);
     });
 }
        private bool Compile(out PcodeRec FuncCode, out DataTypes ReturnType)
        {
            int LineNumber;

            Compiler.ASTExpression AST;
            CompileErrors          Error = Compiler.CompileSpecialFunction(
                document.CodeCenter,
                new FunctionParamRec[0] /*no arguments*/,
                out LineNumber,
                out ReturnType,
                textBox.SelectedTextStorage.GetText(Environment.NewLine),
                false /*suppressCILEmission*/,
                out FuncCode,
                out AST);

            if (Error != CompileErrors.eCompileNoError)
            {
                textBox.Focus();
                textBox.SetSelectionLine(textBox.SelectionStartLine + LineNumber - 1);
                textBox.ScrollToSelection();
                BuildErrorInfo error = new LiteralBuildErrorInfo(
                    Compiler.GetCompileErrorString(Error),
                    LineNumber);
                MessageBox.Show(error.CompositeErrorMessage, "Compile Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return(false);
            }
            return(true);
        }
        private void HandleAddingDynamicallyCompiledPlugin(AggregateCatalog returnValue, string plugin, CompilerResults compileResult)
        {
            if (compileResult.Errors != null && compileResult.Errors.HasErrors)
            {
                var errors   = new StringBuilder();
                var filename = Path.GetFileName(plugin);
                foreach (CompilerError err in compileResult.Errors)
                {
                    errors.Append(string.Format("\r\n{0}({1},{2}): {3}: {4}",
                                                filename, err.Line, err.Column,
                                                err.ErrorNumber, err.ErrorText));
                }
                CompileErrors.Add("Error loading script " + plugin + "\r\n" + errors.ToString());
            }
            else
            {
                var newCatalog = new AssemblyCatalog(compileResult.CompiledAssembly);


                returnValue.Catalogs.Add(newCatalog);

                //foreach (string assm in mReferenceListExternal)
                //{
                //    Assembly ass = Assembly.LoadFrom(assm);
                //    var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic).Select(a => a.Location);

                //    returnValue.Catalogs.Add(newCatalog);
                //}
            }
        }
Esempio n. 4
0
        public WaveTableStorageRec WaveTableData; // null = needs to be built


        // Exposed separately to support Disassemble menu item
        public bool BuildCode(BuildFailedCallback failedCallback, out PcodeRec FuncCode)
        {
            int       ErrorLineNumberCompilation;
            DataTypes ReturnType;

            Compiler.ASTExpression AST;
            CompileErrors          CompileError = Compiler.CompileSpecialFunction(
                ((Document)Parent).CodeCenter,
                new FunctionParamRec[]
            {
                new FunctionParamRec("frames", DataTypes.eInteger),
                new FunctionParamRec("tables", DataTypes.eInteger),
                new FunctionParamRec("data", DataTypes.eArrayOfFloat),
            },
                out ErrorLineNumberCompilation,
                out ReturnType,
                AlgoWaveTableFormula,
                false /*suppressCILEmission*/,
                out FuncCode,
                out AST);

            if (CompileError != CompileErrors.eCompileNoError)
            {
                failedCallback(this, new LiteralBuildErrorInfo(Compiler.GetCompileErrorString(CompileError), ErrorLineNumberCompilation));
                return(false);
            }

            return(true);
        }
Esempio n. 5
0
        // Compile functions to find errors. Does not do a full build - compiles only this module and does
        // not check function arg/return types for references to other modules.
        public bool TestBuild(
            bool force,
            PcodeSystem.IEvaluationContext pcodeEnvironment,
            BuildFailedCallback failedCallback,
            CodeCenterRec throwAwayCodeCenter)
        {
            int           ErrorLine;
            int           ErrorModuleIndex;
            CompileErrors Error = Compiler.CompileWholeProgram(
                out ErrorLine,
                out ErrorModuleIndex,
                new string[] { this.Source },
                new object[] { this },
                throwAwayCodeCenter, // use throw-away linker to not pollute the real one with unchecked function calls
                new string[] { this.Name });

            if ((Error != CompileErrors.eCompileNoError)
                // these errors are permitted for test-build because without full function signatures known there will be
                // arg-type inference ambiguities.
                && (Error != CompileErrors.eCompileMultiplyDeclaredFunction))
            {
                failedCallback(
                    this,
                    new LiteralBuildErrorInfo(Compiler.GetCompileErrorString(Error), ErrorLine));
                return(false);
            }
            return(true);
        }
Esempio n. 6
0
 public void PublishWarning(PluginLib.CompileError error)
 {
     IDEView.inst().Dispatcher.Invoke(delegate()
     {
         CompileErrors.Add(error);
         OnPropertyChanged("CompileErrorCt");
         OnPropertyChanged("CompileWarningCt");
     });
 }
Esempio n. 7
0
        public SampleStorageActualRec SampleData; // null = needs to be built


        // Exposed separately to support Disassemble menu item
        public bool BuildCode(BuildFailedCallback failedCallback, out PcodeRec FuncCode)
        {
            int       ErrorLineNumberCompilation;
            DataTypes ReturnType;

            Compiler.ASTExpression AST;
            CompileErrors          CompileError = Compiler.CompileSpecialFunction(
                ((Document)Parent).CodeCenter,
                NumChannels == NumChannelsType.eSampleStereo
                ? new FunctionParamRec[]
            {
                new FunctionParamRec("loopstart1", DataTypes.eInteger),
                new FunctionParamRec("loopstart2", DataTypes.eInteger),
                new FunctionParamRec("loopstart3", DataTypes.eInteger),
                new FunctionParamRec("loopend1", DataTypes.eInteger),
                new FunctionParamRec("loopend2", DataTypes.eInteger),
                new FunctionParamRec("loopend3", DataTypes.eInteger),
                new FunctionParamRec("origin", DataTypes.eInteger),
                new FunctionParamRec("samplingrate", DataTypes.eInteger),
                new FunctionParamRec("naturalfrequency", DataTypes.eDouble),
                new FunctionParamRec("leftdata", DataTypes.eArrayOfFloat),
                new FunctionParamRec("rightdata", DataTypes.eArrayOfFloat),
            }
                : new FunctionParamRec[]
            {
                new FunctionParamRec("loopstart1", DataTypes.eInteger),
                new FunctionParamRec("loopstart2", DataTypes.eInteger),
                new FunctionParamRec("loopstart3", DataTypes.eInteger),
                new FunctionParamRec("loopend1", DataTypes.eInteger),
                new FunctionParamRec("loopend2", DataTypes.eInteger),
                new FunctionParamRec("loopend3", DataTypes.eInteger),
                new FunctionParamRec("origin", DataTypes.eInteger),
                new FunctionParamRec("samplingrate", DataTypes.eInteger),
                new FunctionParamRec("naturalfrequency", DataTypes.eDouble),
                new FunctionParamRec("data", DataTypes.eArrayOfFloat),
            },
                out ErrorLineNumberCompilation,
                out ReturnType,
                AlgoSampFormula,
                false /*suppressCILEmission*/,
                out FuncCode,
                out AST);

            if (CompileError != CompileErrors.eCompileNoError)
            {
                failedCallback(this, new LiteralBuildErrorInfo(Compiler.GetCompileErrorString(CompileError), ErrorLineNumberCompilation));
                return(false);
            }

            return(true);
        }
Esempio n. 8
0
        public override bool EnsureBuilt(
            bool force,
            PcodeSystem.IEvaluationContext pcodeEnvironment,
            BuildFailedCallback failedCallback)
        {
            if (!force && Built)
            {
                return(true);
            }

            List <string> sources    = new List <string>();
            List <string> filenames  = new List <string>();
            List <object> signatures = new List <object>();

            for (int i = 0; i < functionList.Count; i++)
            {
                sources.Add(functionList[i].Source);
                filenames.Add(functionList[i].Name);
                signatures.Add(functionList[i]);

                functionList[i].Unbuild1();
            }

            int           ErrorLine;
            int           ErrorModuleIndex;
            CompileErrors Error = Compiler.CompileWholeProgram(
                out ErrorLine,
                out ErrorModuleIndex,
                sources.ToArray(),
                signatures.ToArray(),
                CodeCenter,
                filenames.ToArray());

            if (Error != CompileErrors.eCompileNoError)
            {
                failedCallback(
                    (FunctionObjectRec)signatures[ErrorModuleIndex],
                    new LiteralBuildErrorInfo(Compiler.GetCompileErrorString(Error), ErrorLine));
                return(false);
            }

            for (int i = 0; i < functionList.Count; i++)
            {
                functionList[i].Built1 = true;
            }

            return(true);
        }
Esempio n. 9
0
        /* return a null terminated static string describing the error. */
        public static string GetCompileErrorString(CompileErrors Error)
        {
#if DEBUG
            /* verify structure */
            for (int i = 0; i < Errors.Length; i += 1)
            {
                if (Errors[i].ErrorCode != i + CompileErrors.eCompileNoError)
                {
                    Debug.Assert(false);
                    throw new InvalidOperationException();
                }
            }
#endif

            /* direct index error string */
            return(Errors[Error - CompileErrors.eCompileNoError].Message);
        }
        private void AddPluginsFromDirectory(List <string> pluginsToIgnore, AggregateCatalog returnValue, string plugin)
        {
            try
            {
                bool shouldProcessPlugin = true;
                // GlueView is a special case, so we should skip that
                string pluginToLower = plugin.ToLower().Replace("\\", "/");
                if (pluginToLower.EndsWith("/glueview") || pluginToLower.EndsWith("/glueview/"))
                {
                    shouldProcessPlugin = false;
                }

                if (shouldProcessPlugin)
                {
                    var compileResult = CompilePlugin(plugin);

                    // We had a && false here, so I don't think we use this ignored check, do we?
                    bool isIgnored = pluginsToIgnore != null && pluginsToIgnore.Any(item =>
                                                                                    FileManager.Standardize(item.ToLowerInvariant()) == FileManager.Standardize(plugin.ToLowerInvariant()));

                    if (!isIgnored)
                    {
                        bool wasCompiledFromCSharpCode = compileResult != null;

                        if (wasCompiledFromCSharpCode)
                        {
                            HandleAddingDynamicallyCompiledPlugin(returnValue, plugin, compileResult);
                        }

                        // If nothing was compiled check for any dlls to load
                        else
                        {
                            HandleAddingPreCompiledPluginInDirectory(returnValue, plugin);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CompileErrors.Add("Error loading plugin at " + plugin + "\r\n\r\n" + ex);
            }
        }
Esempio n. 11
0
        public bool Compile()
        {
            char[,] main = OpenedProject.Sources[OpenedProject.MainMethod];
            var keys = OpenedProject.Sources.Keys.ToList();
            Dictionary <char, char[, ]> otherMethods = new Dictionary <char, char[, ]>();

            foreach (string key in keys)
            {
                if (key.Length == 1)
                {
                    otherMethods.Add(key[0], OpenedProject.Sources[key]);
                }
            }
            Compiler comp = new Compiler(main, otherMethods);
            Tuple <int, CompileErrors> res = comp.GenerateCode(Path.GetDirectoryName(OpenedProject.ProjectPath) + @"\" + Path.GetFileNameWithoutExtension(OpenedProject.ProjectPath) + ".exe");

            CompilationErrors = res.Item2;
            ShowErrors();
            return(res.Item1 == 0);
        }
Esempio n. 12
0
        private void Eval()
        {
            if (!mainWindow.MakeUpToDate())
            {
                return;
            }

            int ErrorLineNumberCompilation;
            DataTypes ReturnType;
            PcodeRec FuncCode;
            Compiler.ASTExpression AST;
            CompileErrors CompileError = Compiler.CompileSpecialFunction(
                mainWindow.Document.CodeCenter,
                new FunctionParamRec[]
                {
                    new FunctionParamRec("frames", DataTypes.eInteger),
                    new FunctionParamRec("tables", DataTypes.eInteger),
                    new FunctionParamRec("data", DataTypes.eArrayOfFloat),
                },
                out ErrorLineNumberCompilation,
                out ReturnType,
                textBoxFormula.Text,
                false/*suppressCILEmission*/,
                out FuncCode,
                out AST);
            if (CompileError != CompileErrors.eCompileNoError)
            {
                textBoxFormula.Focus();
                textBoxFormula.SetSelectionLine(ErrorLineNumberCompilation - 1);
                textBoxFormula.ScrollToSelection();
                LiteralBuildErrorInfo errorInfo = new LiteralBuildErrorInfo(Compiler.GetCompileErrorString(CompileError), ErrorLineNumberCompilation);
                MessageBox.Show(errorInfo.CompositeErrorMessage, "Error", MessageBoxButtons.OK);
                return;
            }

            using (ParamStackRec ParamList = new ParamStackRec())
            {
                int numFrames = waveTableObject.WaveTableData.NumFrames;
                int numTables = waveTableObject.WaveTableData.NumTables;
                float[] vector = new float[numFrames * numTables];

                ArrayHandleFloat dataHandle = new ArrayHandleFloat(vector);

                int initialCapacity = 1/*frames*/ + 1/*tables*/ + 1/*data*/ + 1/*retaddr*/;
                ParamList.EmptyParamStackEnsureCapacity(initialCapacity);

                ParamList.AddIntegerToStack(numFrames);
                ParamList.AddIntegerToStack(numTables);
                ParamList.AddArrayToStack(dataHandle);
                ParamList.AddIntegerToStack(0); /* return address placeholder */

                for (int i = 0; i < numTables; i++)
                {
                    WaveTableStorageRec.Table table = waveTableObject.WaveTableData.ListOfTables[i];
                    for (int j = 0; j < numFrames; j++)
                    {
                        vector[i * numFrames + j] = table[j];
                    }
                }

                CodeCenterRec CodeCenter = mainWindow.Document.CodeCenter;
                EvalErrInfoRec ErrorInfo;
                EvalErrors EvaluationError = PcodeSystem.EvaluatePcodeThread.EvaluatePcode(
                    ParamList,
                    FuncCode,
                    CodeCenter,
                    out ErrorInfo,
                    new PcodeExterns(mainWindow));
                if (EvaluationError != EvalErrors.eEvalNoError)
                {
                    PcodeEvaluationErrorInfo errorInfo = new PcodeEvaluationErrorInfo(
                        EvaluationError,
                        ErrorInfo,
                        FuncCode,
                        CodeCenter);
                    MessageBox.Show(errorInfo.CompositeErrorMessage, "Error", MessageBoxButtons.OK);
                    return;
                }
                Debug.Assert(ParamList.GetStackNumElements() == initialCapacity); // args - retaddr + return value
#if DEBUG
                ParamList.Elements[2].AssertFloatArray();
#endif
                dataHandle = ParamList.Elements[2].reference.arrayHandleFloat;

                WaveTableStorageRec NewTable = new WaveTableStorageRec(numTables, numFrames, waveTableObject.WaveTableData.NumBits);
                float[] NewData = dataHandle.floats;
                if (NewData.Length != numTables * numFrames)
                {
                    PcodeEvaluationErrorInfo errorInfo = new PcodeEvaluationErrorInfo(
                        "<anonymous>",
                        PcodeSystem.GetPcodeErrorMessage(EvalErrors.eEvalArrayWrongDimensions),
                        1);
                    MessageBox.Show(errorInfo.CompositeErrorMessage, "Error", MessageBoxButtons.OK);
                    return;
                }
                SampConv.QuantizeAndClampVector(NewData, NewTable.NumBits);
                for (int i = 0; i < numTables; i++)
                {
                    WaveTableStorageRec.Table table = NewTable.ListOfTables[i];
                    for (int j = 0; j < numFrames; j++)
                    {
                        table[j] = NewData[i * numFrames + j];
                    }
                }

                undo.Push(waveTableObject.WaveTableData);
                redo.Clear();
                waveTableObject.WaveTableData = NewTable;
            }
        }
Esempio n. 13
0
        // Compile multiple modules. (eliminates the need to do prototyping or function signature inference.)
        // CodeCenter is cleared, and if compilation succeeds, the functions are added to CodeCenter.
        public static CompileErrors CompileWholeProgram(
            out int ErrorLineNumber,
            out int ErrorModuleIndex,
            string[] TextDatas,
            object[] Signatures,
            CodeCenterRec CodeCenter,
            string[] Filenames)
        {
            Debug.Assert(TextDatas.Length == Signatures.Length);
            Debug.Assert(TextDatas.Length == Filenames.Length);

            ErrorLineNumber  = -1;
            ErrorModuleIndex = -1;

            CodeCenter.FlushAllCompiledFunctions();
            CodeCenter.RetainedFunctionSignatures = new KeyValuePair <string, FunctionSignature> [0];

            // parse

            List <SymbolRec>     SymbolTableEntriesForForm = new List <SymbolRec>();
            List <ASTExpression> FunctionBodyRecords       = new List <ASTExpression>();
            List <int>           ModuleIndices             = new List <int>();
            Dictionary <string, List <ParserContext.FunctionSymbolRefInfo> > FunctionRefSymbolList = new Dictionary <string, List <ParserContext.FunctionSymbolRefInfo> >();
            List <int> InitialLineNumbersOfForm = new List <int>();

            for (int module = 0; module < TextDatas.Length; module++)
            {
                string TextData = TextDatas[module];

                ErrorModuleIndex = module;

                ScannerRec <KeywordsType> TheScanner     = new ScannerRec <KeywordsType>(TextData, KeywordTable);
                SymbolTableRec            TheSymbolTable = new SymbolTableRec();

                /* loop until there are no more things to parse */
                while (true)
                {
                    TokenRec <KeywordsType> Token = TheScanner.GetNextToken();
                    int InitialLineNumberOfForm   = TheScanner.GetCurrentLineNumber();
                    if (Token.GetTokenType() == TokenTypes.eTokenEndOfInput)
                    {
                        /* no more functions to parse, so stop */
                        break;
                    }

                    SymbolRec     SymbolTableEntryForForm;
                    ASTExpression FunctionBodyRecord;

                    /* parse the function */
                    TheScanner.UngetToken(Token);
                    CompileErrors Error = ParseForm(
                        out SymbolTableEntryForForm,
                        out FunctionBodyRecord,
                        new ParserContext(
                            TheScanner,
                            TheSymbolTable,
                            FunctionRefSymbolList),
                        out ErrorLineNumber);
                    if (Error != CompileErrors.eCompileNoError)
                    {
                        return(Error);
                    }

                    Debug.Assert(FunctionBodyRecord != null);
                    ModuleIndices.Add(module);
                    SymbolTableEntriesForForm.Add(SymbolTableEntryForForm);
                    FunctionBodyRecords.Add(FunctionBodyRecord);
                    InitialLineNumbersOfForm.Add(InitialLineNumberOfForm);
                }

                foreach (KeyValuePair <string, List <ParserContext.FunctionSymbolRefInfo> > name in FunctionRefSymbolList)
                {
                    foreach (ParserContext.FunctionSymbolRefInfo funcRef in name.Value)
                    {
                        funcRef.module = module;
                    }
                }
            }

            // push function type signatures into function call refs

            Dictionary <string, bool> functionNamesUsed = new Dictionary <string, bool>();

            for (int i = 0; i < SymbolTableEntriesForForm.Count; i++)
            {
                ErrorModuleIndex = ModuleIndices[i];

                SymbolRec FunctionDeclarationSymbol = SymbolTableEntriesForForm[i];
                if (functionNamesUsed.ContainsKey(FunctionDeclarationSymbol.SymbolName))
                {
                    ErrorLineNumber = FunctionBodyRecords[i].LineNumber;
                    return(CompileErrors.eCompileMultiplyDeclaredFunction);
                }
                functionNamesUsed.Add(FunctionDeclarationSymbol.SymbolName, false);

                List <ParserContext.FunctionSymbolRefInfo> symbols;
                if (FunctionRefSymbolList.TryGetValue(FunctionDeclarationSymbol.SymbolName, out symbols))
                {
                    foreach (ParserContext.FunctionSymbolRefInfo functionRef in symbols)
                    {
                        functionRef.symbol.SymbolBecomeFunction2(
                            FunctionDeclarationSymbol.FunctionArgList,
                            FunctionDeclarationSymbol.FunctionReturnType);
                    }
                    FunctionRefSymbolList.Remove(FunctionDeclarationSymbol.SymbolName);
                }
            }

            foreach (KeyValuePair <string, List <ParserContext.FunctionSymbolRefInfo> > name in FunctionRefSymbolList)
            {
                foreach (ParserContext.FunctionSymbolRefInfo funcRef in name.Value)
                {
                    ErrorModuleIndex = funcRef.module;
                    ErrorLineNumber  = funcRef.lineNumber;
                    return(CompileErrors.eCompileMultiplyDeclaredFunction);
                }
            }

            // type check and type inference

            for (int i = 0; i < FunctionBodyRecords.Count; i++)
            {
                int           module = ModuleIndices[i];
                SymbolRec     SymbolTableEntryForForm = SymbolTableEntriesForForm[i];
                ASTExpression FunctionBodyRecord      = FunctionBodyRecords[i];
                int           InitialLineNumberOfForm = InitialLineNumbersOfForm[i];

                ErrorModuleIndex = module;

                /* SymbolTableEntryForForm will be the symbol table entry that */
                /* was added to the symbol table.  FunctionBodyRecord is either */
                /* an expression for a function or NIL if it was a prototype */

                Debug.Assert(!CodeCenter.CodeCenterHaveThisFunction(SymbolTableEntryForForm.SymbolName));

                /* step 1:  do type checking */
                DataTypes     ResultingType;
                CompileErrors Error = FunctionBodyRecord.TypeCheck(
                    out ResultingType,
                    out ErrorLineNumber);
                if (Error != CompileErrors.eCompileNoError)
                {
                    return(Error);
                }
                /* check to see that resulting type matches declared type */
                if (!CanRightBeMadeToMatchLeft(SymbolTableEntryForForm.FunctionReturnType, ResultingType))
                {
                    ErrorLineNumber = InitialLineNumberOfForm;
                    return(CompileErrors.eCompileTypeMismatch);
                }
                /* if it has to be promoted, then promote it */
                if (MustRightBePromotedToLeft(SymbolTableEntryForForm.FunctionReturnType, ResultingType))
                {
                    /* insert promotion operator above expression */
                    ASTExpression ReplacementExpr = PromoteTheExpression(
                        ResultingType,
                        SymbolTableEntryForForm.FunctionReturnType,
                        FunctionBodyRecord,
                        InitialLineNumberOfForm);
                    FunctionBodyRecord = ReplacementExpr;
                    /* sanity check */
                    Error = FunctionBodyRecord.TypeCheck(
                        out ResultingType,
                        out ErrorLineNumber);
                    if (Error != CompileErrors.eCompileNoError)
                    {
                        // type promotion caused failure
                        Debug.Assert(false);
                        throw new InvalidOperationException();
                    }
                    if (ResultingType != SymbolTableEntryForForm.FunctionReturnType)
                    {
                        // after type promotion, types are no longer the same
                        Debug.Assert(false);
                        throw new InvalidOperationException();
                    }
                }
            }

            // code generation

            CILAssembly cilAssembly = null;

            if (CILObject.EnableCIL)
            {
                cilAssembly = new CILAssembly();
            }

            FuncCodeRec[] TheWholeFunctionThings = new FuncCodeRec[FunctionBodyRecords.Count];
            for (int i = 0; i < FunctionBodyRecords.Count; i++)
            {
                int           module = ModuleIndices[i];
                SymbolRec     SymbolTableEntryForForm = SymbolTableEntriesForForm[i];
                ASTExpression FunctionBodyRecord      = FunctionBodyRecords[i];
                int           InitialLineNumberOfForm = InitialLineNumbersOfForm[i];

                string Filename  = Filenames[module];
                object Signature = Signatures[module];

                ErrorModuleIndex = module;

                Debug.Assert(!CodeCenter.CodeCenterHaveThisFunction(SymbolTableEntryForForm.SymbolName));

                /* step 1.5:  optimize the AST */
                OptimizeAST(ref FunctionBodyRecord);

                /* step 2:  do code generation */
                /* calling conventions:  */
                /*  - push the arguments */
                /*  - funccall pushes the return address */
                /* thus, upon entry, Stack[0] will be the return address */
                /* and Stack[-1] will be the rightmost argument */
                /* on return, args and retaddr are popped and retval replaces them */
                int           StackDepth             = 0;
                int           MaxStackDepth          = 0;
                int           ReturnValueLocation    = StackDepth; /* remember return value location */
                int           ArgumentIndex          = 0;
                SymbolListRec FormalArgumentListScan = SymbolTableEntryForForm.FunctionArgList;
                while (FormalArgumentListScan != null)
                {
                    SymbolRec TheFormalArg = FormalArgumentListScan.First;
                    StackDepth++;                                          /* allocate first */
                    MaxStackDepth = Math.Max(MaxStackDepth, StackDepth);
                    TheFormalArg.SymbolVariableStackLocation = StackDepth; /* remember */
                    ArgumentIndex++;
                    FormalArgumentListScan = FormalArgumentListScan.Rest;
                }
                /* reserve return address spot */
                StackDepth++;
                MaxStackDepth = Math.Max(MaxStackDepth, StackDepth);
                /* allocate the function code */
                PcodeRec TheFunctionCode = new PcodeRec();
                FunctionBodyRecord.PcodeGen(
                    TheFunctionCode,
                    ref StackDepth,
                    ref MaxStackDepth);
                Debug.Assert(StackDepth <= MaxStackDepth);
                /* 2 extra words for retaddr and resultofexpr */
                if (StackDepth != ArgumentIndex + 1 + 1)
                {
                    // stack depth error after evaluating function
                    Debug.Assert(false);
                    throw new InvalidOperationException();
                }
                /* now put the return instruction (pops retaddr and args, leaving retval) */
                int ignored;
                TheFunctionCode.AddPcodeInstruction(Pcodes.epReturnFromSubroutine, out ignored, InitialLineNumberOfForm);
                TheFunctionCode.AddPcodeOperandInteger(ArgumentIndex);
                StackDepth = StackDepth - (1 + ArgumentIndex);
                Debug.Assert(StackDepth <= MaxStackDepth);
                if (StackDepth != 1)
                {
                    // stack depth is wrong at end of function
                    Debug.Assert(false);
                    throw new InvalidOperationException();
                }

                TheFunctionCode.MaxStackDepth = MaxStackDepth;

                /* step 2.5:  optimize the code */
                TheFunctionCode.OptimizePcode();

                /* step 3:  create the function and save it away */
                FuncCodeRec TheWholeFunctionThing = new FuncCodeRec(
                    SymbolTableEntryForForm.SymbolName,
                    SymbolTableEntryForForm.FunctionArgList,
                    TheFunctionCode,
                    SymbolTableEntryForForm.FunctionReturnType,
                    Filename);

                TheWholeFunctionThings[i] = TheWholeFunctionThing;

                if (CILObject.EnableCIL)
                {
                    DataTypes[] argsTypes;
                    string[]    argsNames;
                    SymbolicArgListToType(SymbolTableEntryForForm, out argsTypes, out argsNames);
                    CILObject cilObject = new CILObject(
                        CodeCenter.ManagedFunctionLinker,
                        argsTypes,
                        argsNames,
                        SymbolTableEntryForForm.FunctionReturnType,
                        FunctionBodyRecord,
                        cilAssembly,
                        false /*argsByRef*/);
                    TheWholeFunctionThing.CILObject = cilObject;
                }
            }

            // register after entire assembly is emitted
            if (CILObject.EnableCIL)
            {
                cilAssembly.Finish();
            }

            for (int i = 0; i < TheWholeFunctionThings.Length; i++)
            {
                FuncCodeRec TheWholeFunctionThing = TheWholeFunctionThings[i];
                object      Signature             = Signatures[ModuleIndices[i]];

                CodeCenter.AddFunctionToCodeCenter(TheWholeFunctionThing, Signature);
            }

            // retain signatures for compilation of special functions

            CodeCenter.RetainedFunctionSignatures = new KeyValuePair <string, FunctionSignature> [SymbolTableEntriesForForm.Count];
            for (int i = 0; i < CodeCenter.RetainedFunctionSignatures.Length; i++)
            {
                DataTypes[] argsTypes;
                string[]    argsNames;
                SymbolicArgListToType(SymbolTableEntriesForForm[i], out argsTypes, out argsNames);
                CodeCenter.RetainedFunctionSignatures[i] = new KeyValuePair <string, FunctionSignature>(
                    SymbolTableEntriesForForm[i].SymbolName,
                    new FunctionSignature(
                        argsTypes,
                        SymbolTableEntriesForForm[i].FunctionReturnType));
            }

            return(CompileErrors.eCompileNoError);
        }
Esempio n. 14
0
 public CompileErrorRec(CompileErrors ErrorCode, string Message)
 {
     this.ErrorCode = ErrorCode;
     this.Message   = Message;
 }
        private void HandleAddingPreCompiledPluginInDirectory(AggregateCatalog returnValue, string pluginDirectory)
        {
            List <Assembly> assemblies = new List <Assembly>();

            var assembliesFiles = Directory.GetFiles(pluginDirectory, "*.dll");

            foreach (string assemblyName in assembliesFiles)
            {
                try
                {
                    if (IsAssemblyAlreadyReferenced(assemblyName))
                    {
                        string message = $"Warning: {pluginDirectory} - Skipping over assembly {assemblyName} because it is already loaded by a different plugin";

                        CompileOutput.Add(message);
                    }
                    else
                    {
                        var asm = Assembly.LoadFrom(assemblyName);

                        assemblies.Add(asm);
                    }
                }
                catch (Exception ex)
                {
                    CompileErrors.Add(string.Format("Failed to load {0}: {1}", assemblyName, ex.Message));
                }
            }

            AggregateCatalog catalogToMakeSureStuffIsLinked = new AggregateCatalog();

            foreach (var assembly in assemblies)
            {
                var catalog = new AssemblyCatalog(assembly);
                catalogToMakeSureStuffIsLinked.Catalogs.Add(catalog);
            }

            bool failed = false;

            try
            {
                var container = new CompositionContainer(catalogToMakeSureStuffIsLinked);
                container.GetExports <object>();
            }
            catch (Exception e)
            {
                string message = "";
                message += "Error trying to load plugins from directory:     " + pluginDirectory;

                if (e is ReflectionTypeLoadException)
                {
                    foreach (var innerException in (e as ReflectionTypeLoadException).LoaderExceptions)
                    {
                        message += "\r\n" + innerException.ToString();
                    }
                }
                else
                {
                    message += "\r\n" + e.ToString();
                }
                CompileErrors.Add(message);

                failed = true;
            }

            if (!failed)
            {
                foreach (var assemblyCatalog in catalogToMakeSureStuffIsLinked.Catalogs)
                {
                    returnValue.Catalogs.Add(assemblyCatalog);
                }
            }
        }
Esempio n. 16
0
        public Assembly GetAssembly()
        {
            ImplementInterface();
            CreateConstructor();

            string _source = "//------------------------------------------------------------------------------" + Environment.NewLine +
                             "// <auto-generated>" + Environment.NewLine +
                             "//     Dynamically created source code. Provisionally created as C# syntax, " + Environment.NewLine +
                             "//     because CodeDom is not supported under .NET Core. " + Environment.NewLine +
                             "// </auto-generated>" + Environment.NewLine +
                             "//------------------------------------------------------------------------------" + Environment.NewLine;

            _source += "namespace " + CodeNameSpace + Environment.NewLine;
            _source += "{" + Environment.NewLine;
            _source += "    using System;" + Environment.NewLine;
            _source += "    using Stateless;" + Environment.NewLine;
            _source += "    using Stateless.Graph;" + Environment.NewLine;
            _source += "    using LogFSMShared;" + Environment.NewLine;
            _source += "    using System.Linq;" + Environment.NewLine;

            //_source += "    using System.ComponentModel.Primitives;" + Environment.NewLine;
            _source += "    using System.IO;" + Environment.NewLine;
            _source += "    using System.Collections;" + Environment.NewLine;
            _source += "    using System.Collections.Generic;" + Environment.NewLine;

            _source += "    public class " + ClassName + ": LogFSMShared.LogFSMBase, LogFSMShared.ILogFSM " + Environment.NewLine;
            _source += "    {" + Environment.NewLine;
            _source += "        private Dictionary<int,Stateless.StateMachine<State,Trigger>> machines;" + Environment.NewLine;

            _source += constructorCodeFragment;

            _source += createProcessEventMethodCodeFragment;

            _source += createRulesFunctionCodeFragment;

            _source += createTriggerFunctionCodeFragment;

            _source += enumDefinitionCodeFragment;

            _source += triggerDefinitionCodeFragment;

            _source += "     } " + Environment.NewLine;
            _source += " } " + Environment.NewLine;

            // export generated cs code for inspection
            if (parsedCommandLineArguments.Flags.Contains("EXPORT_GENERATED_SOURCE") || parsedCommandLineArguments.IsDebug)
            {
                using (StreamWriter sourceWriter = new StreamWriter(sourceFileName))
                {
                    sourceWriter.Write(_source);
                }
            }

            Assembly createdAssembly = null;

            var options = new CSharpCompilationOptions(
                OutputKind.DynamicallyLinkedLibrary,
                optimizationLevel: OptimizationLevel.Release,
                allowUnsafe: false);

            var compilation = CSharpCompilation.Create(Path.GetRandomFileName(), options: options);

            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(_source);

            compilation = compilation.AddSyntaxTrees(syntaxTree);

            // TODO: Optimize!

            #region Add Rferences

            var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
            List <MetadataReference> references = new List <MetadataReference>();

            references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Private.CoreLib.dll")));
            references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Console.dll")));
            references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll")));

            var usings = compilation.SyntaxTrees.Select(tree => tree.GetRoot().DescendantNodes().OfType <UsingDirectiveSyntax>()).SelectMany(s => s).ToArray();

            foreach (var u in usings)
            {
                if (File.Exists(Path.Combine(assemblyPath, u.Name.ToString() + ".dll")))
                {
                    references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, u.Name.ToString() + ".dll")));
                }
            }

            references.Add(MetadataReference.CreateFromFile(Path.Combine(parsedCommandLineArguments.RuntimePath, "Stateless.dll")));
            references.Add(MetadataReference.CreateFromFile(Assembly.Load("netstandard, Version=2.0.0.0").Location));
            references.Add(MetadataReference.CreateFromFile(Path.Combine(parsedCommandLineArguments.RuntimePath, "LogFSMShared.dll")));

            #endregion

            compilation = compilation.AddReferences(references);

            //compile

            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);

                if (!result.Success)
                {
                    IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                                 diagnostic.IsWarningAsError ||
                                                                                 diagnostic.Severity == DiagnosticSeverity.Error);

                    foreach (Diagnostic diagnostic in failures)
                    {
                        CompileErrors.Add(diagnostic.Id + ";" + diagnostic.GetMessage() + ";" + diagnostic.Location);
                    }
                }
                else
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    AssemblyLoadContext context = AssemblyLoadContext.Default;
                    createdAssembly = context.LoadFromStream(ms);
                }
            }

            if (HasErrors)
            {
                foreach (string l in CompileErrors)
                {
                    File.AppendAllText(Path.Combine(parsedCommandLineArguments.OutputPath, "logfsmlasterror.txt"), l);
                }
            }

            return(createdAssembly);
        }