-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathSolverContextFactory.java
375 lines (331 loc) · 13.9 KB
/
SolverContextFactory.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
// This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.function.Consumer;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.sosy_lab.common.NativeLibraries;
import org.sosy_lab.common.ShutdownNotifier;
import org.sosy_lab.common.configuration.Configuration;
import org.sosy_lab.common.configuration.FileOption;
import org.sosy_lab.common.configuration.InvalidConfigurationException;
import org.sosy_lab.common.configuration.Option;
import org.sosy_lab.common.configuration.Options;
import org.sosy_lab.common.io.PathCounterTemplate;
import org.sosy_lab.common.log.LogManager;
import org.sosy_lab.java_smt.api.FloatingPointRoundingMode;
import org.sosy_lab.java_smt.api.SolverContext;
import org.sosy_lab.java_smt.basicimpl.AbstractNumeralFormulaManager.NonLinearArithmetic;
import org.sosy_lab.java_smt.delegate.debugging.DebuggingSolverContext;
import org.sosy_lab.java_smt.delegate.logging.LoggingSolverContext;
import org.sosy_lab.java_smt.delegate.statistics.StatisticsSolverContext;
import org.sosy_lab.java_smt.delegate.synchronize.SynchronizedSolverContext;
import org.sosy_lab.java_smt.solvers.bitwuzla.BitwuzlaSolverContext;
import org.sosy_lab.java_smt.solvers.boolector.BoolectorSolverContext;
import org.sosy_lab.java_smt.solvers.cvc4.CVC4SolverContext;
import org.sosy_lab.java_smt.solvers.cvc5.CVC5SolverContext;
import org.sosy_lab.java_smt.solvers.mathsat5.Mathsat5SolverContext;
import org.sosy_lab.java_smt.solvers.opensmt.OpenSmtSolverContext;
import org.sosy_lab.java_smt.solvers.princess.PrincessSolverContext;
import org.sosy_lab.java_smt.solvers.smtinterpol.SmtInterpolSolverContext;
import org.sosy_lab.java_smt.solvers.yices2.Yices2SolverContext;
import org.sosy_lab.java_smt.solvers.z3.Z3SolverContext;
/**
* Factory class for loading and generating solver contexts. Generates a {@link SolverContext}
* corresponding to the chosen solver.
*
* <p>Main entry point for JavaSMT.
*/
@Options(prefix = "solver")
public class SolverContextFactory {
public enum Solvers {
OPENSMT,
MATHSAT5,
SMTINTERPOL,
Z3,
PRINCESS,
BOOLECTOR,
CVC4,
CVC5,
YICES2,
BITWUZLA
}
@Option(secure = true, description = "Export solver queries in SmtLib format into a file.")
private boolean logAllQueries = false;
@Option(secure = true, description = "Export solver queries in SmtLib format into a file.")
@FileOption(FileOption.Type.OUTPUT_FILE)
private @Nullable PathCounterTemplate logfile =
PathCounterTemplate.ofFormatString("smtquery.%03d.smt2");
@Option(
secure = true,
description = "If logging from the same application, avoid conflicting logfile names.")
private boolean renameLogfileToAvoidConflicts = true;
private static final Set<String> logfiles = new LinkedHashSet<>();
@Option(secure = true, description = "Random seed for SMT solver.")
private long randomSeed = 42;
@Option(secure = true, description = "Which SMT solver to use.")
private Solvers solver = Solvers.SMTINTERPOL;
@Option(secure = true, description = "Log solver actions, this may be slow!")
private boolean useLogger = false;
@Option(
secure = true,
description = "Sequentialize all solver actions to allow concurrent access!")
private boolean synchronize = false;
@Option(secure = true, description = "Apply additional checks to catch common user errors.")
private boolean useDebugMode = false;
@Option(
secure = true,
description = "Counts all operations and interactions towards the SMT solver.")
private boolean collectStatistics = false;
@Option(secure = true, description = "Default rounding mode for floating point operations.")
private FloatingPointRoundingMode floatingPointRoundingMode =
FloatingPointRoundingMode.NEAREST_TIES_TO_EVEN;
@Option(
secure = true,
description =
"Use non-linear arithmetic of the solver if supported and throw exception otherwise, "
+ "approximate non-linear arithmetic with UFs if unsupported, "
+ "or always approximate non-linear arithmetic. "
+ "This affects only the theories of integer and rational arithmetic.")
private NonLinearArithmetic nonLinearArithmetic = NonLinearArithmetic.USE;
private final LogManager logger;
private final ShutdownNotifier shutdownNotifier;
private final Configuration config;
private final Consumer<String> loader;
/**
* This constructor uses the default JavaSMT loader for accessing native libraries.
*
* @see #SolverContextFactory(Configuration, LogManager, ShutdownNotifier, Consumer)
*/
public SolverContextFactory(
Configuration pConfig, LogManager pLogger, ShutdownNotifier pShutdownNotifier)
throws InvalidConfigurationException {
this(pConfig, pLogger, pShutdownNotifier, NativeLibraries::loadLibrary);
}
/**
* This constructor instantiates a factory for building solver contexts for a configured SMT
* solver (via the parameter <code>pConfig</code>). Each created context is independent of other
* contexts and uses its own environment for building formulas and querying the solver.
*
* @param pConfig The configuration to be used when instantiating JavaSMT and the solvers. By
* default, the configuration specifies the solver to use via the option <code>
* solver.solver=...</code>. This option can be overridden when calling the method {@link
* #generateContext(Solvers)}.
* @param pLogger The processing of log messages from SMT solvers (or their bindings) is handled
* via this LogManager.
* @param pShutdownNotifier This central instance allows to request the termination of all
* operations in the created solver. Please note that the solver can decide on its own to
* accept the shutdown request and terminate its operation afterwards. We do not forcefully
* terminate any solver query eagerly. In general, a solver is of good nature, and maturely
* developed, and terminates accordingly.
* @param pLoader The loading mechanism (loading method) in this class can be injected by the user
* and, e.g., can be used to search for the library binaries in more directories. This makes
* the loading process for native solvers like Boolector, CVC4, MathSAT, Z3 more flexible. For
* Java-based libraries (solvers like SMTInterpol or Princess, and also other dependences),
* this class is irrelevant and not accessed.
*/
public SolverContextFactory(
Configuration pConfig,
LogManager pLogger,
ShutdownNotifier pShutdownNotifier,
Consumer<String> pLoader)
throws InvalidConfigurationException {
pConfig.inject(this);
logger = pLogger.withComponentName("JavaSMT");
shutdownNotifier = checkNotNull(pShutdownNotifier);
config = pConfig;
loader = checkNotNull(pLoader);
if (!logAllQueries) {
logfile = null;
}
if (logfile != null && renameLogfileToAvoidConflicts) {
logfile = makeUniqueLogfile(logfile);
}
}
/**
* compute a new unused template. This method is helpful, if several instances of a solver are
* used interleaved via JavaSMT and only one configuration is used.
*/
private static synchronized PathCounterTemplate makeUniqueLogfile(PathCounterTemplate pLogfile) {
final String original = pLogfile.getTemplate();
final String extension = getFileExtension(original);
final String basename = original.substring(0, original.length() - extension.length());
String template = original;
int counter = 0;
while (logfiles.contains(template)) {
counter++;
template = basename + "." + counter + extension;
}
logfiles.add(template);
return PathCounterTemplate.ofFormatString(template);
}
private static String getFileExtension(String path) {
int lastIndexOf = path.lastIndexOf('.');
return (lastIndexOf == -1) ? "" : path.substring(lastIndexOf);
}
/** Create new context with solver chosen according to the supplied configuration. */
public SolverContext generateContext() throws InvalidConfigurationException {
return generateContext(solver);
}
/**
* Create new context with solver name supplied.
*
* @see #generateContext()
*/
@SuppressWarnings("resource") // returns unclosed context object
public SolverContext generateContext(Solvers solverToCreate)
throws InvalidConfigurationException {
SolverContext context;
try {
context = generateContext0(solverToCreate);
} catch (UnsatisfiedLinkError | NoClassDefFoundError e) {
throw new InvalidConfigurationException(
String.format(
"The SMT solver %s is not available on this machine because of missing libraries"
+ " (%s).",
solverToCreate, e.getMessage()),
e);
}
if (useLogger) {
context = new LoggingSolverContext(logger, context);
}
if (synchronize) {
context = new SynchronizedSolverContext(config, logger, shutdownNotifier, context);
}
if (useDebugMode) {
context = new DebuggingSolverContext(solverToCreate, config, context);
}
if (collectStatistics) {
// statistics need to be the most outer wrapping layer.
context = new StatisticsSolverContext(context);
}
return context;
}
private SolverContext generateContext0(Solvers solverToCreate)
throws InvalidConfigurationException {
switch (solverToCreate) {
case OPENSMT:
return OpenSmtSolverContext.create(
config, logger, shutdownNotifier, randomSeed, nonLinearArithmetic, loader);
case CVC4:
return CVC4SolverContext.create(
logger,
shutdownNotifier,
(int) randomSeed,
nonLinearArithmetic,
floatingPointRoundingMode,
loader);
case CVC5:
return CVC5SolverContext.create(
logger,
config,
shutdownNotifier,
(int) randomSeed,
nonLinearArithmetic,
floatingPointRoundingMode,
loader);
case SMTINTERPOL:
return SmtInterpolSolverContext.create(
config, logger, shutdownNotifier, logfile, randomSeed, nonLinearArithmetic);
case MATHSAT5:
return Mathsat5SolverContext.create(
logger,
config,
shutdownNotifier,
logfile,
randomSeed,
floatingPointRoundingMode,
nonLinearArithmetic,
loader);
case Z3:
return Z3SolverContext.create(
logger,
config,
shutdownNotifier,
logfile,
randomSeed,
floatingPointRoundingMode,
nonLinearArithmetic,
loader);
case PRINCESS:
return PrincessSolverContext.create(
config, shutdownNotifier, logfile, (int) randomSeed, nonLinearArithmetic, logger);
case YICES2:
return Yices2SolverContext.create(nonLinearArithmetic, shutdownNotifier, loader, logger);
case BOOLECTOR:
return BoolectorSolverContext.create(config, shutdownNotifier, logfile, randomSeed, loader);
case BITWUZLA:
return BitwuzlaSolverContext.create(
config,
shutdownNotifier,
logfile,
randomSeed,
floatingPointRoundingMode,
loader,
logger);
default:
throw new AssertionError("no solver selected");
}
}
/**
* Shortcut for getting a {@link SolverContext}, the solver is selected using the configuration
* {@code config}.
*/
public static SolverContext createSolverContext(
Configuration config, LogManager logger, ShutdownNotifier shutdownNotifier)
throws InvalidConfigurationException {
return new SolverContextFactory(config, logger, shutdownNotifier, NativeLibraries::loadLibrary)
.generateContext();
}
/**
* Shortcut for getting a {@link SolverContext}, the solver is selected using an argument.
*
* <p>See {@link #SolverContextFactory(Configuration, LogManager, ShutdownNotifier, Consumer)} for
* documentation of accepted parameters.
*/
public static SolverContext createSolverContext(
Configuration config, LogManager logger, ShutdownNotifier shutdownNotifier, Solvers solver)
throws InvalidConfigurationException {
return new SolverContextFactory(config, logger, shutdownNotifier, NativeLibraries::loadLibrary)
.generateContext(solver);
}
/**
* This is the most explicit method for getting a {@link SolverContext}, the solver, the logger,
* the shutdownNotifier, and the libraryLoader are provided as parameters by the caller.
*
* <p>See {@link #SolverContextFactory(Configuration, LogManager, ShutdownNotifier, Consumer)} for
* documentation of accepted parameters.
*/
public static SolverContext createSolverContext(
Configuration config,
LogManager logger,
ShutdownNotifier shutdownNotifier,
Solvers solver,
Consumer<String> loader)
throws InvalidConfigurationException {
return new SolverContextFactory(config, logger, shutdownNotifier, loader)
.generateContext(solver);
}
/**
* Minimalistic shortcut for creating a solver context. Empty default configuration, no logging,
* and no shutdown notifier.
*
* @param solver Solver to initialize
*/
public static SolverContext createSolverContext(Solvers solver)
throws InvalidConfigurationException {
return new SolverContextFactory(
Configuration.defaultConfiguration(),
LogManager.createNullLogManager(),
ShutdownNotifier.createDummy(),
NativeLibraries::loadLibrary)
.generateContext(solver);
}
}