grammar Canql

include Registry
include Patient
include Provider
include Anomaly
include GeneticTest
include TestResult
include TestResultGroup
include HesEvent
include Dates
include EBaseRecords
include BatchTypes
include PerinatalHospital
include Age

# The root grammar
rule query
  case_query / patient_query
end

rule case_query
  quantity:record_count? pre:case_preconditions* cases_keyword post:case_additional_conditions* case_with_clause?
end

rule patient_query
  quantity:record_count? pre:patient_preconditions* patient_keyword post:patient_additional_conditions* patient_with_clause?
end

rule word_break
  !(!(' '/',') .)
end

rule space
  ' '+
end

rule comma
  space? (',' / 'and') space?
end

rule number
  [0-9]+
end

rule record_count
  all_keyword
  /
  'first' space number <Nodes::RecordCountNode>
end

rule all_keyword
   'all' word_break
end

rule cases_keyword
   space subject:('cases' / 'babies') word_break <Nodes::SubjectNode>
end

rule patient_keyword
  space subject:'patients' word_break <Nodes::SubjectNode>
end

rule case_preconditions
  registry / gender / outcome / primacy / category
end

rule patient_preconditions
   gender / primacy / category
end

rule case_additional_conditions
  and_keyword? (expected / with_birth_date / with_death_date)
end

rule patient_additional_conditions
  and_keyword? (with_birth_date / with_death_date)
end

rule case_with_clause
  with_keyword post:case_with_conditions+ <Nodes::WithConditions>
end

rule patient_with_clause
  with_keyword post:patient_with_conditions+ <Nodes::WithConditions>
end

rule with_keyword
   space 'with' word_break
end

rule and_keyword
   space 'and' word_break
end

rule existance_keyword
   space ('missing' / ('field' 's'?) / 'populated') word_break
end

rule no_keyword
   space 'no' word_break
end

rule prenatal_keyword
  space 'prenatal' word_break
end

rule postnatal_keyword
  space 'postnatal' word_break
end

rule suspected_keyword
  space 'suspected' word_break
end

rule confirmed_keyword
  space 'confirmed' word_break
end

rule probable_keyword
  space 'probable' word_break
end

rule diagnosed_keyword
  space 'diagnosed' word_break
end

rule at_keyword
  space 'at' word_break
end

rule case_with_conditions
   anomalies / genetic_tests / test_results / perinatal_hospital /
   case_field_existance / test_acceptance_existance / test_result_groups /
   mother_conditions / action_or_ebr / hes_events
end

rule patient_with_conditions
   anomalies / genetic_tests / test_results / patient_field_existance /
   action_or_ebr / hes_events
end

end