Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Search iOS9// File : Core/Sources/SPSearchKit/QuerySyntax.swift10// Description : Reading of the query syntax (terms, phrases, exclusions,11// operators) for highlighting and query rewriting.12// Module : SPSearchKit13// Repository : https://git.spboucher.ai/sp-search-ios14// Project Website : https://search.spboucher.ai15// Created : 2026-12-0116// Last Modified : 2026-12-0117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author : Simon-Pierre Boucher23// Position : Professor of Finance24// Institution : Université du Québec en Outaouais (UQO)25// Department : Département des sciences administratives26// Organization : SP Boucher27//28// Website : https://spboucher.ai29// Git : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General : info@spboucher.ai36// Professional : contact@spboucher.ai37// Direct : simon@spboucher.ai38// Research : research@spboucher.ai39// Development : dev@spboucher.ai40// Support : support@spboucher.ai41// Security/Admin : admin@spboucher.ai42// Notifications : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification : Public69// Distribution : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License : None specified (no license file in this repository)83// Maintainer : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation9192public enum QueryToken: Sendable, Hashable {93 case term(String)94 case phrase(String)95 case excluded(String)96 /// `site:`, `intitle:` or `lang:` with its value.97 case op(name: String, value: String)98}99100public enum QuerySyntax {101 public static let operators = ["site", "intitle", "lang"]102 private static let quotes: Set<Character> = ["\"", "“", "”", "«", "»"]103104 /// An unclosed quotation mark runs to the end of the query, as the engine reads it.105 public static func tokens(_ query: String) -> [QueryToken] {106 var out: [QueryToken] = []107 var i = query.startIndex108 func skipSpaces() { while i < query.endIndex, query[i].isWhitespace { i = query.index(after: i) } }109 func readQuoted() -> String {110 i = query.index(after: i)111 let start = i112 while i < query.endIndex, !quotes.contains(query[i]) { i = query.index(after: i) }113 let s = String(query[start..<i])114 if i < query.endIndex { i = query.index(after: i) }115 return s.split(whereSeparator: \.isWhitespace).joined(separator: " ")116 }117 func readWord() -> String {118 let start = i119 while i < query.endIndex, !query[i].isWhitespace, !quotes.contains(query[i]) { i = query.index(after: i) }120 return String(query[start..<i])121 }122 while true {123 skipSpaces()124 guard i < query.endIndex else { break }125 var negative = false126 if query[i] == "-", query.index(after: i) < query.endIndex, !query[query.index(after: i)].isWhitespace {127 negative = true128 i = query.index(after: i)129 }130 if quotes.contains(query[i]) {131 let p = readQuoted()132 if !p.isEmpty { out.append(negative ? .excluded(p) : .phrase(p)) }133 continue134 }135 let word = readWord()136 if word.isEmpty { i = query.index(after: i); continue }137 if let colon = word.firstIndex(of: ":") {138 let name = word[..<colon].lowercased()139 if operators.contains(name) {140 var value = String(word[word.index(after: colon)...])141 if value.isEmpty, i < query.endIndex, quotes.contains(query[i]) { value = readQuoted() }142 if negative { out.append(.excluded(value)) } else { out.append(.op(name: name, value: value)) }143 continue144 }145 }146 out.append(negative ? .excluded(word) : .term(word))147 }148 return out149 }150151 /// What may be marked in a title or a snippet: terms, whole phrases and `intitle:` values; never exclusions.152 public static func highlightTerms(_ query: String) -> [String] {153 var seen = Set<String>()154 var out: [String] = []155 func add(_ s: String) {156 let t = s.trimmingCharacters(in: CharacterSet.punctuationCharacters.union(.whitespaces))157 guard t.count >= 2 || t.unicodeScalars.contains(where: { $0.value > 0x2E80 }) else { return }158 if seen.insert(Highlighter.fold(t)).inserted { out.append(t) }159 }160 for token in tokens(query) {161 switch token {162 case .term(let t): add(t)163 case .phrase(let p): add(p)164 case .op(let name, let value) where name == "intitle": add(value)165 default: break166 }167 }168 return out169 }170171 /// The query restricted to one site; a previous `site:` is replaced.172 public static func restricting(_ query: String, toSite domain: String) -> String {173 var parts: [String] = []174 for token in tokens(query) {175 switch token {176 case .term(let t): parts.append(t)177 case .phrase(let p): parts.append("\"\(p)\"")178 case .excluded(let e): parts.append(e.contains(" ") ? "-\"\(e)\"" : "-\(e)")179 case .op(let name, let value): if name != "site" { parts.append("\(name):\(value)") }180 }181 }182 parts.append("site:\(domain)")183 return parts.joined(separator: " ")184 }185186 /// Text of the field after an operator chip is tapped: the operator starts a new word.187 public static func appending(_ fragment: String, to text: String) -> String {188 if text.isEmpty || text.last?.isWhitespace == true { return text + fragment }189 return text + " " + fragment190 }191}192