|
| 1 | +//----------------------------------------------------------------------------- |
| 2 | +// |
| 3 | +// Copyright by the contributors to the Dafny Project |
| 4 | +// SPDX-License-Identifier: MIT |
| 5 | +// |
| 6 | +//----------------------------------------------------------------------------- |
| 7 | + |
| 8 | +#nullable enable |
| 9 | + |
| 10 | +using System; |
| 11 | +using System.Collections.Generic; |
| 12 | +using System.Linq; |
| 13 | +using System.Numerics; |
| 14 | +using System.Diagnostics.Contracts; |
| 15 | +using Microsoft.BaseTypes; |
| 16 | +using Microsoft.Boogie; |
| 17 | + |
| 18 | +namespace Microsoft.Dafny.Compilers { |
| 19 | + public class ExtractorError : Exception { |
| 20 | + public ExtractorError(string message) |
| 21 | + : base(message) { |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + public class BoogieExtractor : ASTVisitor<IASTVisitorContext> { |
| 26 | + /// <summary> |
| 27 | + /// Says to look inside the module for contents to extract. |
| 28 | + /// Can be applied to a module. |
| 29 | + /// |
| 30 | + /// Note: This attribute isn't used yet, so the use of the attribute is just a stylistic thing at the moment. |
| 31 | + /// Similarly, one can imagine that the extractor will look at a module's export clauses, to--in some way--check that |
| 32 | + /// the set of Boogie declarations exported are self consistent. But that isn't done yet, either. Instead, all contents |
| 33 | + /// of all files given to the extractor are considered for extraction. |
| 34 | + /// </summary> |
| 35 | + private const string ExtractAttribute = "extract_boogie"; |
| 36 | + |
| 37 | + /// <summary> |
| 38 | + /// Gives the Boogie name to be used in the extraction. |
| 39 | + /// Can be applied to types and functions. |
| 40 | + /// </summary> |
| 41 | + private const string NameAttribute = "extract_boogie_name"; |
| 42 | + |
| 43 | + /// <summary> |
| 44 | + /// Says to place the extracted axiom declaration in the "uses" block of the given function. |
| 45 | + /// Can be applied to lemmas. |
| 46 | + /// </summary> |
| 47 | + private const string UsedByAttribute = "extract_used_by"; |
| 48 | + |
| 49 | + /// <summary> |
| 50 | + /// Gives a matching pattern to be applied in the quantifier emitted from a lemma or from a quantifier. |
| 51 | + /// Can be applied to lemmas and quantifiers. |
| 52 | + /// </summary> |
| 53 | + private const string PatternAttribute = "extract_pattern"; |
| 54 | + |
| 55 | + /// <summary> |
| 56 | + /// Specifies an additional attribute to be attached to the quantifier emitted from a lemma. |
| 57 | + /// Can be applied to lemmas. |
| 58 | + /// </summary> |
| 59 | + private const string AttributeAttribute = "extract_attribute"; |
| 60 | + |
| 61 | + /// <summary> |
| 62 | + /// Throws an "ExtractorError" if the input is unexpected or unsupported. |
| 63 | + /// </summary> |
| 64 | + public static Boogie.Program Extract(Program program) { |
| 65 | + var extractor = new BoogieExtractor(); |
| 66 | + extractor.VisitModule(program.DefaultModule); |
| 67 | + extractor.FixUpUsedByInformation(); |
| 68 | + |
| 69 | + var extractedProgram = new Boogie.Program(); |
| 70 | + extractedProgram.AddTopLevelDeclarations(extractor.allDeclarations); |
| 71 | + return extractedProgram; |
| 72 | + } |
| 73 | + |
| 74 | + private List<Boogie.Declaration> declarations = new(); // for the current module |
| 75 | + private List<Boogie.Declaration> allDeclarations = new(); // these are the declarations for all modules marked with {:extract} |
| 76 | + private readonly Dictionary<Function, Boogie.Function> functionExtractions = new(); |
| 77 | + private readonly List<(Boogie.Axiom, Function)> axiomUsedBy = new(); |
| 78 | + |
| 79 | + private BoogieExtractor() { |
| 80 | + } |
| 81 | + |
| 82 | + void FixUpUsedByInformation() { |
| 83 | + foreach (var (axiom, function) in axiomUsedBy) { |
| 84 | + if (!functionExtractions.TryGetValue(function, out var boogieFunction)) { |
| 85 | + throw new ExtractorError($":{UsedByAttribute} attribute mentions non-extracted function: {function.Name}"); |
| 86 | + } |
| 87 | + boogieFunction.OtherDefinitionAxioms.Add(axiom); |
| 88 | + } |
| 89 | + axiomUsedBy.Clear(); |
| 90 | + } |
| 91 | + |
| 92 | + public override IASTVisitorContext GetContext(IASTVisitorContext astVisitorContext, bool inFunctionPostcondition) { |
| 93 | + return astVisitorContext; |
| 94 | + } |
| 95 | + |
| 96 | + void VisitModule(ModuleDecl module) { |
| 97 | + var previousDeclarations = declarations; |
| 98 | + declarations = new(); |
| 99 | + |
| 100 | + VisitDeclarations(module.Signature.TopLevels.Values.ToList()); |
| 101 | + |
| 102 | + if (Attributes.Contains(module.Signature.ModuleDef.Attributes, ExtractAttribute)) { |
| 103 | + declarations.Sort((d0, d1) => d0.tok.pos - d1.tok.pos); |
| 104 | + allDeclarations.AddRange(declarations); |
| 105 | + } |
| 106 | + declarations = previousDeclarations; |
| 107 | + } |
| 108 | + |
| 109 | + protected override void VisitOneDeclaration(TopLevelDecl decl) { |
| 110 | + if (decl is ModuleDecl moduleDecl) { |
| 111 | + VisitModule(moduleDecl); |
| 112 | + return; |
| 113 | + } |
| 114 | + |
| 115 | + if (GetExtractName(decl.Attributes) is { } extractName) { |
| 116 | + var ty = new Boogie.TypeCtorDecl(decl.tok, extractName, decl.TypeArgs.Count); |
| 117 | + declarations.Add(ty); |
| 118 | + } |
| 119 | + |
| 120 | + base.VisitOneDeclaration(decl); // this will visit the declaration's members |
| 121 | + } |
| 122 | + |
| 123 | + public override void VisitMethod(Method method) { |
| 124 | + if (method is not Lemma lemma) { |
| 125 | + return; |
| 126 | + } |
| 127 | + |
| 128 | + var patterns = Attributes.FindAllExpressions(lemma.Attributes, PatternAttribute); |
| 129 | + var usedByInfo = Attributes.Find(lemma.Attributes, UsedByAttribute); |
| 130 | + if (patterns == null && usedByInfo == null) { |
| 131 | + return; |
| 132 | + } |
| 133 | + |
| 134 | + if ((lemma.Ins.Count == 0) != (patterns == null)) { |
| 135 | + throw new ExtractorError($"a parameterized lemma must specify at least one :{PatternAttribute}: {lemma.Name}"); |
| 136 | + } |
| 137 | + if (lemma.TypeArgs.Count != 0) { |
| 138 | + throw new ExtractorError($"an extracted lemma is not allowed to have type parameters: {lemma.Name}"); |
| 139 | + } |
| 140 | + if (lemma.Outs.Count != 0) { |
| 141 | + throw new ExtractorError($"an extracted lemma is not allowed to have out-parameters: {lemma.Name}"); |
| 142 | + } |
| 143 | + |
| 144 | + var tok = lemma.tok; |
| 145 | + |
| 146 | + var boundVars = lemma.Ins.ConvertAll(formal => |
| 147 | + (Boogie.Variable)new Boogie.BoundVariable(tok, new TypedIdent(tok, formal.Name, ExtractType(formal.Type))) |
| 148 | + ); |
| 149 | + |
| 150 | + var triggers = GetTriggers(tok, patterns); |
| 151 | + |
| 152 | + var ante = BoogieGenerator.BplAnd(lemma.Req.ConvertAll(req => ExtractExpr(req.E))); |
| 153 | + var post = BoogieGenerator.BplAnd(lemma.Ens.ConvertAll(ens => ExtractExpr(ens.E))); |
| 154 | + var body = BoogieGenerator.BplImp(ante, post); |
| 155 | + |
| 156 | + Boogie.Expr axiomBody; |
| 157 | + if (boundVars.Count == 0) { |
| 158 | + axiomBody = body; |
| 159 | + } else { |
| 160 | + var kv = GetKeyValues(tok, lemma.Attributes); |
| 161 | + axiomBody = new Boogie.ForallExpr(tok, new List<TypeVariable>(), boundVars, kv, triggers, body); |
| 162 | + } |
| 163 | + var axiom = new Boogie.Axiom(tok, axiomBody); |
| 164 | + declarations.Add(axiom); |
| 165 | + |
| 166 | + if (usedByInfo != null) { |
| 167 | + if (usedByInfo.Args.Count == 1 && usedByInfo.Args[0].Resolved is MemberSelectExpr { Member: Function function }) { |
| 168 | + axiomUsedBy.Add((axiom, function)); |
| 169 | + } else { |
| 170 | + throw new ExtractorError($":{UsedByAttribute} argument on lemma '{lemma.Name}' is expected to be an extracted function"); |
| 171 | + } |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + private Trigger? GetTriggers(IToken tok, List<List<Expression>>? patterns) { |
| 176 | + if (patterns == null) { |
| 177 | + return null; |
| 178 | + } |
| 179 | + |
| 180 | + Boogie.Trigger? triggers = null; |
| 181 | + for (var i = 0; i < patterns.Count; i++) { |
| 182 | + var terms = patterns![i].ConvertAll(ExtractExpr); |
| 183 | + triggers = new Boogie.Trigger(tok, true, terms, triggers); |
| 184 | + } |
| 185 | + |
| 186 | + return triggers; |
| 187 | + } |
| 188 | + |
| 189 | + private QKeyValue? GetKeyValues(IToken tok, Attributes attributes) { |
| 190 | + Boogie.QKeyValue kv = null; |
| 191 | + var extractAttributes = Attributes.FindAllExpressions(attributes, AttributeAttribute); |
| 192 | + if (extractAttributes != null) { |
| 193 | + if (extractAttributes.Count == 0) { |
| 194 | + throw new ExtractorError($"first argument to :{AttributeAttribute} is expected to be a literal string; got no arguments"); |
| 195 | + } |
| 196 | + for (var i = extractAttributes.Count; 0 <= --i;) { |
| 197 | + string? attrName = null; |
| 198 | + var parameters = new List<object>(); |
| 199 | + foreach (var argument in extractAttributes[i]) { |
| 200 | + if (attrName != null) { |
| 201 | + parameters.Add(ExtractExpr(argument)); |
| 202 | + } else if (argument is StringLiteralExpr { Value: string name }) { |
| 203 | + attrName = name; |
| 204 | + } else { |
| 205 | + throw new ExtractorError($"first argument to :{AttributeAttribute} is expected to be a literal string; got: {argument}"); |
| 206 | + } |
| 207 | + } |
| 208 | + |
| 209 | + kv = new Boogie.QKeyValue(tok, attrName, parameters, kv); |
| 210 | + } |
| 211 | + } |
| 212 | + |
| 213 | + return kv; |
| 214 | + } |
| 215 | + |
| 216 | + public override void VisitFunction(Function function) { |
| 217 | + if (GetExtractName(function.Attributes) is { } extractName) { |
| 218 | + var tok = function.tok; |
| 219 | + if (function.TypeArgs.Count != 0) { |
| 220 | + throw new ExtractorError($"an extracted function is not allowed to have type parameters: {function.Name}"); |
| 221 | + } |
| 222 | + var inParams = function.Ins.ConvertAll(formal => |
| 223 | + (Boogie.Variable)new Boogie.Formal(tok, new TypedIdent(tok, formal.Name, ExtractType(formal.Type)), true) |
| 224 | + ); |
| 225 | + var result = new Boogie.Formal(tok, new TypedIdent(tok, TypedIdent.NoName, ExtractType(function.ResultType)), false); |
| 226 | + var fn = new Boogie.Function(tok, extractName, inParams, result); |
| 227 | + declarations.Add(fn); |
| 228 | + functionExtractions.Add(function, fn); |
| 229 | + } |
| 230 | + } |
| 231 | + |
| 232 | + private Boogie.Type ExtractType(Type type) { |
| 233 | + switch (type) { |
| 234 | + case IntType: |
| 235 | + return Boogie.Type.Int; |
| 236 | + case BoolType: |
| 237 | + return Boogie.Type.Bool; |
| 238 | + case UserDefinedType udt: { |
| 239 | + var cl = udt.ResolvedClass; |
| 240 | + var name = GetExtractName(cl.Attributes) ?? cl.Name; |
| 241 | + return new Boogie.UnresolvedTypeIdentifier(Boogie.Token.NoToken, name, udt.TypeArgs.ConvertAll(ExtractType)); |
| 242 | + } |
| 243 | + default: |
| 244 | + throw new ExtractorError($"type not supported by extractor: {type}"); |
| 245 | + } |
| 246 | + } |
| 247 | + |
| 248 | + private string? GetExtractName(Attributes attributes) { |
| 249 | + if (Attributes.Find(attributes, NameAttribute) is { } extractNameAttribute) { |
| 250 | + if (extractNameAttribute.Args.Count == 1 && extractNameAttribute.Args[0] is StringLiteralExpr { Value: string extractName }) { |
| 251 | + return extractName; |
| 252 | + } |
| 253 | + } |
| 254 | + return null; |
| 255 | + } |
| 256 | + |
| 257 | + private Boogie.Expr ExtractExpr(Expression expr) { |
| 258 | + expr = expr.Resolved; |
| 259 | + var tok = expr.tok; |
| 260 | + switch (expr) { |
| 261 | + case LiteralExpr literalExpr: { |
| 262 | + if (literalExpr.Value is bool boolValue) { |
| 263 | + // use the specific literals, rather than Boogie.LiteralExpr(bool), in order for the |
| 264 | + // peephole optimizations to kick in |
| 265 | + return boolValue ? Boogie.Expr.True : Boogie.Expr.False; |
| 266 | + } else if (literalExpr.Value is BigInteger intValue) { |
| 267 | + var n = BigNum.FromBigInt(intValue); |
| 268 | + return Boogie.Expr.Literal(n); |
| 269 | + } |
| 270 | + break; |
| 271 | + } |
| 272 | + |
| 273 | + case IdentifierExpr identifierExpr: |
| 274 | + return new Boogie.IdentifierExpr(tok, identifierExpr.Name); |
| 275 | + |
| 276 | + case FunctionCallExpr functionCallExpr: { |
| 277 | + var function = functionCallExpr.Function; |
| 278 | + var functionName = GetExtractName(function.Attributes) ?? function.Name; |
| 279 | + Contract.Assert(function.IsStatic); |
| 280 | + var arguments = functionCallExpr.Args.ConvertAll(ExtractExpr); |
| 281 | + return new Boogie.NAryExpr(tok, new Boogie.FunctionCall(new Boogie.IdentifierExpr(tok, functionName)), arguments); |
| 282 | + } |
| 283 | + |
| 284 | + case BinaryExpr binaryExpr: { |
| 285 | + var e0 = ExtractExpr(binaryExpr.E0); |
| 286 | + var e1 = ExtractExpr(binaryExpr.E1); |
| 287 | + switch (binaryExpr.ResolvedOp) { |
| 288 | + case BinaryExpr.ResolvedOpcode.EqCommon: |
| 289 | + return Boogie.Expr.Eq(e0, e1); |
| 290 | + case BinaryExpr.ResolvedOpcode.NeqCommon: |
| 291 | + return Boogie.Expr.Neq(e0, e1); |
| 292 | + case BinaryExpr.ResolvedOpcode.Iff: |
| 293 | + return BoogieGenerator.BplIff(e0, e1); |
| 294 | + case BinaryExpr.ResolvedOpcode.Imp: |
| 295 | + return BoogieGenerator.BplImp(e0, e1); |
| 296 | + case BinaryExpr.ResolvedOpcode.And: |
| 297 | + return BoogieGenerator.BplAnd(e0, e1); |
| 298 | + case BinaryExpr.ResolvedOpcode.Or: |
| 299 | + return BoogieGenerator.BplOr(e0, e1); |
| 300 | + case BinaryExpr.ResolvedOpcode.Le: |
| 301 | + return Boogie.Expr.Le(e0, e1); |
| 302 | + case BinaryExpr.ResolvedOpcode.Lt: |
| 303 | + return Boogie.Expr.Lt(e0, e1); |
| 304 | + case BinaryExpr.ResolvedOpcode.Add: |
| 305 | + return Boogie.Expr.Add(e0, e1); |
| 306 | + case BinaryExpr.ResolvedOpcode.Sub: |
| 307 | + return Boogie.Expr.Sub(e0, e1); |
| 308 | + default: |
| 309 | + break; |
| 310 | + } |
| 311 | + break; |
| 312 | + } |
| 313 | + |
| 314 | + case UnaryOpExpr unaryOpExpr: |
| 315 | + if (unaryOpExpr.ResolvedOp == UnaryOpExpr.ResolvedOpcode.BoolNot) { |
| 316 | + var e = ExtractExpr(unaryOpExpr.E); |
| 317 | + return Boogie.Expr.Not(e); |
| 318 | + } else { |
| 319 | + throw new ExtractorError($"extractor does not support unary operator {unaryOpExpr.ResolvedOp}"); |
| 320 | + } |
| 321 | + |
| 322 | + case QuantifierExpr quantifierExpr: { |
| 323 | + var boundVars = quantifierExpr.BoundVars.ConvertAll(boundVar => |
| 324 | + (Boogie.Variable)new Boogie.BoundVariable(tok, new TypedIdent(tok, boundVar.Name, ExtractType(boundVar.Type))) |
| 325 | + ); |
| 326 | + |
| 327 | + var patterns = Attributes.FindAllExpressions(quantifierExpr.Attributes, PatternAttribute); |
| 328 | + if (patterns.Count == 0) { |
| 329 | + throw new ExtractorError($"extraction expects every quantifier to specify at least one :{PatternAttribute}"); |
| 330 | + } |
| 331 | + var triggers = GetTriggers(tok, patterns); |
| 332 | + |
| 333 | + var kv = GetKeyValues(tok, quantifierExpr.Attributes); |
| 334 | + var body = ExtractExpr(quantifierExpr.LogicalBody()); |
| 335 | + if (quantifierExpr is ExistsExpr) { |
| 336 | + return new Boogie.ExistsExpr(tok, new List<TypeVariable>(), boundVars, kv, triggers, body); |
| 337 | + } else { |
| 338 | + Contract.Assert(quantifierExpr is ForallExpr); |
| 339 | + return new Boogie.ForallExpr(tok, new List<TypeVariable>(), boundVars, kv, triggers, body); |
| 340 | + } |
| 341 | + } |
| 342 | + |
| 343 | + default: |
| 344 | + break; |
| 345 | + } |
| 346 | + |
| 347 | + throw new ExtractorError($"extraction does not support expression of type {expr.GetType()}: {expr}"); |
| 348 | + } |
| 349 | + } |
| 350 | +} |
0 commit comments