Class: Z3Solver

Inherits:
Object
  • Object
show all
Defined in:
lib/solver-lib.rb

Instance Method Summary collapse

Constructor Details

#initialize(progress, z3path) ⇒ Z3Solver

Returns a new instance of Z3Solver.



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/solver-lib.rb', line 140

def initialize(progress, z3path)
  z3version = `#{z3path} --version`.chomp()
  if $?.exitstatus == 0 then
    progress.print_line "INFO: Using #{z3version} found in z3path=#{z3path}"
    @z3in, @z3outAndErr, @z3thr = Open3.popen2e(z3path, '-in', '-smt2')
    Process.detach(@z3thr.pid)
  else
    progress.print_line "WARN: could not find z3 in z3path=#{z3path.inspect}"
    `which z3`
    if $?.exitstatus == 0 then
      z3version = `z3 --version`.chomp()
      progress.print_line "However, #{z3version} is availlable on the PATH. Using this one."
      @z3in, @z3outAndErr, @z3thr = Open3.popen2e('z3', '-in', '-smt2')
      Process.detach(@z3thr.pid)
    else
      raise RuntimeError.new("ERROR: unable to find Z3. Exiting! (Please provide its location in the config file using the key :z3path)")
    end
  end
  @z3in.sync = true

  @sessionIdCounter = 0
end

Instance Method Details

#check_type(type, value, xpath) ⇒ Object



373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/solver-lib.rb', line 373

def check_type(type, value, xpath)
  if type == "String" then
    unless value =~ /\".*\"/ then
      raise RuntimeError.new("inconsistent model value: model value for #{xpath} should be a String, but was #{value}.")
    end
  elsif type == "Bool"
    unless value == "true" or value == "false" then
      raise RuntimeError.new("inconsistent model value for #{xpath} should be a Bool, but was #{value.inspect}.")
    end
  elsif type == "Int"
    unless value =~ /\d+/ then
      raise RuntimeError.new("inconsistent model value: model value for #{xpath} should be a Int, but was #{value}.")
    end
  else
    raise RuntimeError.new("encountered unknown solver type: type of solver-var for #{xpath} is #{info[:type]}.")
  end
end

#closeObject



163
164
165
166
167
# File 'lib/solver-lib.rb', line 163

def close()
  @z3in.close()
  @z3outAndErr.close()
  Thread.kill(@z3thr)
end

#convert_solver_value(type, datatype, value, xpath) ⇒ Object



391
392
393
394
395
396
397
398
399
400
# File 'lib/solver-lib.rb', line 391

def convert_solver_value(type, datatype, value, xpath)
  check_type(type, value, xpath)
  if datatype == :date then
    return (Time.at(0).to_date + Integer(value)).to_s
  elsif datatype == :timestamp then
    return Time.at(Integer(value)).to_s
  else
    return value
  end
end

#display_assertion(assertion, solver) ⇒ Object



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
# File 'lib/solver-lib.rb', line 199

def display_assertion(assertion, solver)
  if assertion =~ /validation_rule_(.*)_instance_(.*)/ then
    return "Validation rule #{$1} of structure #{$2.gsub("_", "/")}"
  else
    info = solver.getAssociationForAssertionID(assertion)
    if info then
      if info[:assertion_type] == :doc_field_filled then
        return "Field #{info[:xpath]} contains value #{info[:value].inspect} in document"
      elsif info[:assertion_type] == :doc_field_empty then
        return "Field #{info[:xpath]} is empty in document"
      elsif info[:assertion_type] == :doc_structure_exists then
        return "Structure #{info[:xpath]} exists in document"
      elsif info[:assertion_type] == :doc_structure_not_exists then
        return "Structure #{info[:xpath]} does not exist in document"
      elsif info[:assertion_type] == :constraint then
        if info[:constraint_type] == :min then
          return "Field #{info[:xpath]} has a minimum value of #{info[:value]}."
        elsif info[:constraint_type] == :max then
          return "Field #{info[:xpath]} has a maximum value of #{info[:value]}."
        elsif info[:constraint_type] == :required then
          return "Field #{info[:xpath]} is required."
        else
          p info
          raise RuntimeError.new("encountered unknown :constraint_type #{info[:constraint_type].inspect} for assertionID #{assertion.inspect}")
        end
      else
        raise RuntimeError.new("encountered unknown :assertion_type #{info[:assertion_type].inspect} for assertionID #{assertion.inspect}")
      end
    else
      return assertion
    end
  end
end

#foreach_field_in_model_str(str, solver, const_info, &block) ⇒ Object



402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# File 'lib/solver-lib.rb', line 402

def foreach_field_in_model_str(str, solver, const_info, &block)
  unless str =~ /^\((.*)\)$/m
    raise RuntimeError.new("could not parse model: #{str.inspect}")
  end
  str = $1

  str.split("\n").each do |line|
    unless line =~ /\(([^\ ]*)\ (.*)\)/
      raise RuntimeError.new("could not parse model line: #{line.inspect}")
    end
    varname = $1
    value = $2
    if value =~ /\(-\ (\d+)\)/ then
      simplified = "-#{$1}"
      value = simplified
    end
    info = const_info[varname]

    block.call(varname, value, info)
  end

  return nil
end

#handleSolverError(progress, solver, options, result) ⇒ Object

Raises:

  • (RuntimeError)


426
427
428
429
# File 'lib/solver-lib.rb', line 426

def handleSolverError(progress, solver, options, result)
  solver.writeProtocolToFile(progress, options[:solverLog])
  raise RuntimeError.new("Solver Error: Solver returned '#{result}', for more information see #{options[:solverLog]}")
end

#parse_unsat_core(solver, unsat_core) ⇒ Object



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/solver-lib.rb', line 233

def parse_unsat_core(solver, unsat_core)
  unsat_core = unsat_core.chomp
  # TODO: implement
  unless unsat_core =~ /\((.*)\)/ then
    raise RuntimeError.new("could not parse unsat core: #{unsat_core.inspect}")
  end
  list = $1.split(" ")

  result = "EXPLANATION:\n"
  result += "The following values\n"

  list.filter{|a| a.start_with?("doc-")}.each do |assertion|
    result += "- #{display_assertion(assertion, solver)} (#{assertion})\n"
  end
  result += "\nviolate the following constraints\n"
  list.filter{|a| !a.start_with?("doc-")}.each do |assertion|
    result += "- #{display_assertion(assertion, solver)} (#{assertion})\n"
  end
  return result
end

#query(progress, options, &block) ⇒ Object



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
# File 'lib/solver-lib.rb', line 169

def query(progress, options, &block)
  unless options[:solverLog]
    raise RuntimeError.new("No solverLog specified, but the option :solverLog is required!")
  end
  progress.print_line("calling solver (solver-log is written to #{options[:solverLog]})")
  solver = SolverSession.new(@z3in, @z3outAndErr, options[:solverLog])

  block.call(solver)

  solver.to_solver(progress, "(check-sat)")
  result = solver.from_solver(progress)
  explanation = true
  if result.chomp == "sat"
      # model is not contradictory -> continue
  elsif result.chomp == "unsat"
      # model is contradictory -> add a message

      solver.to_solver(progress, "(get-unsat-core)")
      unsat_core = solver.from_solver(progress)
      explanation = parse_unsat_core(solver, unsat_core)
  else
    handleSolverError(progress, solver, options, result)
  end

  solver.to_solver(progress, "(reset)")
  solver.to_solver(progress, "(set-logic ALL)") 
  solver.to_solver(progress, "(set-option :produce-unsat-cores true)") 
  return explanation
end

#query_model(progress, options, &block) ⇒ Object

main entry point!



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
# File 'lib/solver-lib.rb', line 255

def query_model(progress, options, &block)
  unless options[:solverLog]
    raise RuntimeError.new("No solverLog specified, but the option :solverLog is required!")
  end
  progress.print_line("calling solver (solver-log is written to #{options[:solverLog]})")
  solver = SolverSession.new(@z3in, @z3outAndErr, options[:solverLog])

  block.call(solver)
  
  solver.to_solver(progress, "(check-sat)")
  result = solver.from_solver(progress)
  if result.chomp == "sat"
      # model is not contradictory -> extract model
      const_list = []
      const_info = {}
      solver.for_each_const do |name, info|
        const_list << name
        const_info[name] = info
      end
      solver.to_solver(progress, "(get-value (#{const_list.join(" ")}))")
      model_str = solver.read_multiline_from_solver()
      model = {}
      foreach_field_in_model_str(model_str, solver, const_info) do |varname, value, info|
        unless info then
          progress.print_line "WARN: no info availlable for varname=#{varname.inspect}, value=#{value.inspect}"
        end
        xpath = info[:xpath]
        if model.has_key?(xpath) then
          if varname.end_with?("-filled") then
            unless model[xpath][:type] == :field then
              raise RuntimeError.new("inconsistent model: xpath #{xpath} should be a field, not a #{model[xpath][:type]}.")
            end
            unless value == "true" or value == "false" then
              raise RuntimeError.new("inconsistent model value filled-value of #{xpath} should be a Bool, but was #{value.inspect}.")
            end
            if value == "true" then
              model[xpath][:filled] = true
            else
              model[xpath][:filled] = false
            end
          elsif varname.end_with?("-value") then
            unless model[xpath][:type] == :field || model[xpath][:type] == :list then
              raise RuntimeError.new("inconsistent model: xpath #{xpath} should be a field or a list, not a #{model[xpath][:type]}.")
            end
            if model[xpath][:type] == :field then
              model[xpath][:value] = convert_solver_value(info[:type], info[:datatype], value, xpath)
            elsif model[xpath][:type] == :list then
              unless varname =~ /-index-(\d+)-value$/
                raise RuntimeError.new("inconsistent model: xpath #{xpath} is a list value and hence its varname should end like -index-X-value, not #{varname.inspect}.")
              end
              index = Integer($1)
              model[xpath][:xpath_element] = info[:xpath_element]
              if model[xpath].has_key?(:value) then
                val = convert_solver_value(info[:type], info[:datatype], value, xpath)
                model[xpath][:value].insert(index, val)
              else
                val = convert_solver_value(info[:type], info[:datatype], value, xpath)
                model[xpath][:value] = [val]
              end
            end
          elsif varname.end_with?("-size") then
            unless model[xpath][:type] == :list || model[xpath][:type] == :field then
              raise RuntimeError.new("inconsistent model: xpath #{xpath} should be a list or a field, not a #{model[xpath][:type]}.")
            end
            if model[xpath][:type] == :field then
              model[xpath][:type] = :list
            end
            model[xpath][:size] = Integer(value)
          elsif varname.start_with?("struct-") && varname.end_with?("-exists") then
            unless model[xpath][:type] == :struct then
              raise RuntimeError.new("inconsistent model: xpath #{xpath} should be a struct, not a #{model[xpath][:type]}.")
            end
            model[xpath][:exists] = value
          end
        else
          if varname.end_with?("-filled") then
            unless value == "true" or value == "false" then
              raise RuntimeError.new("inconsistent model value filled-value of #{xpath} should be a Bool, but was #{value.inspect}.")
            end
            if value == "true" then
              model[xpath] = { :type => :field, :filled => true }
            else
              model[xpath] = { :type => :field, :filled => false }
            end
          elsif varname.end_with?("-value") then
            check_type(info[:type], value, xpath)
            model[xpath] = {  :type => :field, :value => value }
          elsif varname.start_with?("struct-") && varname.end_with?("-exists") then
            unless value == "true" or value == "false" then
              raise RuntimeError.new("inconsistent model value exists-value of struct #{xpath} should be a Bool, but was #{value.inspect}.")
            end
            model[xpath] = { :type => :struct, :exists => value }
          elsif varname.end_with?("-size") then
            model[xpath] = { :type => :list, :size => value }
          end
        end
      end
      return model
  elsif result.chomp == "unsat"
      # model is contradictory -> add a message

      solver.to_solver(progress, "(get-unsat-core)")
      unsat_core = solver.from_solver(progress)
      solver.writeProtocolToFile(progress, options[:solverLog])
      progress.print_line "Solver reported a contradiction! please see #{options[:solverLog]} for further information."
      return nil
  else
    handleSolverError(progress, solver, options, result)
  end

  messages = []
  solver.to_solver "(reset)"
  solver.to_solver "(set-logic ALL)"
  solver.to_solver "(set-option :produce-unsat-cores true)"

  return messages
end