From f9a5bcf4b293acb19b810a31f8a8beb12be4508f Mon Sep 17 00:00:00 2001 From: yenru0 Date: Thu, 2 Oct 2025 10:07:21 +0900 Subject: [PATCH] complement notes in 10.02 --- notes/4.md | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 68 insertions(+), 3 deletions(-) diff --git a/notes/4.md b/notes/4.md index 016b237..7dfd737 100644 --- a/notes/4.md +++ b/notes/4.md @@ -83,12 +83,12 @@ L -> S | L,S It can be represented as a NFA: -```python {cmd matplotlib} +```python {cmd matplotlib hide} import sys import pymupdf from PIL import Image doc = pymupdf.open("../pdf/L4.pdf") -pix = doc[22].get_pixmap(dpi=500) +pix = doc[22].get_pixmap(dpi=360) img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) plt.imshow(img) @@ -97,8 +97,73 @@ plt.tight_layout() plt.show() ``` +* SLR(1) Parsing + +* LR(1) Grammar +```python {cmd matplotlib hide} +import sys +import pymupdf +from PIL import Image +doc = pymupdf.open("../pdf/L4.pdf") +pix = doc[47].get_pixmap(dpi=360) +img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) + +plt.imshow(img) +plt.axis('off') +plt.tight_layout() +plt.show() +``` + +LR(1) Parsing Table + +is same as LR(0) parsing table construction except for reductions: -* LR(1) Grammar \ No newline at end of file +* LALR(1) Grammar + +LALR(1) generally has the same number of states as SLR (much less than LR(1)) +for Pascal language, SLR requires several hundred states, LR(1) requires several thousand states. + +#### Ambiguous Grammar + +Ambiguity is mainly from + +* Precedence + * The production at higher levels will have operators with lower priorities (and vice versa). + * we can insert non-terminals to enforce precendence. +* Associativity + * we should determine where to place recursion depending on the associativity + + +for example: `if-then-else` + + +**Automatic Disambiguation** + +We can define precedence to use ambiguous grammars w/o shift-reduce conflicts. + + +## AST + +### AST Construction LL + +```c +expr parse_S() { + switch(token) { + case num: + case '(': + expr child1 = parse_E(); + expr child2 = parse_Sp(); + return new S(child1, child2); + default: + parseError(); + + } +} + +``` + +### AST Construction LR +