from __future__ import annotations

from collections import deque
from dataclasses import dataclass
import unicodedata

# 用空元组表示 epsilon 产生式，便于统一处理。
EPSILON = "ε"
END_MARKER = "#"
ITEM_DOT = "·"


@dataclass(frozen=True)
class Production:
    """一条产生式，同时记录它在分析表中的编号。"""

    index: int
    left: str
    right: tuple[str, ...]

    def display(self) -> str:
        """把产生式格式化成便于展示的字符串。"""
        right_text = " ".join(self.right) if self.right else EPSILON
        return f"{self.left} -> {right_text}"

    def numbered_display(self) -> str:
        """带编号输出，方便和 r1、r2 之类的归约动作对应。"""
        return f"{self.index}: {self.display()}"


@dataclass(frozen=True)
class Item:
    """LR(0) 项目，例如 E -> E · + T。"""

    production_index: int
    dot: int


@dataclass(frozen=True)
class Action:
    """SLR(1) 分析表中的一个 ACTION 表项。"""

    kind: str
    target: int | None = None

    def short(self) -> str:
        """输出表中常见的简写形式，例如 s5、r3、acc。"""
        if self.kind == "shift":
            return f"s{self.target}"
        if self.kind == "reduce":
            return f"r{self.target}"
        return "acc"


@dataclass
class AnalysisStep:
    """记录 SLR(1) 表驱动分析过程中的一步。"""

    step_no: int
    state_stack: str
    symbol_stack: str
    remaining_input: str
    action: str


@dataclass
class ParseResult:
    """保存一次输入串分析的完整结果。"""

    original_sentence: str
    normalized_sentence: str
    accepted: bool
    message: str
    steps: list[AnalysisStep]


class SLRGrammar:
    """一个尽量小而清晰的 SLR(1) 文法工具类。"""

    def __init__(
        self,
        productions: dict[str, list[tuple[str, ...]]],
        start_symbol: str,
        terminal_order: list[str] | None = None,
    ) -> None:
        self.productions = productions
        self.start_symbol = start_symbol
        self.nonterminals = list(productions.keys())
        self.nonterminal_set = set(self.nonterminals)

        self.augmented_start_symbol = self._build_augmented_start_symbol()
        self.all_nonterminals = [self.augmented_start_symbol] + self.nonterminals
        self.all_nonterminal_set = set(self.all_nonterminals)

        auto_terminals: list[str] = []
        for alternatives in productions.values():
            for right in alternatives:
                for symbol in right:
                    if symbol in self.nonterminal_set or symbol == EPSILON:
                        continue
                    if symbol not in auto_terminals:
                        auto_terminals.append(symbol)

        self.terminals = terminal_order or auto_terminals
        self.production_list = self._build_production_list()
        self.production_indexes_by_left = self._build_production_indexes_by_left()

    def _build_augmented_start_symbol(self) -> str:
        """构造一个不会和原文法冲突的扩广开始符号。"""
        candidate = f"{self.start_symbol}'"
        while candidate in self.productions:
            candidate += "'"
        return candidate

    def _normalize_right(self, right: tuple[str, ...]) -> tuple[str, ...]:
        """允许用户把 epsilon 写成空元组或显式的 ε。"""
        if right == (EPSILON,):
            return ()
        return right

    def _build_production_list(self) -> list[Production]:
        """
        构造产生式编号表。

        约定：
        - 0 号产生式是扩广文法：S' -> S
        - 1 号及以后才是原文法中的产生式
        """
        production_list = [
            Production(0, self.augmented_start_symbol, (self.start_symbol,))
        ]

        next_index = 1
        for left, alternatives in self.productions.items():
            for right in alternatives:
                production_list.append(
                    Production(next_index, left, self._normalize_right(right))
                )
                next_index += 1

        return production_list

    def _build_production_indexes_by_left(self) -> dict[str, list[int]]:
        """按左部归类产生式，便于 closure 直接查找。"""
        mapping = {left: [] for left in self.all_nonterminals}
        for production in self.production_list:
            mapping.setdefault(production.left, []).append(production.index)
        return mapping

    def is_nonterminal(self, symbol: str) -> bool:
        """判断一个符号是否是非终结符。"""
        return symbol in self.all_nonterminal_set

    def sort_symbol_key(self, symbol: str) -> tuple[int, int]:
        """给终结符和非终结符一个稳定的展示顺序。"""
        if symbol in self.terminals:
            return (0, self.terminals.index(symbol))
        if symbol in self.nonterminals:
            return (1, self.nonterminals.index(symbol))
        if symbol == self.augmented_start_symbol:
            return (2, 0)
        return (3, 0)

    def sort_items(self, items: frozenset[Item]) -> list[Item]:
        """让项目输出顺序稳定，方便和实验报告对照。"""
        return sorted(items, key=lambda item: (item.production_index, item.dot))

    def production_at(self, index: int) -> Production:
        """按编号取产生式。"""
        return self.production_list[index]

    def symbol_after_dot(self, item: Item) -> str | None:
        """查看项目中点号后面的符号。"""
        production = self.production_at(item.production_index)
        if item.dot >= len(production.right):
            return None
        return production.right[item.dot]

    def format_item(self, item: Item) -> str:
        """把 LR(0) 项目格式化成字符串。"""
        production = self.production_at(item.production_index)

        if not production.right:
            return f"{production.left} -> {ITEM_DOT}"

        parts: list[str] = []
        for index, symbol in enumerate(production.right):
            if index == item.dot:
                parts.append(ITEM_DOT)
            parts.append(symbol)
        if item.dot == len(production.right):
            parts.append(ITEM_DOT)

        return f"{production.left} -> {' '.join(parts)}"

    def first_of_sequence(
        self,
        symbols: tuple[str, ...],
        first_sets: dict[str, set[str]],
    ) -> set[str]:
        """计算一个符号串的 FIRST 集。"""
        if not symbols:
            return {EPSILON}

        result: set[str] = set()
        for symbol in symbols:
            if symbol not in self.nonterminal_set:
                result.add(symbol)
                return result

            result.update(first_sets[symbol] - {EPSILON})
            if EPSILON not in first_sets[symbol]:
                return result

        result.add(EPSILON)
        return result

    def compute_first_sets(self) -> dict[str, set[str]]:
        """使用不动点迭代法计算 FIRST 集。"""
        first_sets = {nonterminal: set() for nonterminal in self.nonterminals}

        changed = True
        while changed:
            changed = False

            for left, alternatives in self.productions.items():
                for right in alternatives:
                    normalized_right = self._normalize_right(right)
                    before_size = len(first_sets[left])
                    first_sets[left].update(
                        self.first_of_sequence(normalized_right, first_sets)
                    )
                    if len(first_sets[left]) != before_size:
                        changed = True

        return first_sets

    def compute_follow_sets(
        self,
        first_sets: dict[str, set[str]],
    ) -> dict[str, set[str]]:
        """使用不动点迭代法计算 FOLLOW 集。"""
        follow_sets = {nonterminal: set() for nonterminal in self.nonterminals}
        follow_sets[self.start_symbol].add(END_MARKER)

        changed = True
        while changed:
            changed = False

            for left, alternatives in self.productions.items():
                for right in alternatives:
                    normalized_right = self._normalize_right(right)
                    for index, symbol in enumerate(normalized_right):
                        if symbol not in self.nonterminal_set:
                            continue

                        beta = normalized_right[index + 1 :]
                        first_beta = self.first_of_sequence(beta, first_sets)

                        before_size = len(follow_sets[symbol])
                        follow_sets[symbol].update(first_beta - {EPSILON})

                        if EPSILON in first_beta:
                            follow_sets[symbol].update(follow_sets[left])

                        if len(follow_sets[symbol]) != before_size:
                            changed = True

        return follow_sets

    def closure(self, items: frozenset[Item]) -> frozenset[Item]:
        """计算一个项目集的闭包。"""
        closure_set = set(items)
        queue = deque(items)

        while queue:
            item = queue.popleft()
            symbol = self.symbol_after_dot(item)

            if symbol is None or symbol not in self.nonterminal_set:
                continue

            for production_index in self.production_indexes_by_left[symbol]:
                new_item = Item(production_index, 0)
                if new_item in closure_set:
                    continue
                closure_set.add(new_item)
                queue.append(new_item)

        return frozenset(closure_set)

    def goto(self, items: frozenset[Item], symbol: str) -> frozenset[Item]:
        """计算 GOTO(I, X)。"""
        moved_items = {
            Item(item.production_index, item.dot + 1)
            for item in items
            if self.symbol_after_dot(item) == symbol
        }

        if not moved_items:
            return frozenset()

        return self.closure(frozenset(moved_items))

    def build_canonical_collection(
        self,
    ) -> tuple[list[frozenset[Item]], dict[tuple[int, str], int]]:
        """构造 LR(0) 项目集规范族及状态转移。"""
        start_state = self.closure(frozenset({Item(0, 0)}))
        states = [start_state]
        state_ids = {start_state: 0}
        transitions: dict[tuple[int, str], int] = {}

        queue = deque([0])
        while queue:
            state_id = queue.popleft()
            state = states[state_id]

            next_symbols: list[str] = []
            for item in self.sort_items(state):
                symbol = self.symbol_after_dot(item)
                if symbol is not None and symbol not in next_symbols:
                    next_symbols.append(symbol)

            next_symbols.sort(key=self.sort_symbol_key)

            for symbol in next_symbols:
                next_state = self.goto(state, symbol)
                if not next_state:
                    continue

                if next_state not in state_ids:
                    state_ids[next_state] = len(states)
                    states.append(next_state)
                    queue.append(state_ids[next_state])

                transitions[(state_id, symbol)] = state_ids[next_state]

        return states, transitions

    def describe_action(self, action: Action) -> str:
        """把 ACTION 表项转成更完整的中文说明。"""
        if action.kind == "shift":
            return f"{action.short()}（移进并转到状态 {action.target}）"
        if action.kind == "reduce":
            production = self.production_at(action.target or 0)
            return f"{action.short()}（按 {production.display()} 归约）"
        return "acc（接受）"

    def _put_action_entry(
        self,
        action_table: dict[int, dict[str, Action | None]],
        state_id: int,
        terminal: str,
        action: Action,
        conflicts: list[str],
    ) -> None:
        """向 ACTION 表填入一个表项，并检测冲突。"""
        current = action_table[state_id][terminal]

        if current is None:
            action_table[state_id][terminal] = action
            return

        if current != action:
            message = (
                f"ACTION[{state_id}, {terminal}] 同时出现 "
                f"{self.describe_action(current)} 和 {self.describe_action(action)}"
            )
            if message not in conflicts:
                conflicts.append(message)

    def build_slr_table(
        self,
        follow_sets: dict[str, set[str]],
        states: list[frozenset[Item]],
        transitions: dict[tuple[int, str], int],
    ) -> tuple[
        dict[int, dict[str, Action | None]],
        dict[int, dict[str, int | None]],
        list[str],
    ]:
        """根据 LR(0) 项目集和 FOLLOW 集构造 SLR(1) 分析表。"""
        action_table = {
            state_id: {terminal: None for terminal in self.terminals + [END_MARKER]}
            for state_id in range(len(states))
        }
        goto_table = {
            state_id: {nonterminal: None for nonterminal in self.nonterminals}
            for state_id in range(len(states))
        }
        conflicts: list[str] = []

        for (state_id, symbol), target_state in transitions.items():
            if symbol in self.terminals:
                self._put_action_entry(
                    action_table,
                    state_id,
                    symbol,
                    Action("shift", target_state),
                    conflicts,
                )
                continue

            if symbol in self.nonterminal_set:
                goto_table[state_id][symbol] = target_state

        for state_id, state in enumerate(states):
            for item in self.sort_items(state):
                production = self.production_at(item.production_index)

                if item.dot != len(production.right):
                    continue

                if production.left == self.augmented_start_symbol:
                    self._put_action_entry(
                        action_table,
                        state_id,
                        END_MARKER,
                        Action("accept"),
                        conflicts,
                    )
                    continue

                for terminal in follow_sets[production.left]:
                    self._put_action_entry(
                        action_table,
                        state_id,
                        terminal,
                        Action("reduce", production.index),
                        conflicts,
                    )

        return action_table, goto_table, conflicts

    def analyze_sentence(
        self,
        sentence: str,
        action_table: dict[int, dict[str, Action | None]],
        goto_table: dict[int, dict[str, int | None]],
    ) -> ParseResult:
        """根据 SLR(1) 分析表模拟输入串的表驱动分析过程。"""
        normalized_sentence, tokens = normalize_sentence(sentence, self)
        allowed_symbols = set(self.terminals + [END_MARKER])

        for token in tokens:
            if token not in allowed_symbols:
                return ParseResult(
                    original_sentence=sentence,
                    normalized_sentence=normalized_sentence,
                    accepted=False,
                    message=f"输入串中出现了文法未定义的符号：{token}",
                    steps=[],
                )

        state_stack = [0]
        symbol_stack = [END_MARKER]
        pointer = 0
        step_no = 1
        steps: list[AnalysisStep] = []

        while True:
            current_state = state_stack[-1]
            current_input = tokens[pointer]
            action = action_table[current_state].get(current_input)

            state_snapshot = format_state_stack(state_stack)
            symbol_snapshot = format_symbol_stack(symbol_stack)
            remaining_input = format_token_sequence(tokens[pointer:])

            if action is None:
                steps.append(
                    AnalysisStep(
                        step_no,
                        state_snapshot,
                        symbol_snapshot,
                        remaining_input,
                        f"ACTION[{current_state}, {current_input}] 为空，分析失败",
                    )
                )
                return ParseResult(
                    original_sentence=sentence,
                    normalized_sentence=normalized_sentence,
                    accepted=False,
                    message="分析表中没有对应的动作，输入串不符合该文法。",
                    steps=steps,
                )

            if action.kind == "shift":
                steps.append(
                    AnalysisStep(
                        step_no,
                        state_snapshot,
                        symbol_snapshot,
                        remaining_input,
                        f"按 ACTION[{current_state}, {current_input}] = {action.short()} 移进符号 {current_input}",
                    )
                )
                symbol_stack.append(current_input)
                state_stack.append(action.target or 0)
                pointer += 1
                step_no += 1
                continue

            if action.kind == "reduce":
                production = self.production_at(action.target or 0)

                if production.right:
                    for _ in production.right:
                        symbol_stack.pop()
                        state_stack.pop()

                goto_source_state = state_stack[-1]
                goto_state = goto_table[goto_source_state].get(production.left)
                if goto_state is None:
                    steps.append(
                        AnalysisStep(
                            step_no,
                            state_snapshot,
                            symbol_snapshot,
                            remaining_input,
                            f"归约后 GOTO[{goto_source_state}, {production.left}] 为空，分析失败",
                        )
                    )
                    return ParseResult(
                        original_sentence=sentence,
                        normalized_sentence=normalized_sentence,
                        accepted=False,
                        message="归约后找不到合法的 GOTO 状态。",
                        steps=steps,
                    )

                steps.append(
                    AnalysisStep(
                        step_no,
                        state_snapshot,
                        symbol_snapshot,
                        remaining_input,
                        (
                            f"按 ACTION[{current_state}, {current_input}] = {action.short()}，"
                            f"用 {production.display()} 归约，再转到状态 {goto_state}"
                        ),
                    )
                )
                symbol_stack.append(production.left)
                state_stack.append(goto_state)
                step_no += 1
                continue

            steps.append(
                AnalysisStep(
                    step_no,
                    state_snapshot,
                    symbol_snapshot,
                    remaining_input,
                    f"按 ACTION[{current_state}, {current_input}] = acc，分析成功",
                )
            )
            return ParseResult(
                original_sentence=sentence,
                normalized_sentence=normalized_sentence,
                accepted=True,
                message="输入串符合该 SLR(1) 文法。",
                steps=steps,
            )


def build_default_grammar() -> SLRGrammar:
    """构造实验三默认使用的表达式文法。"""
    productions = {
        "E": [("E", "+", "T"), ("T",)],
        "T": [("T", "*", "F"), ("F",)],
        "F": [("(", "E", ")"), ("i",)],
    }

    # 这里使用更常见的列顺序，输出表格时更容易阅读。
    terminal_order = ["i", "+", "*", "(", ")"]
    return SLRGrammar(
        productions=productions,
        start_symbol="E",
        terminal_order=terminal_order,
    )


DEFAULT_CASES = [
    ("单个标识符", "i"),
    ("简单加法", "i+i"),
    ("乘法优先级", "i+i*i"),
    ("括号表达式", "(i+i)*i"),
    ("错误示例 1", "i+"),
    ("错误示例 2", "(i*i"),
]


def split_sentence(sentence: str, grammar: SLRGrammar) -> list[str]:
    """把输入串拆成符号序列。"""
    stripped = sentence.strip()

    if not stripped:
        return []

    cleaned = "".join(sentence.split())

    # 默认文法中的终结符都是单字符，因此无论用户有没有写空格，
    # 都可以先去掉空白，再逐字符切分。
    if all(len(symbol) == 1 for symbol in grammar.terminals + [END_MARKER]):
        return list(cleaned)

    # 如果你以后把文法改成多字符终结符（例如 id、num），
    # 那么建议输入时使用空格分隔。
    if any(char.isspace() for char in stripped):
        return stripped.split()

    return [cleaned]


def format_token_sequence(tokens: list[str]) -> str:
    """把符号序列还原成适合终端显示的文本。"""
    if all(len(token) == 1 for token in tokens):
        return "".join(tokens)
    return " ".join(tokens)


def normalize_sentence(sentence: str, grammar: SLRGrammar) -> tuple[str, list[str]]:
    """规范化输入串，并自动在末尾补上结束符 #。"""
    tokens = split_sentence(sentence, grammar)
    if not tokens or tokens[-1] != END_MARKER:
        tokens.append(END_MARKER)
    return format_token_sequence(tokens), tokens


def format_state_stack(stack: list[int]) -> str:
    """把状态栈格式化成字符串。"""
    return " ".join(str(state) for state in stack)


def format_symbol_stack(stack: list[str]) -> str:
    """把符号栈格式化成字符串。"""
    return " ".join(stack)


def sort_symbols(symbols: set[str], grammar: SLRGrammar) -> list[str]:
    """按更适合展示的顺序排列 FIRST / FOLLOW 集中的符号。"""
    display_order = grammar.terminals + [END_MARKER, EPSILON]
    return [symbol for symbol in display_order if symbol in symbols]


def format_symbol_set(symbols: set[str], grammar: SLRGrammar) -> str:
    """把 FIRST / FOLLOW 集格式化成字符串。"""
    ordered = sort_symbols(symbols, grammar)
    return "{ " + ", ".join(ordered) + " }"


def build_text_table(headers: list[str], rows: list[list[str]]) -> str:
    """构造一个适合终端查看的纯文本表格。"""
    all_rows = [headers] + rows

    def display_width(text: str) -> int:
        width = 0
        for char in text:
            width += 2 if unicodedata.east_asian_width(char) in {"F", "W"} else 1
        return width

    widths = [
        max(display_width(str(row[index])) for row in all_rows)
        for index in range(len(headers))
    ]

    def make_line(row: list[str]) -> str:
        cells: list[str] = []
        for index, cell in enumerate(row):
            text = str(cell)
            padding = widths[index] - display_width(text)
            cells.append(text + " " * padding)
        return " | ".join(cells)

    separator = "-+-".join("-" * width for width in widths)
    lines = [make_line(headers), separator]
    lines.extend(make_line(row) for row in rows)
    return "\n".join(lines)


def build_grammar_section(grammar: SLRGrammar) -> str:
    """输出原文法。"""
    lines = ["文法："]
    for left, alternatives in grammar.productions.items():
        right_text = " | ".join(
            " ".join(grammar._normalize_right(right)) or EPSILON
            for right in alternatives
        )
        lines.append(f"{left} -> {right_text}")
    return "\n".join(lines)


def build_production_section(grammar: SLRGrammar) -> str:
    """输出产生式编号表。"""
    rows = [
        [str(production.index), production.display()]
        for production in grammar.production_list
    ]
    return "\n".join(
        [
            "产生式编号（含扩广文法）：",
            build_text_table(["编号", "产生式"], rows),
        ]
    )


def build_first_follow_section(
    grammar: SLRGrammar,
    first_sets: dict[str, set[str]],
    follow_sets: dict[str, set[str]],
) -> str:
    """输出 FIRST 集和 FOLLOW 集。"""
    first_rows = [
        [nonterminal, format_symbol_set(first_sets[nonterminal], grammar)]
        for nonterminal in grammar.nonterminals
    ]
    follow_rows = [
        [nonterminal, format_symbol_set(follow_sets[nonterminal], grammar)]
        for nonterminal in grammar.nonterminals
    ]

    return "\n".join(
        [
            "FIRST 集：",
            build_text_table(["非终结符", "FIRST"], first_rows),
            "",
            "FOLLOW 集：",
            build_text_table(["非终结符", "FOLLOW"], follow_rows),
        ]
    )


def build_item_sets_section(
    grammar: SLRGrammar,
    states: list[frozenset[Item]],
    transitions: dict[tuple[int, str], int],
) -> str:
    """输出 LR(0) 项目集规范族。"""
    lines = ["LR(0) 项目集规范族："]

    for state_id, state in enumerate(states):
        lines.append(f"I{state_id}:")
        for item in grammar.sort_items(state):
            lines.append(f"  {grammar.format_item(item)}")

        outgoing = [
            (symbol, target_state)
            for (source_state, symbol), target_state in transitions.items()
            if source_state == state_id
        ]
        outgoing.sort(key=lambda pair: grammar.sort_symbol_key(pair[0]))

        if outgoing:
            transfer_text = ", ".join(
                f"{symbol} -> I{target_state}" for symbol, target_state in outgoing
            )
            lines.append(f"  转移：{transfer_text}")
        else:
            lines.append("  转移：无")

        lines.append("")

    return "\n".join(lines).rstrip()


def build_slr_section(conflicts: list[str]) -> str:
    """输出 SLR(1) 判定结果。"""
    if not conflicts:
        return "SLR(1) 判定：是\n原因：分析表中没有出现移进/归约或归约/归约冲突。"

    lines = ["SLR(1) 判定：否", "原因：分析表中出现了冲突。"]
    for conflict in conflicts:
        lines.append(f"- {conflict}")
    return "\n".join(lines)


def build_parsing_table_section(
    grammar: SLRGrammar,
    action_table: dict[int, dict[str, Action | None]],
    goto_table: dict[int, dict[str, int | None]],
) -> str:
    """输出 SLR(1) 分析表。"""
    headers = ["状态"] + grammar.terminals + [END_MARKER] + grammar.nonterminals
    rows: list[list[str]] = []

    for state_id in range(len(action_table)):
        row = [str(state_id)]

        for terminal in grammar.terminals + [END_MARKER]:
            action = action_table[state_id][terminal]
            row.append(action.short() if action is not None else "")

        for nonterminal in grammar.nonterminals:
            target_state = goto_table[state_id][nonterminal]
            row.append("" if target_state is None else str(target_state))

        rows.append(row)

    return "\n".join(
        [
            "SLR(1) 分析表（前半部分为 ACTION，后半部分为 GOTO）：",
            build_text_table(headers, rows),
        ]
    )


def build_analysis_section(result: ParseResult) -> str:
    """输出一个输入串的分析过程。"""
    lines = [
        f"输入串：{result.original_sentence!r}",
        f"规范化后：{result.normalized_sentence}",
        f"最终结果：{'接受' if result.accepted else '拒绝'}",
        f"说明：{result.message}",
    ]

    if not result.steps:
        return "\n".join(lines)

    rows = [
        [
            str(step.step_no),
            step.state_stack,
            step.symbol_stack,
            step.remaining_input,
            step.action,
        ]
        for step in result.steps
    ]
    lines.extend(
        [
            "",
            build_text_table(["步骤", "状态栈", "符号栈", "剩余输入", "动作"], rows),
        ]
    )
    return "\n".join(lines)


def build_full_report(
    grammar: SLRGrammar,
    custom_sentence: str | None = None,
    example_cases: list[tuple[str, str]] | None = None,
) -> str:
    """组合完整输出，方便 main.py 直接打印。"""
    first_sets = grammar.compute_first_sets()
    follow_sets = grammar.compute_follow_sets(first_sets)
    states, transitions = grammar.build_canonical_collection()
    action_table, goto_table, conflicts = grammar.build_slr_table(
        follow_sets,
        states,
        transitions,
    )

    sections = [
        build_grammar_section(grammar),
        build_production_section(grammar),
        build_first_follow_section(grammar, first_sets, follow_sets),
        build_item_sets_section(grammar, states, transitions),
        build_slr_section(conflicts),
        build_parsing_table_section(grammar, action_table, goto_table),
        "说明：默认文法中的 i 表示一个标识符，例如变量名或常量。",
    ]

    if custom_sentence is not None:
        if conflicts:
            sections.extend(
                [
                    "输入串分析：",
                    "当前文法不是 SLR(1) 文法，标准 SLR(1) 表驱动分析过程已跳过。",
                ]
            )
            return "\n\n".join(sections)

        result = grammar.analyze_sentence(custom_sentence, action_table, goto_table)
        sections.extend(["输入串分析：", build_analysis_section(result)])
        return "\n\n".join(sections)

    if example_cases:
        sections.append("内置测试示例：")

        if conflicts:
            sections.append("当前文法不是 SLR(1) 文法，因此不再演示表驱动分析过程。")
            return "\n\n".join(sections)

        for title, sentence in example_cases:
            result = grammar.analyze_sentence(sentence, action_table, goto_table)
            sections.append(f"[{title}]\n{build_analysis_section(result)}")

    return "\n\n".join(sections)
