Exemplo n.º 1
0
        public CompilerTestCase CreateTestCase(DirectoryInfo testDir)
        {
            FileInfo[] inputFiles = testDir.GetFiles("*.p");
            string     testName   = new Uri(Constants.TestDirectory + Path.DirectorySeparatorChar)
                                    .MakeRelativeUri(new Uri(testDir.FullName))
                                    .ToString();

            ICompilerTestRunner   runner;
            ITestResultsValidator validator;

            CompilerOutput output = CompilerOutput.C;

            runner = new CompileOnlyRunner(output, inputFiles);

            // TODO: validate information about the particular kind of compiler error
            bool isStaticError = testName.Contains("/StaticError/");

            validator = isStaticError
                ? (ITestResultsValidator) new StaticErrorValidator()
                : new CompileSuccessValidator();

            DirectoryInfo tempDirName =
                Directory.CreateDirectory(Path.Combine(testTempBaseDir.FullName, output.ToString(), testName));

            return(new CompilerTestCase(tempDirName, runner, validator));
        }
Exemplo n.º 2
0
        public static void Main(string[] args)
        {
            DirectoryInfo      debugDirectoryInfo = Directory.GetParent(Directory.GetCurrentDirectory());
            string             workingDirectory   = debugDirectoryInfo.Parent.Parent.Parent.Parent.FullName;
            string             filename           = "Branch.sol";
            string             solcPath           = workingDirectory + "\\Tool\\solc.exe";
            string             filePath           = workingDirectory + "\\Test\\regression\\" + filename;
            SolidityCompiler   compiler           = new SolidityCompiler();
            CompilerOutput     compilerOutput     = compiler.Compile(solcPath, filePath);
            SoliditySourceFile soliditySourceFile = compilerOutput.Sources[filename];
            ASTNode            root = soliditySourceFile.Ast;

            Debug.Assert(root.GetType() == typeof(SourceUnit));
            foreach (ASTNode decl in ((SourceUnit)root).Nodes)
            {
                if (decl is ContractDefinition)
                {
                    ContractDefinition contract = (ContractDefinition)decl;
                    Console.WriteLine("contract " + contract.Name);
                    foreach (ASTNode node in contract.Nodes)
                    {
                        if (node is FunctionDefinition)
                        {
                            FunctionDefinition func = (FunctionDefinition)node;
                            Console.WriteLine("function " + func.Name);
                            Test(func);
                        }
                    }
                }
            }

            Console.ReadLine();
        }
        public void OnCompilationSucceededAction(CompilerOutput output)
        {
            //for (int i = 0; i < output.Warnings.Count; i++)
            //    Debug.LogWarning(output.Warnings[i]);

            _lastCompilationSucceeded = true;
        }
Exemplo n.º 4
0
        private static void GetTargetLanguage(FileInfo fullPathName, ref CompilerOutput outputLanguage, ref bool generateSourceMaps)
        {
            XElement projectXML = XElement.Load(fullPathName.FullName);

            if (projectXML.Elements("Target").Any())
            {
                switch (projectXML.Element("Target").Value.ToLowerInvariant())
                {
                case "c":
                    outputLanguage = CompilerOutput.C;
                    // check for generate source maps attribute
                    try
                    {
                        if (projectXML.Element("Target").Attributes("sourcemaps").Any())
                        {
                            generateSourceMaps = bool.Parse(projectXML.Element("Target").Attribute("sourcemaps").Value);
                        }
                    }
                    catch (Exception)
                    {
                        CommandlineOutput.WriteMessage($"Expected true or false, received {projectXML.Element("Target").Attribute("sourcemaps").Value}", SeverityKind.Error);
                        Environment.Exit(1);
                    }
                    break;

                case "coyote":
                    outputLanguage = CompilerOutput.Coyote;
                    break;

                default:
                    outputLanguage = CompilerOutput.C;
                    break;
                }
            }
        }
Exemplo n.º 5
0
 //Method of type Action<CompilerOutput> that will be executed on succesfull compilation(without errors)
 //Outputs warnings occured during compilation to editor console
 public void OnCompilationSucceededAction(CompilerOutput output)
 {
     for (int i = 0; i < output.Warnings.Count; i++)
     {
         Debug.LogWarning(output.Warnings[i]);
     }
 }
Exemplo n.º 6
0
 public InputOptions()
 {
     SolutionXml = "";
     Rebuild     = false;
     Relink      = false;
     Output      = CompilerOutput.CSharp;
     ProjectName = "";
 }
Exemplo n.º 7
0
        /// <summary>
        /// Logs the build result.
        /// </summary>
        /// <param name="output">The result of the build.</param>
        public override void LogResult(CompilerOutput output)
        {
            if (Verbosity >= LoggerVerbosity.Quiet)
            {
                TextWriter w = output.Succeeded ? Console.Out : Console.Error;

                w.WriteLine(output.ToString());
            }
        }
Exemplo n.º 8
0
 /// <summary>
 /// Save a compiled application into a byte array.
 /// </summary>
 /// <param name="compiled">Compiled application to save.</param>
 /// <returns>Saved queue.</returns>
 public static byte[] SaveApplication(CompilerOutput compiled)
 {
     using (var ms = new MemoryStream())
     {
         var bf = new BinaryFormatter();
         bf.Serialize(ms, compiled);
         return ms.ToArray();
     }
 }
Exemplo n.º 9
0
    public void OnCompilationFailedAction(CompilerOutput output)
    {
        ////Uncomment this to acquire additional information
        //for (int i = 0; i < output.Errors.Count; i++)
        //    Debug.LogError(output.Errors[i]);
        //for (int i = 0; i < output.Warnings.Count; i++)
        //    Debug.LogWarning(output.Warnings[i]);

        _lastCompilationSucceeded = false;
    }
Exemplo n.º 10
0
 /// <summary>
 /// Logs the build result.
 /// </summary>
 /// <param name="output">The result of the build.</param>
 public override void LogResult(CompilerOutput output)
 {
     if (Verbosity >= LoggerVerbosity.Quiet)
     {
         if (output.Succeeded)
             Debug.WriteLine(output);
         else
             Debug.Fail("Build failed.", output.ToString());
     }
 }
Exemplo n.º 11
0
        // This method runs within a thread to compile code
        static void threadedFunction(string code)
        {
            //Thread.Sleep(1000);

            try{
                compilerOutput_global = evaluateCode(code);
            }catch (Exception ex) {
                //System.Console.WriteLine("Caught: " + ex.ToString());
            }
        }
Exemplo n.º 12
0
        /// <summary>
        ///     Box a test case from the given directory and parsed Prt run configuration
        /// </summary>
        /// <param name="testDir">The directory containing P source files</param>
        /// <param name="output">The desired output language</param>
        /// <returns>The test case in a runnable state.</returns>
        public CompilerTestCase CreateTestCase(DirectoryInfo testDir, CompilerOutput output)
        {
            var inputFiles = testDir.GetFiles("*.p");
            var testName   = new Uri(Constants.TestDirectory + Path.DirectorySeparatorChar)
                             .MakeRelativeUri(new Uri(testDir.FullName))
                             .ToString();

            ICompilerTestRunner   runner;
            ITestResultsValidator validator;

            string expectedOutput;

            if (output.Equals(CompilerOutput.C))
            {
                var nativeFiles = testDir.GetFiles("*.c");
                runner         = new PrtRunner(inputFiles, nativeFiles);
                expectedOutput =
                    File.ReadAllText(Path.Combine(testDir.FullName, "Prt", Constants.CorrectOutputFileName));
            }
            else if (output.Equals(CompilerOutput.PSharp))
            {
                var nativeFiles = testDir.GetFiles("*.cs");
                runner = new PSharpRunner(inputFiles, nativeFiles);
                var prtGoldenOutputFile      = Path.Combine(testDir.FullName, "Prt", Constants.CorrectOutputFileName);
                var prtSharpGoldenOutputFile =
                    Path.Combine(testDir.FullName, "PrtSharp", Constants.CorrectOutputFileName);
                if (File.Exists(prtSharpGoldenOutputFile))
                {
                    expectedOutput = File.ReadAllText(prtSharpGoldenOutputFile);
                }
                else
                {
                    expectedOutput = File.ReadAllText(prtGoldenOutputFile);
                }
            }
            else
            {
                throw new ArgumentOutOfRangeException();
            }

            // TODO: fix golden outputs for dynamic error assertions (79 tests)
            ParseExpectedOutput(expectedOutput, out var stdout, out var stderr, out var exitCode);
            if (testName.Contains("/DynamicError/") || output.Equals(CompilerOutput.PSharp))
            {
                stdout = null;
                stderr = null;
            }

            validator = new ExecutionOutputValidator(exitCode, stdout, stderr);

            var tempDirName =
                Directory.CreateDirectory(Path.Combine(testTempBaseDir.FullName, output.ToString(), testName));

            return(new CompilerTestCase(tempDirName, runner, validator));
        }
Exemplo n.º 13
0
 //Method of type Action<CompilerOutput> that will be executed on failed compilation(with errors)
 //Outputs errors occured during compilation to editor console
 public void OnCompilationFailedAction(CompilerOutput output)
 {
     for (int i = 0; i < output.Errors.Count; i++)
     {
         Debug.LogError(output.Errors[i]);
     }
     for (int i = 0; i < output.Warnings.Count; i++)
     {
         Debug.LogWarning(output.Warnings[i]);
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// Parse the P Project file
        /// </summary>
        /// <param name="projectFile">Path to the P project file</param>
        /// <param name="job">out parameter of P compilation job, after parsing the project file</param>
        /// <returns></returns>
        public bool ParseProjectFile(string projectFile, out CompilationJob job)
        {
            job = null;
            try
            {
                if (!IsLegalPProjFile(projectFile, out FileInfo projectFilePath))
                {
                    throw new CommandlineParsingError($"Illegal P project file name {projectFile} or file {projectFilePath?.FullName} not found");
                }
                CommandlineOutput.WriteInfo($"----------------------------------------");
                CommandlineOutput.WriteInfo($"==== Loading project file: {projectFile}");

                CompilerOutput  outputLanguage      = CompilerOutput.C;
                List <FileInfo> inputFiles          = new List <FileInfo>();
                bool            generateSourceMaps  = false;
                List <string>   projectDependencies = new List <string>();

                // get all project dependencies and the input files
                var dependencies = GetAllProjectDependencies(projectFilePath);

                inputFiles.AddRange(dependencies.inputFiles);
                projectDependencies.AddRange(dependencies.projectDependencies);

                if (inputFiles.Count == 0)
                {
                    throw new CommandlineParsingError("At least one .p file must be provided as input files, no input files found after parsing the project file");
                }

                // get project name
                string projectName = GetProjectName(projectFilePath);

                // get output directory
                DirectoryInfo outputDirectory = GetOutputDirectory(projectFilePath);

                // get target language
                GetTargetLanguage(projectFilePath, ref outputLanguage, ref generateSourceMaps);

                job = new CompilationJob(output: new DefaultCompilerOutput(outputDirectory), outputDirectory, outputLanguage: outputLanguage, inputFiles: inputFiles, projectName: projectName, projectFilePath.Directory, generateSourceMaps: generateSourceMaps, projectDependencies);

                CommandlineOutput.WriteInfo($"----------------------------------------");
                return(true);
            }
            catch (CommandlineParsingError ex)
            {
                CommandlineOutput.WriteError($"<Error parsing project file>:\n {ex.Message}");
                return(false);
            }
            catch (Exception other)
            {
                CommandlineOutput.WriteError($"<Internal Error>:\n {other.Message}\n <Please report to the P team ([email protected]) or create a issue on GitHub, Thanks!>");
                return(false);
            }
        }
Exemplo n.º 15
0
        public BatchExeResult Execute(string filename, out string expected, out string current)
        {
            BatchExeResult result   = BatchExeResult.SolcError;
            string         filePath = Path.Combine(testDirectory, filename);

            // compile the program
            SolidityCompiler compiler       = new SolidityCompiler();
            CompilerOutput   compilerOutput = compiler.Compile(solcPath, filePath);

            if (compilerOutput.ContainsError())
            {
                compilerOutput.PrintErrorsToConsole();
                throw new SystemException("Compilation Error");
            }

            // build the Solidity AST from solc output
            AST solidityAST = new AST(compilerOutput, Path.GetDirectoryName(filePath));

            // translate Solidity to Boogie
            try
            {
                BoogieTranslator translator = new BoogieTranslator();
                var translatorFlags         = new TranslatorFlags();
                translatorFlags.GenerateInlineAttributes = false;
                BoogieAST boogieAST = translator.Translate(solidityAST, new HashSet <Tuple <string, string> >(), translatorFlags);

                // dump the Boogie program to a file
                using (var outWriter = new StreamWriter(outFile))
                {
                    outWriter.WriteLine(boogieAST.GetRoot());
                }
            } catch (Exception e)
            {
                Console.WriteLine($"VeriSol translation error: {e.Message}");
                result   = BatchExeResult.SolToBoogieError;
                expected = current = null;
                return(result);
            }

            // read the corral configuration from Json
            string configJsonPath            = Path.Combine(configDirectory, Path.GetFileNameWithoutExtension(filename) + ".json");
            string jsonString                = File.ReadAllText(configJsonPath);
            CorralConfiguration corralConfig = JsonConvert.DeserializeObject <CorralConfiguration>(jsonString);

            string corralOutput = RunCorral(corralConfig);

            expected = corralConfig.ExpectedResult;
            current  = corralOutput;
            result   = CompareCorralOutput(corralConfig.ExpectedResult, corralOutput);
            return(result);
        }
Exemplo n.º 16
0
        public CompilationJob(ICompilerOutput output, CompilerOutput outputLanguage, IReadOnlyList <FileInfo> inputFiles,
                              string projectName = null, bool generateSourceMaps = false)
        {
            if (!inputFiles.Any())
            {
                throw new ArgumentException("Must supply at least one input file", nameof(inputFiles));
            }

            Output             = output;
            InputFiles         = inputFiles;
            ProjectName        = projectName ?? Path.GetFileNameWithoutExtension(inputFiles[0].FullName);
            LocationResolver   = new DefaultLocationResolver();
            Handler            = new DefaultTranslationErrorHandler(LocationResolver);
            Backend            = TargetLanguage.GetCodeGenerator(outputLanguage);
            GenerateSourceMaps = generateSourceMaps;
        }
Exemplo n.º 17
0
        /// <summary>
        ///     Box a test case from the given directory and parsed Prt run configuration
        /// </summary>
        /// <param name="testDir">The directory containing P source files</param>
        /// <param name="output">The desired output language</param>
        /// <returns>The test case in a runnable state.</returns>
        public CompilerTestCase CreateTestCase(DirectoryInfo testDir, CompilerOutput output)
        {
            FileInfo[] inputFiles = testDir.GetFiles("*.p");
            string     testName   = new Uri(Constants.TestDirectory + Path.DirectorySeparatorChar)
                                    .MakeRelativeUri(new Uri(testDir.FullName))
                                    .ToString();

            ICompilerTestRunner   runner;
            ITestResultsValidator validator;

            int expectedExitCode;

            if (testName.Contains("/DynamicError/") || testName.Contains("/DynamicErrorCoyoteRuntime/"))
            {
                expectedExitCode = 1;
            }
            else if (testName.Contains("/Correct/") || testName.Contains("/CorrectCoyoteRuntime/"))
            {
                expectedExitCode = 0;
            }
            else
            {
                throw new CompilerTestException(TestCaseError.UnrecognizedTestCaseType);
            }

            if (output.Equals(CompilerOutput.C))
            {
                FileInfo[] nativeFiles = testDir.GetFiles("*.c");
                runner = new PrtRunner(inputFiles, nativeFiles);
            }
            else if (output.Equals(CompilerOutput.Coyote))
            {
                FileInfo[] nativeFiles = testDir.GetFiles("*.cs");
                runner = new CoyoteRunner(inputFiles, nativeFiles);
            }
            else
            {
                throw new ArgumentOutOfRangeException();
            }

            validator = new ExecutionOutputValidator(expectedExitCode);

            DirectoryInfo tempDirName =
                Directory.CreateDirectory(Path.Combine(testTempBaseDir.FullName, output.ToString(), testName));

            return(new CompilerTestCase(tempDirName, runner, validator));
        }
Exemplo n.º 18
0
 public void UpdateSolution(Solution solution)
 {
     solution.State          = StateId;
     solution.RunTime        = RunTimeMs;
     solution.UsingMemoryMb  = UsingMemoryMb;
     solution.CompilerOutput = CompilerOutput?.Substring(0, Math.Min(Solution.CompilerOutputLimit, CompilerOutput.Length));
     if (WrongAnswer != null)
     {
         var wrongAnswer = solution.WrongAnswer ?? new SolutionWrongAnswer();
         {
             wrongAnswer.QuestionDataId = WrongAnswerInputId;
             wrongAnswer.Output         = WrongAnswer?.Substring(0, Math.Min(SolutionWrongAnswer.WrongAnswerLimit, WrongAnswer.Length));
         }
         solution.WrongAnswer = wrongAnswer;
     }
     solution.Lock = null;
 }
Exemplo n.º 19
0
        // This method evaluates the given code and returns a CompilerOutput object
        public static CompilerOutput evaluateCode(string code)
        {
            CompilerOutput compilerOutput = new CompilerOutput();

            /*
             * var compilerContext = new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter());
             *
             * var evaluator = new Evaluator(compilerContext);
             */
            var reportWriter = new StringWriter();
            var settings     = new CompilerSettings();
            var printer      = new ConsoleReportPrinter(reportWriter);

            var compilerContext = new CompilerContext(settings, printer);
            var reports         = new Report(compilerContext, printer);
            var evaluator       = new Evaluator(compilerContext);

            var myString = "";

            originalConsoleOut_global = Console.Out;             // preserve the original stream
            using (var writer = new StringWriter())
            {
                Console.SetOut(writer);

                evaluator.Run(code);
                evaluator.Run("MainClass m1 = new MainClass(); m1.Main();");

                //bConsole.WriteLine ("after executing code");

                if (reports.Errors > 0)
                {
                    Console.WriteLine("reportWriter.ToString: \n" + reportWriter.ToString());
                    compilerOutput.errors = reportWriter.ToString();
                }

                writer.Flush();                 // make sure everything is written out of consule

                myString = writer.GetStringBuilder().ToString();

                compilerOutput.consoleOut = myString;
            }

            Console.SetOut(originalConsoleOut_global);             // restore Console.Out

            return(compilerOutput);
        }
Exemplo n.º 20
0
        // This method evaluates the given code and returns a CompilerOutput object
        public static CompilerOutput evaluateCode(string code)
        {
            CompilerOutput compilerOutput = new CompilerOutput ();
            /*
            var compilerContext = new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter());

            var evaluator = new Evaluator(compilerContext);
            */
            var reportWriter = new StringWriter();
            var settings = new CompilerSettings();
            var printer = new ConsoleReportPrinter(reportWriter);

            var compilerContext = new CompilerContext (settings, printer);
            var reports = new Report(compilerContext, printer);
            var evaluator = new Evaluator(compilerContext);

            var myString = "";
            originalConsoleOut_global = Console.Out; // preserve the original stream
            using(var writer = new StringWriter())
            {
                Console.SetOut(writer);

                evaluator.Run (code);
                evaluator.Run ("MainClass m1 = new MainClass(); m1.Main();");

                //bConsole.WriteLine ("after executing code");

                if (reports.Errors > 0) {
                    Console.WriteLine ("reportWriter.ToString: \n" + reportWriter.ToString ());
                    compilerOutput.errors = reportWriter.ToString ();
                }

                writer.Flush(); // make sure everything is written out of consule

                myString = writer.GetStringBuilder().ToString();

                compilerOutput.consoleOut = myString;

            }

            Console.SetOut(originalConsoleOut_global); // restore Console.Out

            return compilerOutput;
        }
Exemplo n.º 21
0
        /**
         * Runs solidity conversion function
         */
        private bool runSolidityToBoogieConversion()
        {
            Console.WriteLine("Starting Solidity Compiler.");

            // compile the program
            Console.WriteLine($"Running Compiler on {contractName}.");

            SolidityCompiler compiler       = new SolidityCompiler();
            CompilerOutput   compilerOutput = compiler.Compile(solidityCompilerPath, solidityFilePath);

            if (compilerOutput.ContainsError())
            {
                compilerOutput.PrintErrorsToConsole();
                throw new SystemException("Compilation Error");
            }

            // build the Solidity AST from solc output
            AST solidityAST = new AST(compilerOutput, Path.GetDirectoryName(solidityFilePath));

            // translate Solidity to Boogie
            try
            {
                // if application reaches this stage, compilation of the program was successful
                // The application now attemps to convert the solidity code to Boogie through the use of collection and syntax trees.

                ConversionToBoogie_Main translator = new ConversionToBoogie_Main();
                Console.WriteLine($"\nAttempting Conversion to Boogie.");
                BoogieAST boogieAST = translator.Translate(solidityAST, ignoreMethods, translatorFlags);

                // dump the Boogie program to a file
                var outFilePath = Path.Combine(solidityFileDir, boogieRepresentationOfSolContract);
                using (var outWriter = new StreamWriter(boogieRepresentationOfSolContract))
                {
                    outWriter.WriteLine(boogieAST.GetRoot());//get all AST components
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"OverSight translation error: {e.Message}");
                return(false);
            }
            return(true);
        }
Exemplo n.º 22
0
        private static bool ParseProjectFile(string projectFile, out CompilationJob job)
        {
            job = null;
            if (!IsLegalPProjFile(projectFile, out FileInfo projectFilePath))
            {
                CommandlineOutput.WriteMessage(
                    $"Illegal P project file name {projectFile} or file {projectFilePath?.FullName} not found", SeverityKind.Error);
                return(false);
            }

            CommandlineOutput.WriteMessage($".... Parsing the project file: {projectFile}", SeverityKind.Info);

            CompilerOutput  outputLanguage      = CompilerOutput.C;
            List <FileInfo> inputFiles          = new List <FileInfo>();
            bool            generateSourceMaps  = false;
            List <string>   projectDependencies = new List <string>();

            // get all project dependencies and the input files
            var dependencies = GetAllProjectDependencies(projectFilePath);

            inputFiles.AddRange(dependencies.inputFiles);
            projectDependencies.AddRange(dependencies.projectDependencies);

            if (inputFiles.Count == 0)
            {
                CommandlineOutput.WriteMessage("At least one .p file must be provided as input files", SeverityKind.Error);
                return(false);
            }

            // get project name
            string projectName = GetProjectName(projectFilePath);

            // get output directory
            DirectoryInfo outputDirectory = GetOutputDirectory(projectFilePath);


            // get target language
            GetTargetLanguage(projectFilePath, ref outputLanguage, ref generateSourceMaps);

            job = new CompilationJob(output: new DefaultCompilerOutput(outputDirectory), outputLanguage: outputLanguage, inputFiles: inputFiles, projectName: projectName, generateSourceMaps: generateSourceMaps, projectDependencies);
            return(true);
        }
Exemplo n.º 23
0
        // This method accepts a string which contains CSharp code then calls another functions to evaluate and execute the code
        // Output of this function is a string in JSON format
        public string compileCode(string code)
        {
            CompilerOutput result = new CompilerOutput();

            if (isDangerousCode(code))
            {
                result.errors = "Possible dangerous code";
            }
            else if (code.Length >= code_input_limit_global)
            {
                result.errors = "Due to server limits, we have restricted code size to " + code_input_limit_global + " characters.";
            }
            else
            {
                result = run(code);
            }

            string jsontmp = toJSON(result);

            return(jsontmp);
        }
Exemplo n.º 24
0
        private bool ExecuteSolToBoogie()
        {
            // compile the program
            Console.WriteLine($"\n----- Running Solc on {SpecFilePath}....");

            SolidityCompiler compiler       = new SolidityCompiler();
            CompilerOutput   compilerOutput = compiler.Compile(SolcPath, SpecFilePath);

            if (compilerOutput.ContainsError())
            {
                compilerOutput.PrintErrorsToConsole();
                throw new SystemException("Compilation Error");
            }

            // build the Solidity AST from solc output
            AST solidityAST = new AST(compilerOutput, Path.GetDirectoryName(SpecFilePath));

            // translate Solidity to Boogie
            try
            {
                BoogieTranslator translator = new BoogieTranslator();
                Console.WriteLine($"\n----- Running SolToBoogie....");
                var translatorFlags = new TranslatorFlags();
                translatorFlags.GenerateInlineAttributes = true;
                BoogieAST boogieAST = translator.Translate(solidityAST, ignoreMethods, translatorFlags);

                // dump the Boogie program to a file
                var outFilePath = Path.Combine(SpecFileDir, outFileName);
                using (var outWriter = new StreamWriter(outFileName))
                {
                    outWriter.WriteLine(boogieAST.GetRoot());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"VeriSol translation error: {e.Message}");
                return(false);
            }
            return(true);
        }
Exemplo n.º 25
0
        public CompilationJob(ICompilerOutput output, DirectoryInfo outputDir, CompilerOutput outputLanguage, IReadOnlyList <FileInfo> inputFiles,
                              string projectName, DirectoryInfo projectRoot = null, bool generateSourceMaps = false, IReadOnlyList <string> projectDependencies = null,
                              DirectoryInfo aspectjOutputDir = null)
        {
            if (!inputFiles.Any())
            {
                throw new ArgumentException("Must supply at least one input file", nameof(inputFiles));
            }

            Output                 = output;
            OutputDirectory        = outputDir;
            AspectjOutputDirectory = aspectjOutputDir;
            InputFiles             = inputFiles;
            ProjectName            = projectName ?? Path.GetFileNameWithoutExtension(inputFiles[0].FullName);
            ProjectRootPath        = projectRoot;
            LocationResolver       = new DefaultLocationResolver();
            Handler                = new DefaultTranslationErrorHandler(LocationResolver);
            OutputLanguage         = outputLanguage;
            Backend                = TargetLanguage.GetCodeGenerator(outputLanguage);
            GenerateSourceMaps     = generateSourceMaps;
            ProjectDependencies    = projectDependencies ?? new List <string>();
        }
Exemplo n.º 26
0
        private void GetTargetLanguage(FileInfo fullPathName, ref CompilerOutput outputLanguage, ref bool generateSourceMaps)
        {
            XElement projectXml = XElement.Load(fullPathName.FullName);

            if (!projectXml.Elements("Target").Any())
            {
                return;
            }
            switch (projectXml.Element("Target")?.Value.ToLowerInvariant())
            {
            case "c":
                outputLanguage = CompilerOutput.C;
                // check for generate source maps attribute
                try
                {
                    if (projectXml.Element("Target")?.Attributes("sourcemaps").Any() != null)
                    {
                        generateSourceMaps = bool.Parse(projectXml.Element("Target")?.Attribute("sourcemaps")?.Value ?? string.Empty);
                    }
                }
                catch (Exception)
                {
                    throw new CommandlineParsingError($"Expected true or false, received {projectXml.Element("Target")?.Attribute("sourcemaps")?.Value}");
                }
                break;

            case "csharp":
                outputLanguage = CompilerOutput.CSharp;
                break;

            case "rvm":
                outputLanguage = CompilerOutput.Rvm;
                break;

            default:
                throw new CommandlineParsingError($"Expected C or CSharp as target, received {projectXml.Element("Target")?.Value}");
            }
        }
Exemplo n.º 27
0
        public static CommandLineParseResult ParseArguments(IEnumerable <string> args, out CompilationJob job)
        {
            job = null;

            CompilerOutput outputLanguage  = CompilerOutput.C;
            DirectoryInfo  outputDirectory = null;

            List <string>   commandLineFileNames = new List <string>();
            List <FileInfo> inputFiles           = new List <FileInfo>();
            string          targetName           = null;
            bool            generateSourceMaps   = false;

            // enforce the argument prority
            // proj takes priority over everything else and no other arguments should be passed
            if (args.Where(a => a.ToLowerInvariant().Contains("-proj:")).Any() && args.Count() > 1)
            {
                CommandlineOutput.WriteMessage("-proj cannot be combined with other commandline options", SeverityKind.Error);
                return(Failure);
            }

            foreach (string x in args)
            {
                string arg      = x;
                string colonArg = null;
                if (arg[0] == '-')
                {
                    int colonIndex = arg.IndexOf(':');
                    if (colonIndex >= 0)
                    {
                        arg      = x.Substring(0, colonIndex);
                        colonArg = x.Substring(colonIndex + 1);
                    }

                    switch (arg.Substring(1).ToLowerInvariant())
                    {
                    case "t":
                    case "target":
                        if (colonArg == null)
                        {
                            CommandlineOutput.WriteMessage("Missing target name", SeverityKind.Error);
                        }
                        else if (targetName == null)
                        {
                            targetName = colonArg;
                        }
                        else
                        {
                            CommandlineOutput.WriteMessage("Only one target must be specified", SeverityKind.Error);
                        }

                        break;

                    case "g":
                    case "generate":
                        switch (colonArg?.ToLowerInvariant())
                        {
                        case null:
                            CommandlineOutput.WriteMessage(
                                "Missing generation argument, expecting generate:[C,Coyote]", SeverityKind.Error);
                            return(Failure);

                        case "c":
                            outputLanguage = CompilerOutput.C;
                            break;

                        case "coyote":
                            outputLanguage = CompilerOutput.Coyote;
                            break;

                        default:
                            CommandlineOutput.WriteMessage(
                                $"Unrecognized generate option '{colonArg}', expecting C or Coyote",
                                SeverityKind.Error);
                            return(Failure);
                        }

                        break;

                    case "o":
                    case "outputdir":
                        if (colonArg == null)
                        {
                            CommandlineOutput.WriteMessage("Must supply path for output directory",
                                                           SeverityKind.Error);
                            return(Failure);
                        }

                        outputDirectory = Directory.CreateDirectory(colonArg);
                        break;

                    case "proj":
                        if (colonArg == null)
                        {
                            CommandlineOutput.WriteMessage("Must supply project file for compilation",
                                                           SeverityKind.Error);
                            return(Failure);
                        }
                        else
                        {
                            // Parse the project file and generate the compilation job, ignore all other arguments passed
                            if (ParseProjectFile(colonArg, out job))
                            {
                                return(Success);
                            }
                            else
                            {
                                return(Failure);
                            }
                        }

                    case "s":
                    case "sourcemaps":
                        switch (colonArg?.ToLowerInvariant())
                        {
                        case null:
                        case "true":
                            generateSourceMaps = true;
                            break;

                        case "false":
                            generateSourceMaps = false;
                            break;

                        default:
                            CommandlineOutput.WriteMessage(
                                "sourcemaps argument must be either 'true' or 'false'", SeverityKind.Error);
                            return(Failure);
                        }

                        break;

                    case "h":
                    case "help":
                    case "-help":
                        return(HelpRequested);

                    default:
                        commandLineFileNames.Add(arg);
                        CommandlineOutput.WriteMessage($"Unknown Command {arg.Substring(1)}", SeverityKind.Error);
                        return(Failure);
                    }
                }
                else
                {
                    commandLineFileNames.Add(arg);
                }
            }

            // We are here so no project file supplied lets create a compilation job with other arguments

            // Each command line file name must be a legal P file name
            foreach (string inputFileName in commandLineFileNames)
            {
                if (IsLegalPFile(inputFileName, out FileInfo fullPathName))
                {
                    inputFiles.Add(fullPathName);
                }
                else
                {
                    CommandlineOutput.WriteMessage(
                        $"Illegal P file name {inputFileName} or file {fullPathName.FullName} not found", SeverityKind.Error);
                }
            }

            if (inputFiles.Count == 0)
            {
                CommandlineOutput.WriteMessage("At least one .p file must be provided", SeverityKind.Error);
                return(Failure);
            }

            string projectName = targetName ?? Path.GetFileNameWithoutExtension(inputFiles[0].FullName);

            if (!IsLegalUnitName(projectName))
            {
                CommandlineOutput.WriteMessage($"{projectName} is not a legal project name", SeverityKind.Error);
                return(Failure);
            }

            if (outputDirectory == null)
            {
                outputDirectory = new DirectoryInfo(Directory.GetCurrentDirectory());
            }

            job = new CompilationJob(output: new DefaultCompilerOutput(outputDirectory), outputLanguage: outputLanguage, inputFiles: inputFiles, projectName: projectName, generateSourceMaps: generateSourceMaps);
            return(Success);
        }
Exemplo n.º 28
0
        private static bool ParseProjectFile(string projectFile, out CompilationJob job)
        {
            job = null;
            if (!IsLegalPProjFile(projectFile, out FileInfo fullPathName))
            {
                CommandlineOutput.WriteMessage(
                    $"Illegal P project file name {projectFile} or file {fullPathName?.FullName} not found", SeverityKind.Error);
                return(false);
            }

            CommandlineOutput.WriteMessage($".... Parsing the project file: {projectFile}", SeverityKind.Info);

            CompilerOutput  outputLanguage     = CompilerOutput.C;
            DirectoryInfo   outputDirectory    = null;
            List <FileInfo> inputFiles         = new List <FileInfo>();
            string          targetName         = null;
            bool            generateSourceMaps = false;

            XElement projectXML = XElement.Load(fullPathName.FullName);

            // get all files to be compiled

            foreach (XElement inputs in projectXML.Elements("InputFiles"))
            {
                foreach (XElement inputFileName in inputs.Elements("PFile"))
                {
                    var pFiles = new List <string>();

                    if (Directory.Exists(inputFileName.Value))
                    {
                        foreach (var files in Directory.GetFiles(inputFileName.Value, "*.p"))
                        {
                            pFiles.Add(files);
                        }
                    }
                    else
                    {
                        pFiles.Add(inputFileName.Value);
                    }

                    foreach (var pFile in pFiles)
                    {
                        if (IsLegalPFile(pFile, out FileInfo pFilePathName))
                        {
                            CommandlineOutput.WriteMessage($"....... project includes: {pFilePathName.FullName}", SeverityKind.Info);
                            inputFiles.Add(pFilePathName);
                        }
                        else
                        {
                            CommandlineOutput.WriteMessage(
                                $"Illegal P file name {pFile} or file {pFilePathName?.FullName} not found", SeverityKind.Error);
                        }
                    }
                }
            }

            if (inputFiles.Count == 0)
            {
                CommandlineOutput.WriteMessage("At least one .p file must be provided as input files", SeverityKind.Error);
                return(false);
            }

            // get target file name
            if (projectXML.Elements("TargetFileName").Any())
            {
                targetName = projectXML.Element("TargetFileName").Value;
                if (!IsLegalUnitName(targetName))
                {
                    CommandlineOutput.WriteMessage($"{targetName} is not a legal target file name", SeverityKind.Error);
                    return(false);
                }
            }

            string projectName = targetName ?? Path.GetFileNameWithoutExtension(inputFiles[0].FullName);

            // get output directory
            outputDirectory = projectXML.Elements("OutputDir").Any() ? Directory.CreateDirectory(projectXML.Element("OutputDir").Value) : new DirectoryInfo(Directory.GetCurrentDirectory());

            // get target language
            if (projectXML.Elements("Target").Any())
            {
                switch (projectXML.Element("Target").Value.ToLowerInvariant())
                {
                case "c":
                    outputLanguage = CompilerOutput.C;
                    // check for generate source maps attribute
                    try
                    {
                        if (projectXML.Element("Target").Attributes("sourcemaps").Any())
                        {
                            generateSourceMaps = bool.Parse(projectXML.Element("Target").Attribute("sourcemaps").Value);
                        }
                    }
                    catch (Exception)
                    {
                        CommandlineOutput.WriteMessage($"Expected true or false, received {projectXML.Element("Target").Attribute("sourcemaps").Value}", SeverityKind.Error);
                    }
                    break;

                case "p#":
                    outputLanguage = CompilerOutput.PSharp;
                    break;

                default:
                    outputLanguage = CompilerOutput.C;
                    break;
                }
            }

            job = new CompilationJob(output: new DefaultCompilerOutput(outputDirectory), outputLanguage: outputLanguage, inputFiles: inputFiles, projectName: projectName, generateSourceMaps: generateSourceMaps);
            return(true);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Parse the commandline arguments to construct the compilation job
        /// </summary>
        /// <param name="args">Commandline arguments</param>
        /// <param name="job">Generated Compilation job</param>
        /// <returns></returns>
        internal bool ParseCommandLineOptions(IEnumerable <string> args, out CompilationJob job)
        {
            string         targetName      = null;
            CompilerOutput outputLanguage  = CompilerOutput.CSharp;
            DirectoryInfo  outputDirectory = null;

            List <FileInfo> inputFiles = new List <FileInfo>();

            job = null;
            try
            {
                foreach (string x in args)
                {
                    string arg      = x;
                    string colonArg = null;
                    if (arg[0] == '-')
                    {
                        int colonIndex = arg.IndexOf(':');
                        if (colonIndex >= 0)
                        {
                            arg      = x.Substring(0, colonIndex);
                            colonArg = x.Substring(colonIndex + 1);
                        }

                        switch (arg.Substring(1).ToLowerInvariant())
                        {
                        case "t":
                        case "target":
                            if (colonArg == null)
                            {
                                throw new CommandlineParsingError("Missing target project name (-t:<project name>)");
                            }
                            else if (targetName == null)
                            {
                                targetName = colonArg;
                            }
                            else
                            {
                                throw new CommandlineParsingError("Only one target must be specified with (-t)");
                            }
                            break;

                        case "g":
                        case "generate":
                            switch (colonArg?.ToLowerInvariant())
                            {
                            case null:
                                throw new CommandlineParsingError("Missing generation argument, expecting generate:[C,CSharp,RVM]");

                            case "c":
                                outputLanguage = CompilerOutput.C;
                                break;

                            case "csharp":
                                outputLanguage = CompilerOutput.CSharp;
                                break;

                            case "rvm":
                                outputLanguage = CompilerOutput.Rvm;
                                break;

                            default:
                                throw new CommandlineParsingError($"Unrecognized generate option '{colonArg}', expecting C or CSharp");
                            }
                            break;

                        case "o":
                        case "outputdir":
                            if (colonArg == null)
                            {
                                throw new CommandlineParsingError("Must supply path for output directory (-o:<output directory>)");
                            }
                            outputDirectory = Directory.CreateDirectory(colonArg);
                            break;

                        default:
                            CommandLineOptions.PrintUsage();
                            throw new CommandlineParsingError($"Illegal Command {arg.Substring(1)}");
                        }
                    }
                    else
                    {
                        if (IsLegalPFile(arg, out FileInfo fullPathName))
                        {
                            inputFiles.Add(fullPathName);
                        }
                        else
                        {
                            throw new CommandlineParsingError($"Illegal P file name {arg} or file {fullPathName.FullName} not found");
                        }
                    }
                }

                if (inputFiles.Count == 0)
                {
                    commandlineOutput.WriteError("At least one .p file must be provided");
                    return(false);
                }

                string projectName = targetName ?? Path.GetFileNameWithoutExtension(inputFiles[0].FullName);
                if (!IsLegalProjectName(projectName))
                {
                    commandlineOutput.WriteError($"{projectName} is not a legal project name");
                    return(false);
                }

                if (outputDirectory == null)
                {
                    outputDirectory = new DirectoryInfo(Directory.GetCurrentDirectory());
                }

                job = new CompilationJob(output: new DefaultCompilerOutput(outputDirectory), outputDirectory, outputLanguage: outputLanguage, inputFiles: inputFiles, projectName: projectName, outputDirectory);
                commandlineOutput.WriteInfo($"----------------------------------------");
                return(true);
            }
            catch (CommandlineParsingError ex)
            {
                commandlineOutput.WriteError($"<Error parsing commandline>:\n {ex.Message}");
                return(false);
            }
            catch (Exception other)
            {
                commandlineOutput.WriteError($"<Internal Error>:\n {other.Message}\n <Please report to the P team ([email protected]) or create an issue on GitHub, Thanks!>");
                return(false);
            }
        }
Exemplo n.º 30
0
 public static ICodeGenerator GetCodeGenerator(CompilerOutput languageName)
 {
     return(BackendMap[languageName]);
 }
Exemplo n.º 31
0
 private static void RegisterCodeGenerator(CompilerOutput name, ICodeGenerator generator)
 {
     BackendMap[name] = generator;
 }
Exemplo n.º 32
0
 /// <summary>
 ///     Box a new compile runner
 /// </summary>
 /// <param name="compilerOutput"></param>
 /// <param name="inputFiles">The P source files to compile</param>
 public CompileOnlyRunner(CompilerOutput compilerOutput, IReadOnlyList <FileInfo> inputFiles)
 {
     this.inputFiles     = inputFiles;
     this.compilerOutput = compilerOutput;
 }
Exemplo n.º 33
0
        private int TestPc(
            TestConfig config,
            TextWriter tmpWriter,
            DirectoryInfo workDirectory,
            string activeDirectory,
            CompilerOutput outputLanguage)
        {
            List <string> pFiles = workDirectory.EnumerateFiles("*.p").Select(pFile => pFile.FullName).ToList();

            if (!pFiles.Any())
            {
                throw new Exception("no .p file found in test directory");
            }

            string inputFileName = pFiles.First();
            string linkFileName  = Path.ChangeExtension(inputFileName, ".4ml");

            var compilerOutput = new CompilerTestOutputStream(tmpWriter);
            var compileArgs    = new CommandLineOptions
            {
                inputFileNames = new List <string>(pFiles),
                shortFileNames = true,
                outputDir      = workDirectory.FullName,
                unitName       = linkFileName,
                //liveness = LivenessOption.None,
                liveness = outputLanguage == CompilerOutput.Zing && config.Arguments.Contains("/liveness")
                    ? LivenessOption.Standard
                    : LivenessOption.None,
                compilerOutput = outputLanguage
            };

            // Compile
            if (!PCompiler.Value.Compile(compilerOutput, compileArgs))
            //if (!PCompilerService.Value.Compile(compilerOutput, compileArgs))
            {
                tmpWriter.WriteLine("EXIT: -1");
                return(-1);
            }

            //(TODO)Skip the link step if outputLanguage == CompilerOutput.CSharp?
            // Link
            compileArgs.dependencies.Add(linkFileName);
            compileArgs.inputFileNames.Clear();

            if (config.Link != null)
            {
                compileArgs.inputFileNames.Add(Path.Combine(activeDirectory, config.Link));
            }

            if (!PCompiler.Value.Link(compilerOutput, compileArgs))
            //if(!PCompilerService.Value.Link(compilerOutput, compileArgs))
            {
                tmpWriter.WriteLine("EXIT: -1");
                return(-1);
            }
            else
            {
                tmpWriter.WriteLine("EXIT: 0");
            }
            return(0);
        }
Exemplo n.º 34
0
        // This method runs within a thread to compile code
        static void threadedFunction(string code)
        {
            //Thread.Sleep(1000);

            try{
                compilerOutput_global = evaluateCode (code);
            }catch(Exception ex){
                //System.Console.WriteLine("Caught: " + ex.ToString());

            }
        }
Exemplo n.º 35
0
        public static void Main(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Usage: SolToBoogie <relative path to filename.sol> <workingdir> <relative path to outfile.bpl> [options]");
                Console.WriteLine("\t Options:");
                Console.WriteLine("\t\t /break: Opens the debugger");
                Console.WriteLine("\t\t /ignoreMethod:<method>@<contract>: Ignores translation of the method within contract, and only generates a declaration");
                Console.WriteLine("\t\t\t\t multiple such pairs can be specified, ignored set is the union");
                Console.WriteLine("\t\t\t\t a wild card '*' can be used for method, would mean all the methods of the contract");
                Console.WriteLine("\t\t /noInlineAttrs: do not generate any {:inline x} attributes, to speed Corral");
                return;
            }

            string filePath         = Path.Combine(Directory.GetCurrentDirectory(), args[0]);
            string workingDirectory = args[1];
            string outFile          = Path.Combine(Directory.GetCurrentDirectory(), args[2]);

            string           solcName       = GetSolcNameByOSPlatform();
            string           solcPath       = Path.Combine(workingDirectory, "Tool", solcName);
            SolidityCompiler compiler       = new SolidityCompiler();
            CompilerOutput   compilerOutput = compiler.Compile(solcPath, filePath);
            HashSet <Tuple <string, string> > ignoredMethods = new HashSet <Tuple <string, string> >();

            // Issue with run_verisol_win.cmd it passes "/ignoreMethod:a@b /ignoreMethod:c@d .." as a single string
            var splitArgs = new List <string>();

            args.Select(arg => arg.Split(" "))
            .ToList()
            .ForEach(a => a.ToList().ForEach(b => splitArgs.Add(b)));

            if (splitArgs.Any(x => x.Equals("/break")))
            {
                Debugger.Launch();
            }
            foreach (var arg in splitArgs.Where(x => x.StartsWith("/ignoreMethod:")))
            {
                Debug.Assert(arg.Contains("@"), $"Error: incorrect use of /ignoreMethod in {arg}");
                Debug.Assert(arg.LastIndexOf("@") == arg.IndexOf("@"), $"Error: incorrect use of /ignoreMethod in {arg}");
                var str      = arg.Substring("/ignoreMethod:".Length);
                var method   = str.Substring(0, str.IndexOf("@"));
                var contract = str.Substring(str.IndexOf("@") + 1);
                ignoredMethods.Add(Tuple.Create(method, contract));
            }
            Console.WriteLine($"Ignored method/contract pairs ==> \n\t {string.Join(",", ignoredMethods.Select(x => x.Item1 + "@" + x.Item2))}");

            bool genInlineAttributesInBpl = true;

            if (splitArgs.Any(x => x.Equals("/noInlineAttrs")))
            {
                genInlineAttributesInBpl = false;
            }

            if (compilerOutput.ContainsError())
            {
                PrintErrors(compilerOutput.Errors);
                throw new SystemException("Compilation Error");
            }
            else
            {
                AST solidityAST = new AST(compilerOutput, Path.GetDirectoryName(filePath));

                try
                {
                    BoogieTranslator translator = new BoogieTranslator();
                    BoogieAST        boogieAST  = translator.Translate(solidityAST, ignoredMethods, genInlineAttributesInBpl);

                    using (var outWriter = new StreamWriter(outFile))
                    {
                        outWriter.WriteLine(boogieAST.GetRoot());
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Verisol translation exception: {e.Message}");
                }
            }
        }
Exemplo n.º 36
0
        // This method accepts a string which contains CSharp code then calls another functions to evaluate and execute the code
        // Output of this function is a string in JSON format
        public string compileCode(string code)
        {
            CompilerOutput result = new CompilerOutput();
            if (isDangerousCode (code)) {
                result.errors = "Possible dangerous code";
            } else if (code.Length >= code_input_limit_global) {
                result.errors = "Due to server limits, we have restricted code size to " + code_input_limit_global + " characters.";
            }else {
                result = run (code);
            }

            string jsontmp = toJSON (result);
            return jsontmp;
        }