Top Level Namespace
Defined Under Namespace
Classes: CoreEnumerationAlgo, FatalError, NormalProgramTermination, Progress, ProgressBar, Regexp_to_SMTLIB, SolverSession, Z3Solver
Constant Summary collapse
- CHUNK_SIZE =
10000- DEFAULT_Z3_PATH =
"z3"- CONFIG_FILE =
"config.yml"- OUTPUT_FILE =
"result.xml"- CONTINUATION_FILE =
"continuation.log"- COMBINATION_LOG =
"combinations.log"- VARS_LOG =
"vars.log"- OUTPUT_DIR =
"result"- LISTS_DIR =
"lists"- QUERY_DIR =
"queries"- PARAMETERIZED_QUERY_DIR =
"parameterized_queries"- XML_TEMPLATE =
""- DEFAULT_CONFIG =
{ :z3path => "z3", :generation_system_mode => "Production", :generation_system => "Production" }
- USAGE =
<<EOF usage: GENERATING A SINGLE MESSAGE: ruby #{$PROGRAM_NAME} -list-validation-rules - outputs a list of all validation rule names that have been specified in #{$PROGRAM_NAME}. ruby #{$PROGRAM_NAME} <options> - generates a message of the given type, which - is valid XML - adheres to the schema, and - satisfies all validation rules specified for messages of this type. where <options> is a combination of -negate <validation_rule> - negates the named validation rule. This causes the resulting message to still satisfy all other validation rules, but to violate this one. NOTE: the result can be found in #{OUTPUT_FILE} GENERATING MESSAGES FOR ALL COMBINATIONS: ruby #{$PROGRAM_NAME} -list-keys - outputs a list of all keys that have been used in #{$PROGRAM_NAME} to mark fields or structures. ruby #{$PROGRAM_NAME} -list <key> - outputs a list of all fields and structures that have been marked with <key> in #{$PROGRAM_NAME}. ruby #{$PROGRAM_NAME} -count-docs-for-key <key> - calculates the number of combinations of all fields and structures marked with <key> ruby #{$PROGRAM_NAME} -generate-docs-for-key <key> <options> - generates all valid messages of the given type that can be derived from combinations of all the fields and structures marked with <key>. where <options> is a combination of -continue - continues a previously interrupted generation process. Must use the same <key> the the interrupted generation.ARGF -max-num-docs <limit> - stops generation process after generating <limit> documents. NOTE: enumerating large combination-spaces may take a long time. - Use -count-docs-for-key to measure the size of the combination-space beforehand. - Also: you can interrupt the generation process at any time using Ctrl+C. The intermediate result is stored in the directory #{OUTPUT_DIR} and the generation process can be restarted later by adding -continue to the command line. NOTE: do not expect the number of generated documents to equal the number of combinations as combinations may not have any valid message instances (for instance when they contradict the validation rules). NOTE: the result can be found in the directory #{OUTPUT_DIR} VALIDATING THE MODEL: ruby #{$PROGRAM_NAME} -validate <file.xml> - reads in the given XML file and validates it against the model - that is, it checks whether it conforms to the specified XML schema and to the validation rules. EOF
Instance Method Summary collapse
- #add_model_struct_to_doc(progress, struct, doc, model, prefix = nil) ⇒ Object
- #all_values_for_field(field) ⇒ Object
- #build_document_from_model(progress, struct, model) ⇒ Object
- #calc_combinations(message, key) ⇒ Object
- #calc_combinations_for_key_fields(key_fields) ⇒ Object
- #collect_key_fields(fkey, struct, prefix = nil) ⇒ Object
- #collect_key_fields_and_strctures(fkey, struct, prefix = nil) ⇒ Object
- #collect_keys(struct) ⇒ Object
- #collect_validation_rule_names(struct) ⇒ Object
- #collect_validation_rules(struct) ⇒ Object
- #default_value_for_fielddef(fielddef) ⇒ Object
- #enum_constraint_for_expr(expr, values) ⇒ Object
- #exists_var_for_structure(xpath) ⇒ Object
- #extract_key_field_values_from_model(key_fields, model) ⇒ Object
- #filled_var_for_field(xpath) ⇒ Object
- #generate(message, argv, message_config_filename = nil) ⇒ Object
- #generate_doc(progress, message, output_filename, config, options) ⇒ Object
- #introduce_parent_links(message, parent = nil, prefix = nil) ⇒ Object
- #list_fields_and_structures(message, fkey) ⇒ Object
- #list_keys(message) ⇒ Object
- #list_validation_rules(message) ⇒ Object
- #max_constraint_for_expr(expr, upper_bound) ⇒ Object
- #maxLength_contraint_for_expr(expr, maxLength) ⇒ Object
- #min_constraint_for_expr(expr, lower_bound) ⇒ Object
- #oneOf_contraint_for_expr(expr, values) ⇒ Object
- #parse_field_value(fielddef, value) ⇒ Object
- #prepare_output_doc_filename(number, output_dir) ⇒ Object
- #raw_field(xpath) ⇒ Object
- #read_docs_from_log_file(log_filename) ⇒ Object
- #regex_constraint_for_expr(expr, regex) ⇒ Object
- #resolve_field_def(path, relative_to_struct, prefix) ⇒ Object
- #resolve_field_path(path, relative_to_struct, prefix) ⇒ Object
- #resolve_struct_def(path, relative_to_struct, prefix, context_desc = "") ⇒ Object
- #resolve_struct_path(path, relative_to_struct, prefix) ⇒ Object
- #set_standard_options(progress, solver) ⇒ Object
- #size_var_for_list(xpath) ⇒ Object
- #solver_value_to_string(solver_value) ⇒ Object
- #translate_datatype_to_SMTLIB(datatype) ⇒ Object
- #translate_doc_to_SMTLIB(progress, solver, struct, doc, hash = {}) ⇒ Object
- #translate_field_def_to_SMTLIB_constraints(progress, solver, fielddef, xpath) ⇒ Object
- #translate_list_def_to_SMTLIB_constraints(progress, solver, fielddef, varname) ⇒ Object
- #translate_struct_in_doc_to_SMTLIB(progress, solver, struct, doc, prefix, hash = {}) ⇒ Object
- #translate_structure_to_SMTLIB(progress, solver, struct, hash = {}) ⇒ Object
- #translate_substructure_to_SMTLIB(progress, solver, struct, hash = {}) ⇒ Object
- #translate_validation_rule_to_SMTLIB(rule, context_struct, prefix, config, options, rule_name) ⇒ Object
- #translate_validation_rules_for_structure_to_SMTLIB(progress, solver, struct, prefix, config, options) ⇒ Object
- #translate_validation_rules_to_SMTLIB(progress, solver, struct, prefix, config, options) ⇒ Object
- #translate_value_to_SMTLIB(value) ⇒ Object
- #validate_doc(progress, struct, doc, options, config) ⇒ Object
- #validate_doc_against_schema(struct, doc) ⇒ Object
- #validate_doc_struct_against_schema(struct, doc, prefix = nil) ⇒ Object
- #validate_model(message, prefix = nil) ⇒ Object
- #validate_schema_against_doc_struct(struct, doc, prefix = nil) ⇒ Object
- #value_of_type(value, type) ⇒ Object
- #value_var_for_field(xpath) ⇒ Object
- #value_var_for_list(xpath, index) ⇒ Object
- #values_for_key_field(field) ⇒ Object
- #z3ValueToRubyValue(value) ⇒ Object
Instance Method Details
#add_model_struct_to_doc(progress, struct, doc, model, prefix = nil) ⇒ Object
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 |
# File 'lib/mbt-gen.rb', line 747 def add_model_struct_to_doc(progress, struct, doc, model, prefix = nil) struct.each do |key, value| next if key == :validation_rules || key == :predicates || key == :parent_link || key == :struct_xpath_prefix || key == :additional_smtlib if prefix then xpath = "#{prefix}/#{key}" else xpath = key.to_s end model_value = model[xpath] if value[:type] == :field then unless model_value then raise RuntimeError.new("xpath '#{xpath}' not contained in model.") end if model_value[:filled] == true || model_value[:filled] == "true" then doc.add_child("<#{key}>#{solver_value_to_string(model_value[:value])}</#{key}>") end elsif value[:type] == :list then node = doc.add_child("<#{key}></#{key}>") if node.is_a?(Nokogiri::XML::NodeSet) then node = node.first end xpath_element = value[:xpath_element] if Integer(model_value[:size]) > 0 then model_value[:value].slice(0, Integer(model_value[:size])).each do |mvalue| node.add_child("<#{xpath_element}>#{solver_value_to_string(mvalue)}</#{xpath_element}>") end end elsif value[:type] == :structure then unless value[:ref] then raise RuntimeError.new("struct is broken: :structure #{key.inspect} does not have a :ref") end if model_value[:exists] == true || model_value[:exists] == "true" then node = doc.add_child("<#{key}></#{key}>") if node.is_a?(Nokogiri::XML::NodeSet) then node = node.first end add_model_struct_to_doc(progress, value[:ref], node, model, xpath) end else raise RuntimeError.new("struct is broken: encountered unknown :type #{value[:type].inspect}") end end end |
#all_values_for_field(field) ⇒ Object
884 885 886 887 888 889 890 891 892 893 894 895 896 |
# File 'lib/mbt-gen.rb', line 884 def all_values_for_field(field) unless field[:type] == :field then raise RuntimeError.new("something that is not a field definition was passed to all_values_for_field(): #{field.inspect}") end unless field[:datatype] == :enum then raise RuntimeError.new("all_values_for_field() is only applicable to fields of datatype enum! not #{field[:datatype].inspect}.") end values = field[:values].dup if field[:optional] == true then values << nil end return values end |
#build_document_from_model(progress, struct, model) ⇒ Object
741 742 743 744 745 |
# File 'lib/mbt-gen.rb', line 741 def build_document_from_model(progress, struct, model) doc = Nokogiri::XML(XML_TEMPLATE) add_model_struct_to_doc(progress, struct, doc, model) return doc end |
#calc_combinations(message, key) ⇒ Object
926 927 928 929 |
# File 'lib/mbt-gen.rb', line 926 def calc_combinations(, key) key_fields = collect_key_fields(key, ) return calc_combinations_for_key_fields(key_fields) end |
#calc_combinations_for_key_fields(key_fields) ⇒ Object
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 |
# File 'lib/mbt-gen.rb', line 898 def calc_combinations_for_key_fields(key_fields) count = 1 key_fields.each do |field| if field[1][:type] == :field then if field[1][:datatype] == :enum then num_values = field[1][:values].size num_values += 1 if field[1][:optional] elsif field[1][:datatype] == :int then if field[1].has_key?(:min) and field[1].has_key?(:max) and field[1][:min] <= field[1][:max] then if field[1][:optional] then num_values = 2 + field[1][:max] - field[1][:min] else num_values = 1 + field[1][:max] - field[1][:min] end else return "potentially infinite" end elsif field[1][:datatype] == :string then return "potentially infinite" end elsif field[1][:type] == :structure then num_values = 2 end count *= num_values end return count end |
#collect_key_fields(fkey, struct, prefix = nil) ⇒ Object
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 |
# File 'lib/mbt-gen.rb', line 1001 def collect_key_fields(fkey, struct, prefix = nil) result = {} struct.each do |key, value| next if key == :validation_rules || key == :predicates || key == :parent_link || key == :struct_xpath_prefix || key == :additional_smtlib if value[:type] == :structure if value.has_key?(:keys) and value[:keys].include?(fkey) then xpath = key.to_s xpath = "#{prefix}/#{xpath}" if prefix result[xpath] = value.clone().filter{|k,v| [:type, :optional, :datatype, :values].include?(k)} end if prefix then new_prefix = "#{prefix}/#{key}" else new_prefix = key end result = result.merge(collect_key_fields(fkey, value[:ref], new_prefix)) elsif value[:type] == :field and value.has_key?(:keys) and value[:keys].include?(fkey) then xpath = key.to_s xpath = "#{prefix}/#{xpath}" if prefix result[xpath] = value.clone().filter{|k,v| [:type, :optional, :datatype, :values, :min, :max].include?(k)} end end return result end |
#collect_key_fields_and_strctures(fkey, struct, prefix = nil) ⇒ Object
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 |
# File 'lib/mbt-gen.rb', line 1026 def collect_key_fields_and_strctures(fkey, struct, prefix = nil) fields = [] structures = [] struct.each do |key, value| next if key == :validation_rules || key == :predicates || key == :parent_link || key == :struct_xpath_prefix || key == :additional_smtlib if value[:type] == :structure if value.has_key?(:keys) and value[:keys].include?(fkey) then xpath = key.to_s xpath = "#{prefix}/#{xpath}" if prefix structures << xpath end if prefix then new_prefix = "#{prefix}/#{key}" else new_prefix = key end result_fields, result_structures = collect_key_fields_and_strctures(fkey, value[:ref], new_prefix) fields += result_fields structures += result_structures elsif value[:type] == :field and value.has_key?(:keys) and value[:keys].include?(fkey) then xpath = key.to_s xpath = "#{prefix}/#{xpath}" if prefix fields << xpath end end return fields, structures end |
#collect_keys(struct) ⇒ Object
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 |
# File 'lib/mbt-gen.rb', line 1054 def collect_keys(struct) result = [] struct.each do |key, value| next if key == :validation_rules || key == :predicates || key == :parent_link || key == :struct_xpath_prefix || key == :additional_smtlib if value[:type] == :structure if value.has_key?(:keys) then result += value[:keys] end if value[:ref] then result += collect_keys(value[:ref]) else raise RuntimeError.new("Model error: encountered structure without :ref: key=#{key.inspect} value=#{value.inspect}") end elsif value[:type] == :field and value.has_key?(:keys) then result += value[:keys] end end result.uniq end |
#collect_validation_rule_names(struct) ⇒ Object
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 |
# File 'lib/mbt-gen.rb', line 791 def collect_validation_rule_names(struct) result = [] struct.each do |key, value| next if key == :predicates || key == :parent_link || key == :struct_xpath_prefix || key == :additional_smtlib if key == :validation_rules value.each do |key, value| result << key end else if value[:type] == :structure result += collect_validation_rule_names(value[:ref]) end end end return result end |
#collect_validation_rules(struct) ⇒ Object
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 |
# File 'lib/mbt-gen.rb', line 1074 def collect_validation_rules(struct) result = [] struct.each do |key, value| next if key == :predicates || key == :parent_link || key == :struct_xpath_prefix || key == :additional_smtlib if key == :validation_rules then result += value.keys else if value[:type] == :structure if value[:ref] then result += collect_validation_rules(value[:ref]) else raise RuntimeError.new("Model error: encountered structure without :ref: key=#{key.inspect} value=#{value.inspect}") end end end end result.uniq end |
#default_value_for_fielddef(fielddef) ⇒ Object
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 |
# File 'lib/mbt-gen.rb', line 305 def default_value_for_fielddef(fielddef) datatype = fielddef[:datatype] case datatype when :int return "0" when :string return "".inspect when :date return "0" when :timestamp return "0" when :enum return "".inspect else raise RuntimeError.new("unknown datatype: #{datatype.inspect}") end end |
#enum_constraint_for_expr(expr, values) ⇒ Object
171 172 173 |
# File 'lib/mbt-gen.rb', line 171 def enum_constraint_for_expr(expr, values) "(or #{values.map{|x| "(= #{expr} #{translate_value_to_SMTLIB(x)})"}.join(" ")})" end |
#exists_var_for_structure(xpath) ⇒ Object
103 104 105 106 107 |
# File 'lib/mbt-gen.rb', line 103 def exists_var_for_structure(xpath) struct_str = "base" struct_str = xpath.gsub("/", "-") if xpath "struct-#{struct_str}-exists" end |
#extract_key_field_values_from_model(key_fields, model) ⇒ Object
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 |
# File 'lib/mbt-gen.rb', line 861 def extract_key_field_values_from_model(key_fields, model) result = {} key_fields.each do |xpath, fieldDesc| fieldInfo = model[xpath] if fieldDesc[:type] == :field then if fieldInfo[:filled] then result[xpath] = z3ValueToRubyValue(fieldInfo[:value]) else result[xpath] = nil end elsif fieldDesc[:type] == :struct || fieldDesc[:type] == :structure then if fieldInfo.has_key?(:exists) then result[xpath] = z3ValueToRubyValue(fieldInfo[:exists]) else result[xpath] = false end else raise RuntimeError.new("encountered unknown :type in solver model: #{fieldDesc[:type].inspect}") end end return result end |
#filled_var_for_field(xpath) ⇒ Object
95 96 97 |
# File 'lib/mbt-gen.rb', line 95 def filled_var_for_field(xpath) "#{raw_field(xpath)}-filled" end |
#generate(message, argv, message_config_filename = nil) ⇒ Object
1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 |
# File 'lib/mbt-gen.rb', line 1855 def generate(, argv, = nil) if ARGV[0] == "--help" || ARGV[0] == "-help" || ARGV[0] == "help" then puts USAGE exit(0) end = { :negated_validation_rules => [], :date_now => (Date.today - Time.at(0).to_date).to_i, :timestamp_now => Time.now().to_i } opt = argv.shift while opt do if opt == "-negate" then rule = argv.shift [:negated_validation_rules] << rule elsif opt == "-list-keys" then [:list_keys] = true elsif opt == "-list" then [:list] = argv.shift elsif opt == "-list-validation-rules" then [:list_validation_rules] = true elsif opt == "-generate-docs-from" then [:combination_source] = argv.shift elsif opt == "-skip" then [:skip] = Integer(argv.shift) elsif opt == "-generate-docs-for-key" then [:docs_for_key] = argv.shift elsif opt == "-count-docs-for-key" then [:count_docs_for_key] = argv.shift elsif opt == "-continue" then [:continue] = true elsif opt == "-max-num-docs" then [:max_num_docs] = Integer(argv.shift) puts "flag -max-num-docs used. Will stop after generating #{[:max_num_docs]} documents." elsif opt == "-validate" then if .has_key?(:validate_files) then [:validate_files] << argv.shift else [:validate_files] = [argv.shift] end else puts "FATAL: unknown option #{opt.inspect}." puts USAGE raise FatalError.new("") end opt = argv.shift end unless [:negated_validation_rules].empty? then puts "negating rules: #{[:negated_validation_rules].join(", ")}" rules = collect_validation_rule_names() unknown_negated_rules = [:negated_validation_rules].filter { |rule_name| !rules.include?(rule_name) } unless unknown_negated_rules.empty? then throw RuntimeError.new("unknown negated rules #{unknown_negated_rules.join(", ")}") end end if File.exist?(CONFIG_FILE) then config = YAML.load_file(CONFIG_FILE) else config = DEFAULT_CONFIG File.open(CONFIG_FILE, "w") do |f| f.puts(config.to_yaml) end puts "No config file found. Default config written to #{CONFIG_FILE}" end if then = YAML.load_file() config = config.merge() end introduce_parent_links() if [:validate_files] then puts "using #{[:date_now]} as [Date.now]" puts "using #{[:timestamp_now]} as [Timestamp.now]" [:validate_files].each do |filename| puts "validating file #{filename}" doc = Nokogiri::XML(File.read(filename)) validate_doc_against_schema(, doc) progress = ProgressBar.new(1) validate_doc(progress, , doc, , config) end elsif [:count_docs_for_key] then puts "there are #{calc_combinations(, [:count_docs_for_key])} combinations." elsif [:docs_for_key] then puts "using #{[:date_now]} as [Date.now]" puts "using #{[:timestamp_now]} as [Timestamp.now]" validate_model() CoreEnumerationAlgo.new().generate_docs_for_key(, [:docs_for_key], OUTPUT_DIR, config, ) elsif [:list_keys] then list_keys() elsif [:list] then list_fields_and_structures(, [:list]) elsif [:list_validation_rules] then list_validation_rules() else puts "using #{[:date_now]} as [Date.now]" puts "using #{[:timestamp_now]} as [Timestamp.now]" validate_model() progress = ProgressBar.new(1) generate_doc(progress, , OUTPUT_FILE, config, ) end end |
#generate_doc(progress, message, output_filename, config, options) ⇒ Object
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 |
# File 'lib/mbt-gen.rb', line 814 def generate_doc(progress, , output_filename, config, ) log = [:log] || nil log.puts "generating doc #{output_filename}" if log [:solverLog] = [:solverLog] || "#{output_filename}.smt2" z3path = config[:z3path] || DEFAULT_Z3_PATH z3 = Z3Solver.new(progress, z3path) begin model = z3.query_model(progress, ) do |solver| (progress, solver) log.puts "translating structure" if log translate_structure_to_SMTLIB(progress, solver, , :options => , :config => config) solver.to_solver(progress, "") end ensure z3.close() end if model then result_doc = build_document_from_model(progress, , model) dir = File.dirname(output_filename) FileUtils.mkdir_p(dir) unless Dir.exist?(dir) File.open(output_filename, "w") do |f| f.puts result_doc.to_xml() end progress.print_line "DONE. Generated XML was written to #{output_filename}, SMTLIB log was written to #{[:solverLog]}" return true else progress.print_line "FAILED. No XML document was generated. For more details, please see the SMTLIB log in #{[:solverLog]}" return false end end |
#introduce_parent_links(message, parent = nil, prefix = nil) ⇒ Object
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 |
# File 'lib/mbt-gen.rb', line 1587 def introduce_parent_links(, parent = nil, prefix = nil) if parent != nil then [:parent_link] = parent end if prefix != nil then [:struct_xpath_prefix] = prefix end .each_pair do |key, value| next if key == :validation_rules || key == :predicates || key == :parent_link || key == :struct_xpath_prefix || key == :additional_smtlib if value[:type] == :structure then if prefix then new_prefix = "#{prefix}/#{key}" else new_prefix = key end introduce_parent_links(value[:ref], , new_prefix) end end end |
#list_fields_and_structures(message, fkey) ⇒ Object
1098 1099 1100 1101 1102 1103 1104 |
# File 'lib/mbt-gen.rb', line 1098 def list_fields_and_structures(, fkey) fields, structures = collect_key_fields_and_strctures(fkey, ) puts "fields for key #{fkey}:" fields.each { |f| puts " #{f}" } puts "structures for key #{fkey}:" structures.each { |s| puts " #{s}" } end |
#list_keys(message) ⇒ Object
1093 1094 1095 1096 |
# File 'lib/mbt-gen.rb', line 1093 def list_keys() keys = collect_keys() puts "keys: #{keys.join(", ")}" end |
#list_validation_rules(message) ⇒ Object
1106 1107 1108 1109 1110 |
# File 'lib/mbt-gen.rb', line 1106 def list_validation_rules() rules = collect_validation_rules() puts "Validation Rules:" rules.each { |r| puts " #{r}" } end |
#max_constraint_for_expr(expr, upper_bound) ⇒ Object
152 153 154 |
# File 'lib/mbt-gen.rb', line 152 def max_constraint_for_expr(expr, upper_bound) "(<= #{expr} #{upper_bound})" end |
#maxLength_contraint_for_expr(expr, maxLength) ⇒ Object
160 161 162 |
# File 'lib/mbt-gen.rb', line 160 def maxLength_contraint_for_expr(expr, maxLength) "(<= (str.len #{expr}) #{maxLength})" end |
#min_constraint_for_expr(expr, lower_bound) ⇒ Object
148 149 150 |
# File 'lib/mbt-gen.rb', line 148 def min_constraint_for_expr(expr, lower_bound) "(>= #{expr} #{lower_bound})" end |
#oneOf_contraint_for_expr(expr, values) ⇒ Object
164 165 166 167 168 169 |
# File 'lib/mbt-gen.rb', line 164 def oneOf_contraint_for_expr(expr, values) list = values.map do |val| "(= #{expr} \"#{val}\")" end "(or #{list.join(" ")})" end |
#parse_field_value(fielddef, value) ⇒ Object
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 |
# File 'lib/mbt-gen.rb', line 716 def parse_field_value(fielddef, value) value = value.gsub("\n", "") datatype = fielddef[:datatype] case datatype when :int return Integer(value) when :string return value when :enum return value when :date return Date.parse(value) when :timestamp return Time.new(value) end end |
#prepare_output_doc_filename(number, output_dir) ⇒ Object
964 965 966 967 968 969 970 971 |
# File 'lib/mbt-gen.rb', line 964 def prepare_output_doc_filename(number, output_dir) chunk_number = number / 100000 dirname = "#{output_dir}/#{chunk_number}" unless Dir.exist?(dirname) then FileUtils.mkdir_p(dirname) end return "#{dirname}/doc#{number}.xml" end |
#raw_field(xpath) ⇒ Object
89 90 91 92 93 |
# File 'lib/mbt-gen.rb', line 89 def raw_field(xpath) path_str = "base" path_str = xpath.gsub("/", "-") if xpath "field-#{path_str}" end |
#read_docs_from_log_file(log_filename) ⇒ Object
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 |
# File 'lib/mbt-gen.rb', line 931 def read_docs_from_log_file(log_filename) result = [] if File.exist?(log_filename) then File.open(log_filename, "r") do |f| f.each_line do |line| doc = {} if line =~ /(.*)\ <-\ \{(.*)\}/ then filename = $1 combination = $2 combination.split(", ").each do |assignment| if assignment =~ /(.*):\ (.*)/ then key = $1 value = $2 if value =~ /\"(.*)\"/ then value = $1 elsif value == "nil" then value = nil end doc[key] = value else raise RuntimeError.new("could not parse logfile #{log_filename}: invalid assignment #{assignment.inspect}") end end else raise RuntimeError.new("could not parse logfile #{log_filename}: invalid line #{line.inspect}") end result << doc end end end return result end |
#regex_constraint_for_expr(expr, regex) ⇒ Object
156 157 158 |
# File 'lib/mbt-gen.rb', line 156 def regex_constraint_for_expr(expr, regex) "(str.in.re #{expr} #{Regexp_to_SMTLIB.translate_regexp_to_SMTLIB(regex)})" end |
#resolve_field_def(path, relative_to_struct, prefix) ⇒ Object
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 |
# File 'lib/mbt-gen.rb', line 430 def resolve_field_def(path, relative_to_struct, prefix) current = relative_to_struct result = nil path.split("/").each do |segment| unless current then raise RuntimeError.new("could not resolve segment #{segment.inspect} of field path: #{path.inspect}: resolution worked up until #{result.inspect}, but then the last segment was a field or list.") end field_def = current[segment.to_sym] unless field_def then raise RuntimeError.new("could not resolve segment #{segment.inspect} of field path: #{path.inspect}: structure #{prefix.inspect} does not have a member #{segment.to_sym.inspect}.") end if field_def[:type] == :structure then unless field_def[:ref] then raise RuntimeError.new("could not resolve field path: #{path.inspect}: substructure #{segment.inspect} of structure #{prefix.inspect} does not have a :ref.") end current = field_def[:ref] if prefix then prefix = "#{prefix}/#{segment}" else prefix = segment end elsif field_def[:type] == :field then current = nil result = field_def elsif field_def[:type] == :list then current = nil result = field_def end end return result end |
#resolve_field_path(path, relative_to_struct, prefix) ⇒ Object
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 |
# File 'lib/mbt-gen.rb', line 392 def resolve_field_path(path, relative_to_struct, prefix) current = relative_to_struct result = nil path.split("/").each do |segment| unless current then raise RuntimeError.new("could not resolve segment #{segment.inspect} of field path: #{path.inspect}: resolution worked up until #{result.inspect}, but then the last segment was a field or list.") end field_def = current[segment.to_sym] unless field_def then raise RuntimeError.new("could not resolve segment #{segment.inspect} of field path: #{path.inspect}: structure #{prefix.inspect} does not have a member #{segment.to_sym.inspect}.") end if field_def[:type] == :structure then unless field_def[:ref] then raise RuntimeError.new("could not resolve field path: #{path.inspect}: substructure #{segment.inspect} of structure #{prefix.inspect} does not have a :ref.") end current = field_def[:ref] if prefix then prefix = "#{prefix}/#{segment}" else prefix = segment end elsif field_def[:type] == :field then current = nil result = segment if prefix result = "#{prefix}/#{result}" end elsif field_def[:type] == :list then current = nil result = segment if prefix result = "#{prefix}/#{result}" end end end return result end |
#resolve_struct_def(path, relative_to_struct, prefix, context_desc = "") ⇒ Object
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 |
# File 'lib/mbt-gen.rb', line 498 def resolve_struct_def(path, relative_to_struct, prefix, context_desc = "") current = relative_to_struct result = nil path.split("/").each do |segment| unless current then raise RuntimeError.new("could not resolve field path: #{path.inspect} relative to struct #{relative_to_struct.inspect} #{context_desc}") end if segment == "." then result = current elsif segment == ".." then current = current[:parent_link] if prefix then prefix_segs = prefix.split("/") prefix = prefix_segs[0,prefix_segs.size()-1].join("/") else prefix = current[:struct_xpath_prefix] end else field_def = current[segment.to_sym] unless field_def then raise RuntimeError.new("could not resolve segment #{segment.inspect} of field path: #{path.inspect} relative to struct #{relative_to_struct.inspect} #{context_desc}") end if field_def[:type] == :structure then current = field_def[:ref] if prefix then prefix = "#{prefix}/#{segment}" else prefix = segment end result = current end end end return result end |
#resolve_struct_path(path, relative_to_struct, prefix) ⇒ Object
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 |
# File 'lib/mbt-gen.rb', line 462 def resolve_struct_path(path, relative_to_struct, prefix) current = relative_to_struct result = nil path.split("/").each do |segment| unless current then raise RuntimeError.new("could not resolve field path: #{path.inspect} relative to struct #{relative_to_struct.inspect}") end if segment == "." then result = current[:struct_xpath_prefix] elsif segment == ".." then current = current[:parent_link] if prefix then prefix_segs = prefix.split("/") prefix = prefix_segs[0,prefix_segs.size()-1].join("/") else prefix = current[:struct_xpath_prefix] end else field_def = current[segment.to_sym] unless field_def then raise RuntimeError.new("could not resolve segment #{segment.inspect} of field path: #{path.inspect} relative to struct #{relative_to_struct.inspect}") end if field_def[:type] == :structure then current = field_def[:ref] if prefix then prefix = "#{prefix}/#{segment}" else prefix = segment end result = prefix end end end return result end |
#set_standard_options(progress, solver) ⇒ Object
808 809 810 811 812 |
# File 'lib/mbt-gen.rb', line 808 def (progress, solver) solver.to_solver(progress, "(set-option :produce-unsat-cores true) ; enable generation of unsat cores") solver.to_solver(progress, "(set-option :smt.core.minimize true) ; ensure that unsat cores are minimal") solver.to_solver(progress, "") end |
#size_var_for_list(xpath) ⇒ Object
109 110 111 |
# File 'lib/mbt-gen.rb', line 109 def size_var_for_list(xpath) "#{raw_field(xpath)}-size" end |
#solver_value_to_string(solver_value) ⇒ Object
733 734 735 736 737 738 739 |
# File 'lib/mbt-gen.rb', line 733 def solver_value_to_string(solver_value) if solver_value =~ /\"(.*)\"/ then return $1 else return solver_value end end |
#translate_datatype_to_SMTLIB(datatype) ⇒ Object
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
# File 'lib/mbt-gen.rb', line 117 def translate_datatype_to_SMTLIB(datatype) case datatype when :string return "String" when :int return "Int" when :bool return "Bool" when :date return "Int" when :timestamp return "Int" when :enum return "String" end end |
#translate_doc_to_SMTLIB(progress, solver, struct, doc, hash = {}) ⇒ Object
1735 1736 1737 1738 1739 1740 1741 |
# File 'lib/mbt-gen.rb', line 1735 def translate_doc_to_SMTLIB(progress, solver, struct, doc, hash = {}) = hash[:options] config = hash[:config] solver.to_solver(progress, "; --- Document: ---") translate_struct_in_doc_to_SMTLIB(progress, solver, struct, doc, nil, hash) end |
#translate_field_def_to_SMTLIB_constraints(progress, solver, fielddef, xpath) ⇒ Object
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 |
# File 'lib/mbt-gen.rb', line 175 def translate_field_def_to_SMTLIB_constraints(progress, solver, fielddef, xpath) varname = raw_field(xpath) if fielddef[:optional] == nil || fielddef[:optional] == false then # field is required assertionID = "required-#{varname}" info = { :assertion_type => :constraint, :xpath => xpath, :constraint_type => :required } solver.associateAssertionIDWith(assertionID, info) solver.to_solver(progress, "(assert (! #{varname}-filled :named #{assertionID}))") end datatype = fielddef[:datatype] case datatype when :int if fielddef[:min] then assertionID = "min-#{varname}" info = { :assertion_type => :constraint, :xpath => xpath, :datatype => :int, :value => fielddef[:min], :constraint_type => :min } solver.associateAssertionIDWith(assertionID, info) solver.to_solver(progress, "(assert (! (=> #{varname}-filled #{min_constraint_for_expr("#{varname}-value", translate_value_to_SMTLIB(fielddef[:min]))}) :named #{assertionID}))") end if fielddef[:max] then assertionID = "max-#{varname}" info = { :assertion_type => :constraint, :xpath => xpath, :datatype => :int, :value => fielddef[:max], :constraint_type => :max } solver.associateAssertionIDWith(assertionID, info) solver.to_solver(progress, "(assert (! (=> #{varname}-filled #{max_constraint_for_expr("#{varname}-value", translate_value_to_SMTLIB(fielddef[:max]))}) :named #{assertionID}))") end when :string if fielddef[:regex] then assertionID = "regex-#{varname}" info = { :assertion_type => :constraint, :xpath => xpath, :datatype => :string, :pattern => fielddef[:regex], :constraint_type => :regex } solver.associateAssertionIDWith(assertionID, info) solver.to_solver(progress, "(assert (! (=> #{varname}-filled #{regex_constraint_for_expr("#{varname}-value", fielddef[:regex])}) :named #{assertionID}))") end # TODO: minLength? if fielddef[:maxLength] then assertionID = "maxLength-#{varname}" info = { :assertion_type => :constraint, :xpath => xpath, :datatype => :string, :value => fielddef[:maxLength], :constraint_type => :maxLength } solver.associateAssertionIDWith(assertionID, info) solver.to_solver(progress, "(assert (! (=> #{varname}-filled #{maxLength_contraint_for_expr("#{varname}-value", fielddef[:maxLength])}) :named #{assertionID}))") end if fielddef[:from_list] then assertionID = "oneOf-#{varname}" list_filename = "#{LISTS_DIR}/#{fielddef[:from_list]}" info = { :assertion_type => :constraint, :xpath => xpath, :datatype => :string, :filename => list_filename, :constraint_type => :from_list } unless File.exist?(list_filename) raise RuntimeError.new("could not find list file #{list_filename}.") end values = File.read(list_filename).split("\n").map{|v| v.chomp()} solver.associateAssertionIDWith(assertionID, info) solver.to_solver(progress, "(assert (! (=> #{varname}-filled #{oneOf_contraint_for_expr("#{varname}-value", values)}) :named #{assertionID}))") end when :enum assertionID = "enum-#{varname}" info = { :assertion_type => :constraint, :xpath => xpath, :datatype => :enum, :values => fielddef[:values], :constraint_type => :values } solver.associateAssertionIDWith(assertionID, info) solver.to_solver(progress, "(assert (! (=> #{varname}-filled #{enum_constraint_for_expr("#{varname}-value", fielddef[:values])}) :named #{assertionID}))") end end |
#translate_list_def_to_SMTLIB_constraints(progress, solver, fielddef, varname) ⇒ Object
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 |
# File 'lib/mbt-gen.rb', line 272 def translate_list_def_to_SMTLIB_constraints(progress, solver, fielddef, varname) datatype = fielddef[:datatype] case datatype when :int if fielddef[:min] then fielddef[:model_maxLength].times do |i| solver.to_solver(progress, "(assert (! (=> (< #{i} #{varname}-size) #{min_constraint_for_expr("#{varname}-index-#{i}-value", translate_value_to_SMTLIB(fielddef[:min]))}) :named list-min-#{varname}-list-index-#{i}))") end end if fielddef[:max] then fielddef[:model_maxLength].times do |i| solver.to_solver(progress, "(assert (! (=> (< #{i} #{varname}-size) #{max_constraint_for_expr("#{varname}-index-#{i}-value", translate_value_to_SMTLIB(fielddef[:max]))}) :named list-max-#{varname}-list-index-#{i}))") end end when :string if fielddef[:regex] then fielddef[:model_maxLength].times do |i| solver.to_solver(progress, "(assert (! (=> (< #{i} #{varname}-size) #{regex_constraint_for_expr("#{varname}-index-#{i}-value", fielddef[:regex])}) :named list-regex-#{varname}-index-#{i}))") end end # TODO: minLength? if fielddef[:maxLength] then fielddef[:model_maxLength].times do |i| solver.to_solver(progress, "(assert (! (=> (< #{i} #{varname}-size) #{maxLength_contraint_for_expr("#{varname}-index-#{i}-value", fielddef[:maxLength])}) :named list-maxLength-#{varname}-index-#{i}))") end end when :enum fielddef[:model_maxLength].times do |i| solver.to_solver(progress, "(assert (! (=> (< #{i} #{varname}-size) #{enum_constraint_for_expr("#{varname}-index-#{i}-value", fielddef[:values])}) :named list-enum-#{varname}-index-#{i}))") end end end |
#translate_struct_in_doc_to_SMTLIB(progress, solver, struct, doc, prefix, hash = {}) ⇒ Object
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 |
# File 'lib/mbt-gen.rb', line 1743 def translate_struct_in_doc_to_SMTLIB(progress, solver, struct, doc, prefix, hash = {}) = hash[:options] config = hash[:config] struct.each do |key, value| next if key == :additional_smtlib || key == :validation_rules || key == :predicates || key == :parent_link || key == :struct_xpath_prefix if prefix then xpath = "#{prefix}/#{key.to_s}" else xpath = key.to_s end if value[:type] == :structure then node = doc.at_xpath(xpath) if node then info = { :assertion_type => :doc_structure_exists, :xpath => xpath, } assertionID = "doc-#{xpath.gsub('/', '-')}" solver.associateAssertionIDWith(assertionID, info) solver.to_solver(progress, "(assert (! (= #{exists_var_for_structure(xpath)} true) :named #{assertionID}))") translate_struct_in_doc_to_SMTLIB(progress, solver, value[:ref], doc, xpath, hash) else info = { :assertion_type => :doc_structure_not_exists, :xpath => xpath, } assertionID = "doc-#{xpath.gsub('/', '-')}" solver.associateAssertionIDWith(assertionID, info) solver.to_solver(progress, "(assert (! (= #{exists_var_for_structure(xpath)} false) :named #{assertionID}))") end elsif value[:type] == :field then node = doc.at_xpath(xpath) if node then fvalue = node.text info = { :assertion_type => :doc_field_filled, :xpath => xpath, :value => fvalue } fvalue_str = value_of_type(fvalue, value[:datatype]) assertionID = "doc-#{xpath.gsub('/', '-')}" solver.associateAssertionIDWith(assertionID, info) solver.to_solver(progress, "(assert (! (and (= #{filled_var_for_field(xpath)} true) (= #{value_var_for_field(xpath)} #{fvalue_str})) :named #{assertionID}))") else info = { :assertion_type => :doc_field_empty, :xpath => xpath, } assertionID = "doc-#{xpath.gsub('/', '-')}" solver.associateAssertionIDWith(assertionID, info) solver.to_solver(progress, "(assert (! (= #{filled_var_for_field(xpath)} false) :named #{assertionID}))") end elsif value[:type] == :list then node = doc.at_xpath(xpath) if node then fvalues = [] node.children.to_a.each do |c| next unless c.is_a?(Nokogiri::XML::Element) fvalues << c.text end info = { :assertion_type => :doc_list_filled, :xpath => xpath, :values => fvalues } fvalue_str = value_of_type(fvalues, value[:datatype]) assertionID = "doc-#{xpath.gsub('/', '-')}" solver.associateAssertionIDWith(assertionID, info) clauses = [] fvalues.each_with_index do |fvalue, index| clauses << "(= #{value_var_for_list(xpath,index)} #{value_of_type(fvalue, value[:datatype])})" end solver.to_solver(progress, "(assert (! (and (= #{filled_var_for_field(xpath)} true) (= #{size_var_for_list(xpath)} #{fvalues.size}) #{clauses.join(' ')}) :named #{assertionID}))") else info = { :assertion_type => :doc_field_empty, :xpath => xpath, } assertionID = "doc-#{xpath.gsub('/', '-')}" solver.associateAssertionIDWith(assertionID, info) solver.to_solver(progress, "(assert (! (= #{filled_var_for_field(xpath)} false) :named #{assertionID}))") end else raise RuntimeError.new("Model Error: encountered unknown type #{value[:type].inspect}") end end end |
#translate_structure_to_SMTLIB(progress, solver, struct, hash = {}) ⇒ Object
323 324 325 326 327 328 329 330 331 332 333 |
# File 'lib/mbt-gen.rb', line 323 def translate_structure_to_SMTLIB(progress, solver, struct, hash = {}) prefix = hash[:prefix] config = hash[:config] = hash[:options] translate_substructure_to_SMTLIB(progress, solver, struct, hash) translate_validation_rules_to_SMTLIB(progress, solver, struct, prefix, config, ) if [:add_SMTLIB] then solver.to_solver(progress, "; --- additional SMTLIB Code: ---") solver.to_solver(progress, [:add_SMTLIB]) end end |
#translate_substructure_to_SMTLIB(progress, solver, struct, hash = {}) ⇒ Object
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 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 |
# File 'lib/mbt-gen.rb', line 335 def translate_substructure_to_SMTLIB(progress, solver, struct, hash = {}) prefix = hash[:prefix] struct_varname = hash[:struct_varname] config = hash[:config] = hash[:options] solver.to_solver(progress, "; --- Structure: ---") struct.each do |field, definition| if field == :additional_smtlib then solver.to_solver(progress, "; additional SMTLIB of structure #{prefix}") solver.to_solver(progress, translate_validation_rule_to_SMTLIB(definition, struct, prefix, config, , "<additional SMTLIB of structure #{prefix}>")) elsif field == :validation_rules || field == :predicates || field == :parent_link || field == :struct_xpath_prefix next else solver.to_solver(progress, "; #{field.to_s}") if definition[:type] == :field then display_prefix = "" display_prefix = "#{prefix}/" if prefix xpath = field.to_s xpath = "#{prefix}/#{xpath}" if prefix solver.declare_const(progress, filled_var_for_field(xpath), "Bool", {:xpath => xpath}) solver.declare_const(progress, value_var_for_field(xpath), translate_datatype_to_SMTLIB(definition[:datatype]), {:xpath => xpath, :datatype => definition[:datatype]}) solver.to_solver(progress, "(assert (! (=> (not #{filled_var_for_field(xpath)}) (= #{value_var_for_field(xpath)} #{default_value_for_fielddef(definition)})) :named empty-field-has-no-value-for-#{raw_field(xpath)}))") if (struct_varname) solver.to_solver(progress, "(assert (! (=> (not #{struct_varname}) (not #{filled_var_for_field(xpath)})) :named empty-struct-has-no-fields-for-#{raw_field(xpath)}))") end translate_field_def_to_SMTLIB_constraints(progress, solver, definition, xpath) elsif definition[:type] == :list then display_prefix = "" display_prefix = "#{prefix}/" if prefix xpath = field.to_s xpath = "#{prefix}/#{xpath}" if prefix solver.declare_const(progress, filled_var_for_field(xpath), "Bool", {:xpath => xpath}) solver.declare_const(progress, size_var_for_list(xpath), "Int", {:xpath => xpath}) solver.to_solver(progress, "(assert (! (=> (not #{filled_var_for_field(xpath)}) (= #{size_var_for_list(xpath)} 0)) :named empty-list-field-has-zero-size-#{raw_field(xpath)}))") definition[:model_maxLength].times do |i| solver.declare_const(progress, value_var_for_list(xpath, i), translate_datatype_to_SMTLIB(definition[:datatype]), {:xpath => xpath, :xpath_element => definition[:xpath_element], :index => i, :datatype => definition[:datatype]}) solver.to_solver(progress, "(assert (! (=> (<= #{size_var_for_list(xpath)} #{i}) (= #{value_var_for_list(xpath, i)} #{default_value_for_fielddef(definition)})) :named empty-list-field-has-no-value-for-#{raw_field(xpath)}-index-#{i}))") end if (struct_varname) solver.to_solver(progress, "(assert (! (=> (not #{struct_varname}) (= #{size_var_for_list(xpath)} 0)) :named empty-struct-has-no-fields-for-#{raw_field(xpath)}))") end translate_list_def_to_SMTLIB_constraints(progress, solver, definition, raw_field(xpath)) elsif definition[:type] == :structure then xpath = field.to_s xpath = "#{prefix}/#{xpath}" if prefix solver.declare_const(progress, exists_var_for_structure(xpath), "Bool", {:xpath => xpath}) if (struct_varname) solver.to_solver(progress, "(assert (! (=> (not #{struct_varname}) (not #{exists_var_for_structure(xpath)})) :named empty-struct-has-no-substructure-#{raw_field(xpath)}))") end translate_substructure_to_SMTLIB(progress, solver, definition[:ref], :prefix => xpath, :struct_varname => exists_var_for_structure(xpath), :options => , :config => config) else next end end end end |
#translate_validation_rule_to_SMTLIB(rule, context_struct, prefix, config, options, rule_name) ⇒ Object
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 |
# File 'lib/mbt-gen.rb', line 550 def translate_validation_rule_to_SMTLIB(rule, context_struct, prefix, config, , rule_name) date_now = [:date_now] = [:timestamp_now] return rule.gsub(/FILLED\[[^\]]*\]/) do |m| unless m =~ /FILLED\[([^\]]*)\]/ then raise RuntimeError.new("could not parse FILLED[...]: #{m.inspect} in validation rule #{rule_name}") end field = resolve_field_path($1, context_struct, prefix) filled_var_for_field(field) end .gsub(/VALUE\[[^\]]*\]/) do |m| unless m =~ /VALUE\[([^\]]*)\]/ then raise RuntimeError.new("could not parse VALUE[...]: #{m.inspect} in validation rule #{rule_name}") end field = resolve_field_path($1, context_struct, prefix) value_var_for_field(field) end .gsub(/EXIST\[[^\]]*\]/) do |m| unless m =~ /EXIST\[([^\]]*)\]/ then raise RuntimeError.new("could not parse EXIST[...]: #{m.inspect} in validation rule #{rule_name}") end s = resolve_struct_path($1, context_struct, prefix) exists_var_for_structure(s) end .gsub(/SIZE\[[^\]]*\]/) do |m| unless m =~ /SIZE\[([^\]]*)\]/ then raise RuntimeError.new("could not parse SIZE[...]: #{m.inspect} in validation rule #{rule_name}") end l = resolve_field_path($1, context_struct, prefix) size_var_for_list(l) end .gsub(/LIST_CONTAINS\[[^\]]*,[^\]]*\]/) do |m| unless m =~ /LIST_CONTAINS\[([^\]]*),([^\]]*)\]/ then raise RuntimeError.new("could not parse LIST_CONTAINS[...]: #{m.inspect} in validation rule #{rule_name}") end l = resolve_field_path($1, context_struct, prefix) l_def = resolve_field_def($1, context_struct, prefix) value = $2 terms = [] l_def[:model_maxLength].times do |i| terms << "(and (< #{i} #{size_var_for_list(l)}) (= #{value_var_for_list(l, i)} #{value}))" end "(or #{terms.join(" ")})" end .gsub(/LIST_VALUE_FIRST_ELEMENT\[[^\]]*\]/) do |m| unless m =~ /LIST_VALUE_FIRST_ELEMENT\[([^\]]*)\]/ then raise RuntimeError.new("could not parse LIST_VALUE_FIRST_ELEMENT[...]: #{m.inspect} in validation rule #{rule_name}") end xpath = $1 l = resolve_field_path(xpath, context_struct, prefix) value_var_for_list(l, 0) end .gsub("[Date.now]", date_now.to_s) .gsub("[Timestamp.now]", .to_s) .gsub(/PREDICATE\[[^\]]*,[^\]]*\]/) do |m| unless m =~ /PREDICATE\[([^\]]*),([^\]]*)\]/ then raise RuntimeError.new("could not parse PREDICATE[...]: #{m.inspect} in validation rule #{rule_name}") end path = $1 key = $2.strip().to_sym sdef = resolve_struct_def(path, context_struct, prefix, "in validation rule #{rule_name}") unless sdef raise RuntimeError.new("could not resolve struct path #{path.inspect} in validation rule #{rule_name}") end preds = sdef[:predicates] mdk = preds[key] if mdk then if mdk[:smtlib] then translate_validation_rule_to_SMTLIB(mdk[:smtlib], sdef, sdef[:struct_xpath_prefix], config, , "#{rule_name}.predicate.#{key}[#{sdef[:struct_xpath_prefix]}]" ) else raise RuntimeError.new("Predicate #{key} for structure #{sdef[:struct_xpath_prefix]} does not have an SMTLIB definition, but is referenced in validation rule #{rule_name}") end else raise RuntimeError.new("No predicate #{key.inspect} defined for structure #{sdef[:struct_xpath_prefix]}, but one referenced in validation rule #{rule_name}") end end .gsub(/CONFIG\[[^\]]*\]/) do |m| unless m =~ /CONFIG\[([^\]]*)\]/ then raise RuntimeError.new("could not parse LIST_CONTAINS[...]: #{m.inspect} in validation rule #{rule_name}") end key = $1.to_sym if config.has_key?(key) then "\"#{config[key]}\"" else raise RuntimeError.new("unknown CONFIG-key #{key.inspect} encountered in validation rule #{rule_name}" ) end end .gsub(/FIELD_IN_QUERY\[[^\]]*\]/) do |m| unless m =~ /FIELD_IN_QUERY\[([^\]]*),([^\]]*)\]/ then raise RuntimeError.new("could not parse FIELD_IN_QUERY[..,..]: #{m.inspect} in validation rule #{rule_name}") end xpath = $1 query_filename = $2 fpath = resolve_field_path(xpath, context_struct, prefix) fdef = resolve_field_def(xpath, context_struct, prefix) values = File.read("#{QUERY_DIR}/#{query_filename.strip()}").split("\n") if fdef[:datatype] == :string then terms = values.filter{|l| !l.start_with?("#")}.map do |val| "(= #{value_var_for_field(fpath)} \"#{val}\")" end elsif fdef[:datatype] == :int then terms = values.filter{|l| !l.start_with?("#")}.map do |val| "(= #{value_var_for_field(fpath)} #{Integer(val)})" end else raise RuntimeError.new("FIELD_IN_QUERY[] was applied to a field of datatype #{fdef[:datatype].inspect}. However, it can only be applied to fields of datatype string or int.") end "(or #{terms.join(" ")})" end .gsub(/FIELD_IN_SMTLIB_PARAMETERIZED_QUERY\[[^\]]*\]/) do |m| unless m =~ /FIELD_IN_SMTLIB_PARAMETERIZED_QUERY\[([^\]]*),([^\]]*),([^\]]*)\]/ then raise RuntimeError.new("could not parse FIELD_IN_SMTLIB_PARAMETERIZED_QUERY[..,..,..]: #{m.inspect} in validation rule #{rule_name}") end field_xpath = $1 param_smtlib = $2 query_filename = $3 fpath = resolve_field_path(field_xpath.strip(), context_struct, prefix) fdef = resolve_field_def(field_xpath.strip(), context_struct, prefix) query_result = YAML.load_file("#{PARAMETERIZED_QUERY_DIR}/#{query_filename.strip()}") terms = [] if fdef[:datatype] == :string then terms << "(or #{query_result.keys.map { |key| "(= #{param_smtlib} \"#{key}\")" }.join(" ")})" query_result.each_pair do |key, values| terms << "(=> (= #{param_smtlib} \"#{key}\") (or #{values.map{ |v| "(= #{value_var_for_field(fpath)} \"#{v}\")" }.join(" ")}))" end else raise RuntimeError.new("FIELD_IN_SMTLIB_PARAMETERIZED_QUERY[] was applied to a field of datatype #{fdef[:datatype].inspect}. However, it can only be applied to fields of datatype string.") end "(and #{terms.join(" ")})" end .gsub(/CONFIG_IN_QUERY\[[^\]]*\]/) do |m| unless m =~ /CONFIG_IN_QUERY\[([^\]]*),([^\]]*)\]/ then raise RuntimeError.new("could not parse CONFIG_IN_QUERY[..,..]: #{m.inspect} in validation rule #{rule_name}") end key = $1.to_sym unless config.has_key?(key) then raise RuntimeError.new("unknown CONFIG key #{key.inspect} encountered in validation rule #{rule_name}") end query_filename = $2 values = File.read("#{QUERY_DIR}/#{query_filename.strip()}").split("\n") terms = values.filter{|l| !l.start_with?("#")}.map do |val| "(= \"#{config[key]}\" \"#{val}\")" end "(or #{terms.join(" ")})" end end |
#translate_validation_rules_for_structure_to_SMTLIB(progress, solver, struct, prefix, config, options) ⇒ Object
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 |
# File 'lib/mbt-gen.rb', line 697 def translate_validation_rules_for_structure_to_SMTLIB(progress, solver, struct, prefix, config, ) return unless struct[:validation_rules] solver.to_solver(progress, "; --- Validation Rules: ---") negated_rules = [:negated_validation_rules] || [] solver.to_solver(progress, "; negated rules: #{negated_rules.empty? ? "<none>" : negated_rules.join(", ")}") rules = struct[:validation_rules] rules.each do |rule_name, rule| rule = rule[:smtlib] # ignore the text representation next unless rule # warning about this omission is the job of validate_model() rule_SMTLIB = translate_validation_rule_to_SMTLIB(rule, struct, prefix, config, , rule_name) if negated_rules.include?(rule_name) then rule_SMTLIB = "(not #{rule_SMTLIB})" end solver.to_solver(progress, "(assert (! #{rule_SMTLIB} :named validation_rule_#{rule_name}_instance_#{prefix.gsub("/", "_")}))") end end |
#translate_validation_rules_to_SMTLIB(progress, solver, struct, prefix, config, options) ⇒ Object
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 |
# File 'lib/mbt-gen.rb', line 534 def translate_validation_rules_to_SMTLIB(progress, solver, struct, prefix, config, ) solver.to_solver(progress, "; --- Validation Rules ---") translate_validation_rules_for_structure_to_SMTLIB(progress, solver, struct, prefix, config, ) struct.each_pair do |key, value| next if key == :validation_rules || key == :predicates || key == :parent_link || key == :struct_xpath_prefix || key == :additional_smtlib if value[:type] == :structure then if prefix then new_prefix = "#{prefix.to_s}/#{key}" else new_prefix = key.to_s end translate_validation_rules_to_SMTLIB(progress, solver, value[:ref], new_prefix, config, ) end end end |
#translate_value_to_SMTLIB(value) ⇒ Object
134 135 136 137 138 139 140 141 142 143 144 145 146 |
# File 'lib/mbt-gen.rb', line 134 def translate_value_to_SMTLIB(value) if value.is_a?(Integer) then return value.to_s elsif value.is_a?(String) then return value.inspect elsif value.is_a?(Date) then return (value - (Time.at(0).to_date)).to_i # days since 1970.01.01 elsif value.is_a?(Time) then return value.to_i else raise RuntimeError.new("cannot translate value to SMTLIB: #{value.inspect}") end end |
#validate_doc(progress, struct, doc, options, config) ⇒ Object
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 |
# File 'lib/mbt-gen.rb', line 1833 def validate_doc(progress, struct, doc, , config) [:solverLog] = "validation.smt2" z3path = config[:z3path] || DEFAULT_Z3_PATH z3 = Z3Solver.new(progress, z3path) begin result = z3.query(progress, ) do |solver| (progress, solver) translate_structure_to_SMTLIB(progress, solver, struct, :options => , :config => config) translate_doc_to_SMTLIB(progress, solver, struct, doc, :options => , :config => config) solver.to_solver(progress, "") end unless result == true then raise FatalError.new("VALIDATION FAILED! SMTLIB log was written to #{[:solverLog]}.\n\n#{result}") end ensure z3.close() end return true end |
#validate_doc_against_schema(struct, doc) ⇒ Object
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 |
# File 'lib/mbt-gen.rb', line 1656 def validate_doc_against_schema(struct, doc) root = doc.root sdef = struct[root.name.to_sym] unless sdef[:type] == :structure then puts "ERROR: schema validation failed: root element should be a structure" end # first, check that each doc element is defined for the struct validate_doc_struct_against_schema(sdef[:ref], root, root.name) # second, check that all required elements from the struct are actually present in the doc validate_schema_against_doc_struct(sdef[:ref], root, root.name) end |
#validate_doc_struct_against_schema(struct, doc, prefix = nil) ⇒ Object
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 |
# File 'lib/mbt-gen.rb', line 1668 def validate_doc_struct_against_schema(struct, doc, prefix = nil) doc.children.to_a.filter{|x| x.is_a?(Nokogiri::XML::Element) }.each do |c| fdef = struct[c.name.to_sym] if prefix then xpath = "#{prefix}/#{c.name}" else xpath = c.name end if fdef if fdef[:type] == :structure then return unless validate_doc_struct_against_schema(fdef[:ref], c, xpath) end else if prefix then xpath = "#{prefix}/#{c.name}" else xpath = c.name end raise FatalError.new("ERROR: schema validation failed: #{c.name} of #{xpath} is present in document, but not defined in schema.") end end end |
#validate_model(message, prefix = nil) ⇒ Object
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 |
# File 'lib/mbt-gen.rb', line 1607 def validate_model(, prefix=nil) .each_pair do |key, value| if key == :validation_rules then value.each_pair do |vr_key, vr_value| unless vr_value[:text] && vr_value[:text] != "" then puts "INFO: Model Problem: validation rule #{vr_key} does not have a textual representation." end unless vr_value[:smtlib] && vr_value[:smtlib] != "" then puts "WARN: Model Problem: validation rule #{vr_key} does not have an SMTLIB representation. It will hence be omitted!" end end elsif key == :predicates then value.each_pair do |mkey, mvalue| next unless mvalue unless mvalue[:text] && mvalue[:text] != "" then puts "INFO: Model Problem: structure #{prefix}'s predicate #{mkey} does not have a textual representation." end unless mvalue[:smtlib] && mvalue[:smtlib] != "" then puts "WARN: Model Problem: structure #{prefix}'s predicate #{mkey} does not have an SMTLIB representation. It will be regarded as always true." end end elsif key == :parent_link || key == :struct_xpath_prefix || key == :additional_smtlib next else if value[:type] == :structure then unless value[:ref] then raise RuntimeError.new("Model Problem: encountered structure without a :ref (key=#{key.inspect}, value=#{value.inspect})") end if prefix then new_prefix = "#{prefix}/#{key}" else new_prefix = key end validate_model(value[:ref], new_prefix) elsif value[:type] == :field then unless value[:datatype] then raise RuntimeError.new("Model Problem: encountered field without a :datatype (key=#{key.inspect}, value=#{value.inspect})") end if value[:datatype] == :enum then unless value[:values] then raise RuntimeError.new("Model Problem: encountered enum field without a :values (key=#{key.inspect}, value=#{value.inspect})") end end end end end end |
#validate_schema_against_doc_struct(struct, doc, prefix = nil) ⇒ Object
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 |
# File 'lib/mbt-gen.rb', line 1691 def validate_schema_against_doc_struct(struct, doc, prefix = nil) struct.each do |key, value| next if key == :additional_smtlib || key == :validation_rules || key == :predicates || key == :parent_link || key == :struct_xpath_prefix if prefix then xpath = "#{prefix}/#{key}" else xpath = key end if value[:type] == :structure then node = doc.at_xpath(key.to_s) if node then validate_schema_against_doc_struct(value[:ref], node, xpath) else if value[:optional] == false then raise FatalError.new("ERROR: schema validation failed: non-optional structure #{xpath} not found in doc.") end end elsif value[:type] == :field then if value[:optional] == false then unless doc.at_xpath(key.to_s) then raise FatalError.new("ERROR: schema validation failed: non-optional field #{xpath} not found in doc.") end end elsif value[:type] == :list then if value[:optional] == false then unless doc.at_xpath(key.to_s) then raise FatalError.new("ERROR: schema validation failed: non-optional list #{xpath} not found in doc.") end end list = doc.at_xpath(key.to_s) if list then list.children.to_a.each do |c| next unless c.is_a?(Nokogiri::XML::Element) unless c.name == value[:xpath_element] then raise FatalError.new("ERROR: schema validation failed: encountered element #{c.name} in list #{xpath}, which should only contain #{value[:xpath_element]} elements.") end end end else raise RuntimeError.new("Model error: encountered element #{xpath} of unknown type: #{value[:type]}.") end end end |
#value_of_type(value, type) ⇒ Object
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 |
# File 'lib/mbt-gen.rb', line 1112 def value_of_type(value, type) if type == :string or type == :enum then "\"#{value}\"" elsif type == :int then value.to_s elsif type == :date then (Date.parse(value) - Time.at(0).to_date).to_i.to_s elsif type == :timestamp then (Time.new(value) - Time.at(0)).to_i.to_s else raise RuntimeError.new("encountered unknown :datatype #{type.inspect}") end end |
#value_var_for_field(xpath) ⇒ Object
99 100 101 |
# File 'lib/mbt-gen.rb', line 99 def value_var_for_field(xpath) "#{raw_field(xpath)}-value" end |
#value_var_for_list(xpath, index) ⇒ Object
113 114 115 |
# File 'lib/mbt-gen.rb', line 113 def value_var_for_list(xpath, index) "#{raw_field(xpath)}-index-#{index}-value" end |
#values_for_key_field(field) ⇒ Object
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 |
# File 'lib/mbt-gen.rb', line 973 def values_for_key_field(field) if field[:type] == :field then if field[:datatype] == :enum then if field[:optional] then return field[:values] + [nil] else return field[:values] end elsif field[:datatype] == :int then if field.has_key?(:min) and field.has_key?(:max) and field[:min] <= field[:max] then return (field[:min]..field[:max]).to_a else raise RuntimeError.new("cannot determine values for unbounded :int field") end else raise RuntimeError.new("cannot determine values for datatype #{field[:datatype].inspect}") end elsif field[:type] == :structure then if field[:optional] then return [true, false] else return [true] end else raise RuntimeError.new("Encountered unknown :type in model: #{field[:type].inspect} - keys can only mark fields or structures.") end end |
#z3ValueToRubyValue(value) ⇒ Object
847 848 849 850 851 852 853 854 855 856 857 858 859 |
# File 'lib/mbt-gen.rb', line 847 def z3ValueToRubyValue(value) if value =~ /\"(.*)\"/ then # string return $1 elsif value =~ /\d+/ then # int return Integer(value) elsif value == "true" return true elsif value == "false" then return false else raise RuntimeError.new("enountered unknown type of value in z3 model: #{value.inspect}") end end |