Ejemplo n.º 1
0
        public override void Run(List <ExpressionSharpnode> arguments, SyntaxNode originalNode, TranslationContext context)
        {
            AddReceiverToList(arguments);
            var expressions = ConvertToSilver(arguments, context);

            // Determine what argument corresponds to what action - there are three scenarios
            Silvernode dropAmount = "";
            Silvernode takeAmount = "";

            if (this._doTake && this._doDrop)
            {
                takeAmount = expressions[2];
                dropAmount = expressions[1];
            }
            else if (this._doTake)
            {
                takeAmount = expressions[1];
            }
            else if (this._doDrop)
            {
                dropAmount = expressions[1];
            }
            else
            {
                throw new Exception("Never happens.");
            }
            this.Silvernode = new SimpleSequenceSilvernode(originalNode,
                                                           expressions[0],
                                                           "[",
                                                           dropAmount,
                                                           "..",
                                                           takeAmount,
                                                           "]"
                                                           );
        }
        public override TranslationResult Translate(TranslationContext context)
        {
            Silvernode sn = null;

            switch (this.kind)
            {
            case LiteralKind.Boolean:
                sn = this.booleanValue ? new TextSilvernode("true", this.OriginalNode) : new TextSilvernode("false", this.OriginalNode);
                break;

            case LiteralKind.Int32:
                sn = new TextSilvernode(this.integerValue.ToString(), this.OriginalNode);
                break;

            case LiteralKind.Null:
                sn = new TextSilvernode("null", this.OriginalNode);
                break;
            }
            if (sn != null)
            {
                return(TranslationResult.FromSilvernode(sn));
            }
            else
            {
                return(TranslationResult.Error(this.OriginalNode, Diagnostics.SSIL101_UnknownNode, this.OriginalNode.Kind()));
            }
        }
Ejemplo n.º 3
0
        private static SyntaxNode GetSyntaxNodeFromCodePosition(string codePosition, Silvernode originalCode)
        {
            Match m = regexCodePosition.Match(codePosition);

            if (m.Success)
            {
                // ReSharper disable once UnusedVariable
                string codefile     = m.Groups[1].Value;
                string lineString   = m.Groups[2].Value;
                string columnString = m.Groups[3].Value;
                int    line         = Int32.Parse(lineString);   // < Silver line
                int    column       = Int32.Parse(columnString); // < Silver column

                string   silvercode = originalCode.ToString();
                string[] lines      = silvercode.Split('\n');
                int      position   = 0; // < Let's count the position from the start of the text
                for (int i = 0; i < line - 1; i++)
                {
                    position += lines[i].Length + 1;
                }
                position += column - 1;
                SyntaxNode syntaxNode = originalCode.GetSyntaxNodeFromOffset(position);
                return(syntaxNode);
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Converts the standard output of a backend verifier to a list of verification errors.
        /// </summary>
        /// <param name="backendToolResult">The output of the verifier.</param>
        /// <param name="originalCode">The master silvernode tree that was passed to the verifier.</param>
        public static List <Error> ConvertErrorMessages(string backendToolResult, Silvernode originalCode)
        {
            List <Error> errors = new List <Error>();
            bool         noErrorsFoundLineFound = false;

            foreach (string line in backendToolResult.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
            {
                foreach (Regex r in harmlessLines)
                {
                    if (r.IsMatch(line))
                    {
                        goto nextline;
                    }
                }
                if (line.ToLower().Contains("no errors found"))
                {
                    noErrorsFoundLineFound = true;
                    goto nextline;
                }
                if (line.Contains("Parse error"))
                {
                    // Parse error has different format, special case.
                    Match m = regexParseError.Match(line);
                    if (m.Success)
                    {
                        var errorText    = m.Groups[1].Value;
                        var codePosition = m.Groups[2].Value;
                        errors.Add(new Error(Diagnostics.SSIL203_ParseError, GetSyntaxNodeFromCodePosition(codePosition, originalCode),
                                             errorText));
                        continue;
                    }
                }
                else
                {
                    var matches = regexCodePosition.Matches(line);
                    if (matches.Count > 0)
                    {
                        var errorText = line.Trim();
                        foreach (Match m in matches)
                        {
                            var codePosition = m.Value;
                            errors.Add(new Error(Diagnostics.SSIL204_OtherLocalizedError, GetSyntaxNodeFromCodePosition(codePosition, originalCode),
                                                 errorText));
                        }
                    }
                    else
                    {
                        errors.Add(new Error(Diagnostics.SSIL202_BackendUnknownLine, null, line.Trim()));
                    }
                }
                nextline :;
            }
            if (!noErrorsFoundLineFound && errors.Count == 0)
            {
                errors.Add(new Error(Diagnostics.SSIL205_NoErrorsFoundLineNotFound, null));
            }

            return(errors);
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Creates Viper text that reads an element of an array.
 /// </summary>
 /// <param name="originalNode">The Roslyn node that represents an array read.</param>
 /// <param name="containerSilvernode">The array.</param>
 /// <param name="indexSilvernode">The index.</param>
 /// <returns></returns>
 public Silvernode ArrayRead(SyntaxNode originalNode, Silvernode containerSilvernode, Silvernode indexSilvernode)
 {
     return(new SimpleSequenceSilvernode(originalNode,
                                         IntegerArrayRead + "(",
                                         containerSilvernode,
                                         ", ",
                                         indexSilvernode,
                                         ")"));
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Creates Viper text that changes an element of an arrray.
 /// </summary>
 /// <param name="originalNode">The Roslyn node that represents an array write. </param>
 /// <param name="container">The array.</param>
 /// <param name="index">The index.</param>
 /// <param name="value">The new value of container[index].</param>
 /// <returns></returns>
 public SimpleSequenceStatementSilvernode ArrayWrite(SyntaxNode originalNode, Silvernode container, Silvernode index, Silvernode value)
 {
     return(new SimpleSequenceStatementSilvernode(originalNode,
                                                  IntegerArrayWrite + "(",
                                                  container,
                                                  ", ",
                                                  index,
                                                  ", ",
                                                  value,
                                                  ")"));
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Creates a translation result from the specified node and a list of errors.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <param name="errors">The errors. If null, then no errors occurred.</param>
        /// <returns></returns>
        public static TranslationResult FromSilvernode(Silvernode node, IEnumerable <Error> errors = null)
        {
            // ReSharper disable once UseObjectOrCollectionInitializer
            TranslationResult result = new TranslationResult();

            result.Silvernode = node;
            if (errors != null)
            {
                result.Errors.AddRange(errors);
            }
            return(result);
        }
Ejemplo n.º 8
0
        public VerificationResult Verify(Silvernode silvernode)
        {
            if (!nailgunInitialized)
            {
                // Start Nailgun server.
                ReadyNailgun();
                nailgunInitialized = true;
            }

            string silvercode = silvernode.ToString();
            string filename   = Path.GetTempFileName();

            File.WriteAllText(filename, silvercode);
            try
            {
                // Run the nailgun client, catch the output.
                Process p = new Process
                {
                    StartInfo =
                    {
                        UseShellExecute        = false,
                        RedirectStandardOutput = true,
                        CreateNoWindow         = true,
                        RedirectStandardError  = true
                    }
                };
                var enviromentPath = Environment.GetEnvironmentVariable("PATH");
                Debug.Assert(enviromentPath != null, "enviromentPath != null");
                var paths   = enviromentPath.Split(';');
                var exePath = paths
                              .Select(x => Path.Combine(x, "ng.exe"))
                              .FirstOrDefault(File.Exists) ?? "ng.exe";
                p.StartInfo.FileName = exePath;
                // Runner class is the class that operates the verifier (programmed in Scala).
                p.StartInfo.Arguments = _runnerClass + " \"" + filename + "\"";
                p.Start();
                string output = p.StandardOutput.ReadToEnd();
                p.WaitForExit();
                VerificationResult r = new VerificationResult
                {
                    OriginalOutput = output,
                    Errors         = BackendUtils.ConvertErrorMessages(output, silvernode)
                };
                return(r);
            }
            catch (Exception)
            {
                return(VerificationResult.Error(new Error(Diagnostics.SSIL201_BackendNotFound, null, "ng.exe")));
            }
        }
Ejemplo n.º 9
0
        public VerificationResult Verify(Silvernode silvernode)
        {
            string silvercode = silvernode.ToString();
            string filename   = Path.GetTempFileName();

            File.WriteAllText(filename, silvercode);
            try
            {
                // Find and run "silicon.bat" in PATH and catch the output
                Process p = new Process
                {
                    StartInfo =
                    {
                        UseShellExecute        = false,
                        RedirectStandardOutput = true,
                        CreateNoWindow         = true
                    }
                };
                p.StartInfo.RedirectStandardOutput = true;
                var enviromentPath = Environment.GetEnvironmentVariable("PATH");
                Debug.Assert(enviromentPath != null, "enviromentPath != null");
                var paths   = enviromentPath.Split(';');
                var exePath = paths
                              .Select(x => Path.Combine(x, "silicon.bat"))
                              .FirstOrDefault(File.Exists) ?? "silicon.bat";
                p.StartInfo.FileName  = exePath;
                p.StartInfo.Arguments = "\"" + filename + "\"";
                p.Start();

                string             output = p.StandardOutput.ReadToEnd();
                VerificationResult r      = new VerificationResult
                {
                    OriginalOutput = output,
                    Errors         = BackendUtils.ConvertErrorMessages(output, silvernode)
                };
                return(r);
            }
            catch (Exception)
            {
                return(VerificationResult.Error(new Error(Diagnostics.SSIL201_BackendNotFound, null, "silicon.bat")));
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Prepares for insertion into quantifier.
        /// Returns true if this lambda expression is valid for translation inside a ForAll or Exists call; false otherwise.
        /// </summary>
        /// <param name="context">The context.</param>
        public bool PrepareForInsertionIntoQuantifier(TranslationContext context)
        {
            if (this.errorneousResult != null)
            {
                this.failedResult = TranslationResult.Error(this.errorneousResult.Node, this.errorneousResult.Diagnostic, this.errorneousResult.DiagnosticArguments);
                return(false);
            }

            // Translate the single parameter's type
            var parameterSymbol = context.Semantics.GetDeclaredSymbol(this.parameter.ParameterSyntax);

            this.VariableIdentifier = context.Process.IdentifierTranslator.RegisterAndGetIdentifier(parameterSymbol);
            this.VariableSilverType = TypeTranslator.TranslateType(parameterSymbol.Type, this.parameter.OriginalNode,
                                                                   out this.errorneousResult);
            if (this.errorneousResult != null)
            {
                this.failedResult = TranslationResult.Error(this.errorneousResult.Node, this.errorneousResult.Diagnostic, this.errorneousResult.DiagnosticArguments);
                return(false);
            }

            // Translate the lambda's body
            TranslationResult res = this.body.Translate(context.ChangePurityContext(PurityContext.PureOrFail));

            if (res.WasTranslationSuccessful)
            {
                this.BodySilvernode = res.Silvernode;
            }
            else
            {
                this.failedResult = res;
                return(false);
            }

            // Nothing went wrong.
            return(true);
        }
Ejemplo n.º 11
0
 public TranslationProcessResult(Silvernode silvernode, List <Error> errors)
 {
     this.Silvernode = silvernode;
     this.Errors     = errors;
 }
        public override TranslationResult Translate(TranslationContext context)
        {
            // Get symbol from semantic analysis
            var method       = context.Semantics.GetSymbolInfo(this.MethodGroup);
            var methodSymbol = method.Symbol as IMethodSymbol;

            if (methodSymbol == null)
            {
                return(TranslationResult.Error(this.OriginalNode, Diagnostics.SSIL123_ThereIsThisCSharpError,
                                               "This name cannot be unambiguously mapped to a single method."));
            }
            var methodName = methodSymbol.GetQualifiedName();

            // There are many special cases where we don't want to translate a method call as a Viper method or function call
            // Each case is a subclass of InvocationTranslation. See InvocationTranslation for details.
            // These special cases all concern invocation targets within Soothsharp.Contracts and are translated into
            // keyworded Viper constructs
            InvocationTranslation translationStyle;

            switch (methodName)
            {
            case ContractsTranslator.ContractEnsures:
            case ContractsTranslator.ContractRequires:
            case ContractsTranslator.ContractInvariant:
                translationStyle = new InvocationContract(methodName);
                break;

            case ContractsTranslator.Implication:
                translationStyle = new InvocationImplicationEquivalence("==>", this.MethodGroup);
                break;

            case ContractsTranslator.Equivalence:
                translationStyle = new InvocationImplicationEquivalence("<==>", this.MethodGroup);
                break;

            case ContractsTranslator.ForAll:
                translationStyle = new InvocationQuantifier(QuantifierKind.ForAll);
                break;

            case ContractsTranslator.Exists:
                translationStyle = new InvocationQuantifier(QuantifierKind.Exists);
                break;

            case ContractsTranslator.ContractAssert:
                translationStyle = new InvocationPhpStatement("assert");
                break;

            case ContractsTranslator.ContractAssume:
                translationStyle = new InvocationPhpStatement("assume");
                break;

            case ContractsTranslator.ContractInhale:
                translationStyle = new InvocationPhpStatement("inhale");
                break;

            case ContractsTranslator.ContractExhale:
                translationStyle = new InvocationPhpStatement("exhale");
                break;

            case ContractsTranslator.ContractAcc:
                translationStyle = new InvocationViperBuiltInFunction("acc", false);
                break;

            case ContractsTranslator.ContractAccArray:
                translationStyle = new InvocationAccArray();
                break;

            case ContractsTranslator.Old:
                translationStyle = new InvocationViperBuiltInFunction("old", false);
                break;

            case ContractsTranslator.Fold:
                translationStyle = new InvocationPhpStatement("fold");
                break;

            case ContractsTranslator.Unfold:
                translationStyle = new InvocationPhpStatement("unfold");
                break;

            case ContractsTranslator.PermissionCreate:
                translationStyle = new InvocationPermissionCreate();
                break;

            case ContractsTranslator.PermissionFromLocation:
                translationStyle = new InvocationViperBuiltInFunction("perm", false);
                break;

            case SeqTranslator.Contains:
                translationStyle = new InvocationSeqContains(this.MethodGroup, this.methodGroupSharpnode);
                break;

            case SeqTranslator.Drop:
                translationStyle = new InvocationSeqTakeDrop(false, true, this.MethodGroup, this.methodGroupSharpnode);
                break;

            case SeqTranslator.Take:
                translationStyle = new InvocationSeqTakeDrop(true, false, this.MethodGroup, this.methodGroupSharpnode);
                break;

            case SeqTranslator.TakeDrop:
                translationStyle = new InvocationSeqTakeDrop(true, true, this.MethodGroup, this.methodGroupSharpnode);
                break;

            case ContractsTranslator.Result:
                translationStyle = new InvocationResult();
                break;

            case ContractsTranslator.Folding:
                translationStyle = new InvocationFoldingUnfolding(true);
                break;

            case ContractsTranslator.Unfolding:
                translationStyle = new InvocationFoldingUnfolding(false);
                break;

            default:
                // Standard case
                translationStyle = new InvocationStandardMethod(this.MethodGroup, this.methodGroupSharpnode, method);
                break;
            }

            // Perform the translation
            translationStyle.Run(this.Arguments, this.OriginalNode, context);

            // Get the result
            Silvernode silvernode = translationStyle.Silvernode;

            TranslationResult result = TranslationResult.FromSilvernode(silvernode,
                                                                        translationStyle.Errors).AndPrepend(translationStyle.Prependors.ToArray());

            // Maybe prepending is required.
            translationStyle.PostprocessPurity(result, context);
            return(result);
        }