Skip to content

Commit

Permalink
Added FunctionParser
Browse files Browse the repository at this point in the history
  • Loading branch information
RealA10N committed Aug 3, 2024
1 parent 73c84e8 commit 9bce66d
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 1 deletion.
14 changes: 13 additions & 1 deletion parse/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,25 @@ type BlockParser struct {
InstructionParser InstructionParser
}

func (p BlockParser) parseInstructions(v *TokenView, node *BlockNode) {
for {
v.ConsumeManyTokens(lex.SepToken)
inst, err := p.InstructionParser.Parse(v)
if err != nil {
break
}
node.Instructions = append(node.Instructions, inst)
}
v.ConsumeManyTokens(lex.SepToken)
}

func (p BlockParser) Parse(v *TokenView) (node BlockNode, err ParsingError) {
start, err := v.ConsumeToken(lex.LcrToken)
if err != nil {
return
}

node.Instructions = ParseMany(p.InstructionParser, v)
p.parseInstructions(v, &node)

end, err := v.ConsumeToken(lex.RcrToken)
if err != nil {
Expand Down
15 changes: 15 additions & 0 deletions parse/function.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,18 @@ func (n FunctionNode) View() source.UnmanagedSourceView {
func (n FunctionNode) String(ctx source.SourceContext) string {
return n.Signature.String(ctx) + " " + n.Block.String(ctx)
}

type FunctionParser struct {
SignatureParser SignatureParser
BlockParser BlockParser
}

func (p FunctionParser) Parse(v *TokenView) (node FunctionNode, err ParsingError) {
node.Signature, err = p.SignatureParser.Parse(v)
if err != nil {
return
}

node.Block, err = p.BlockParser.Parse(v)
return
}
10 changes: 10 additions & 0 deletions parse/token_view.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,13 @@ func (v *TokenView) ConsumeToken(expectedTypes ...lex.TokenType) (tkn lex.Token,
*v = TokenView{restView}
return tkn, nil
}

func (v *TokenView) ConsumeManyTokens(expectedTypes ...lex.TokenType) (tkns []lex.Token) {
for {
tkn, err := v.ConsumeToken(expectedTypes...)
if err != nil {
return
}
tkns = append(tkns, tkn)
}
}
13 changes: 13 additions & 0 deletions usm.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"os"
"usm/lex"
"usm/parse"
"usm/source"
)

Expand All @@ -25,11 +26,23 @@ func main() {
panic(err)
}

fmt.Println("=== Tokens ===")

_, ctx := view.Detach()
for _, tkn := range tokens {
fmt.Printf("%s ", tkn.String(ctx))
if tkn.Type == lex.SepToken {
fmt.Println()
}
}

fmt.Println("\n=== Formatted Source ===")

tknView := parse.NewTokenView(tokens)
fn, perr := parse.FunctionParser{}.Parse(&tknView)
if perr == nil {
fmt.Println(fn.String(ctx))
} else {
fmt.Println(perr.Error(ctx))
}
}

0 comments on commit 9bce66d

Please sign in to comment.