@@ -765,25 +765,49 @@ instance
765765
766766else instance
767767 ( Symbol.Cons h t tail
768− , ExtractUntilParenGo h t "" args afterParen
768+ , ExtractUntilParenGo h t "" Z args afterParen
769769 ) =>
770770 ExtractUntilParen tail args afterParen
771771
772−class ExtractUntilParenGo :: Symbol -> Symbol -> Symbol -> Symbol -> Symbol -> Constraint
773−class ExtractUntilParenGo head tail acc args afterParen | head tail acc -> args afterParen
772+-- Peano depth counter for nested parentheses
773+data Z
774+data S :: Type -> Type
775+data S n
774776
775−instance ExtractUntilParenGo ")" tail acc acc tail
777+class ExtractUntilParenGo :: Symbol -> Symbol -> Symbol -> Type -> Symbol -> Symbol -> Constraint
778+class ExtractUntilParenGo head tail acc depth args afterParen | head tail acc depth -> args afterParen
776779
780+-- ) at depth zero: done
781+instance ExtractUntilParenGo ")" tail acc Z acc tail
782+
783+-- ) at depth > 0: decrement depth, keep going
784+else instance
785+ ( Symbol.Append acc ")" acc'
786+ , Symbol.Cons nextH nextT tail
787+ , ExtractUntilParenGo nextH nextT acc' n args afterParen
788+ ) =>
789+ ExtractUntilParenGo ")" tail acc (S n) args afterParen
790+
791+-- ( : increment depth, keep going
792+else instance
793+ ( Symbol.Append acc "(" acc'
794+ , Symbol.Cons nextH nextT tail
795+ , ExtractUntilParenGo nextH nextT acc' (S depth) args afterParen
796+ ) =>
797+ ExtractUntilParenGo "(" tail acc depth args afterParen
798+
799+-- Unclosed paren at end of input
777800else instance
778801 Fail (Text "Unclosed parenthesis in SELECT clause") =>
779− ExtractUntilParenGo h "" acc args afterParen
802+ ExtractUntilParenGo h "" acc depth args afterParen
780803
804+-- Any other char: accumulate
781805else instance
782806 ( Symbol.Append acc h acc'
783807 , Symbol.Cons nextH nextT tail
784− , ExtractUntilParenGo nextH nextT acc' args afterParen
808+ , ExtractUntilParenGo nextH nextT acc' depth args afterParen
785809 ) =>
786− ExtractUntilParenGo h tail acc args afterParen
810+ ExtractUntilParenGo h tail acc depth args afterParen
787811
788812-- Resolve aggregate argument: "*" -> Star, column ref -> unwrapped type
789813data Star