Theory TIGER_Rules

(* Author: Basil Fürer *)

theory TIGER_Rules
  imports TIGER_Lexer.TIGER_Spec
begin

section ‹Rule actions from mode operations›

text ‹Rule actions built from three parts: the token kind of the lexeme, a guard on the
  lexeme and an effect on the mode stack. The
  effects are flex's: keep the stack, replace the top (‹BEGIN›), push or pop
  cite‹‹Sect.~10› in "paxson2026-flex-manual"›, or any function on the stack.

  A hook of type typ‹'k option ⇒ 'm ⇒ 'm› computes the new top from the kind of
  the lexeme when the rule names no mode. It is lex's user flag
  cite‹‹Sect.~10› in "lesk1975-lex"› made pure: a flag set in every action is a
  function of the token.›

datatype 'm effect = Keep | Begin 'm | Push 'm | Pop | Stack ‹'m list ⇒ 'm list›

fun apply_effect ::
  ‹('k option ⇒ 'm ⇒ 'm) ⇒ 'm effect ⇒ 'k option ⇒ 'm list ⇒ 'm list›
where
  apply_effect_Keep: ‹apply_effect h Keep k (m # st) = h k m # st›
| apply_effect_Begin: ‹apply_effect h (Begin m') k (m # st) = m' # st›
| apply_effect_Push: ‹apply_effect h (Push m') k st = m' # st›
| apply_effect_Pop: ‹apply_effect h Pop k (m # m' # st) = h k m' # st›
| apply_effect_Stack: ‹apply_effect h (Stack f) k st = f st›
| apply_effect_Pop_last: ‹apply_effect h Pop k [m] = []›
| apply_effect_Nil: ‹apply_effect h e k [] = []›

text ‹The stack after an effect. The hook gives the top after const‹Keep› and
  const‹Pop›, a named mode is taken as it is. A pop of the last mode is the empty
  stack, which the driver rejects (flex aborts on an empty start condition stack cite‹‹Sect.~10› in "paxson2026-flex-manual"›).›

definition mk_act ::
  ‹('k option ⇒ 'm ⇒ 'm) ⇒ ('ch list ⇒ 'k option) ⇒ ('ch list ⇒ bool) ⇒
    'm effect ⇒ 'ch list ⇒ 'm list ⇒ 'k option × 'm list›
where
  ‹mk_act h kind guard e u st =
    (if guard u then (kind u, apply_effect h e (kind u) st) else (None, []))›

text ‹The action of a rule with kind ‹kind›, guard ‹guard› and effect ‹e›. A lexeme that
  fails the guard gives the empty stack, so the driver stops there. The guard cannot fall
  back to another rule, as flex's ‹yyreject()› (formerly ‹REJECT›) does
  cite‹‹Sect.~8› in "paxson2026-flex-manual"›. A failed guard plays the part of a
  Verbatim++ semantic action that returns ‹None› on an ill-formed lexeme
  cite‹‹Sect.~6› in "egolf2022-verbatim-plus-plus"›. Both fail safely, but Verbatim++ then
  rejects the whole input, while here lexing stops at the lexeme and leaves a residue.›

end