86 lines
1.7 KiB
Go
86 lines
1.7 KiB
Go
|
package parser
|
||
|
|
||
|
import (
|
||
|
"bytes"
|
||
|
|
||
|
"go.arsenm.dev/amu/ast"
|
||
|
"go.arsenm.dev/amu/scanner"
|
||
|
)
|
||
|
|
||
|
func (p *Parser) parseCode(tok scanner.Token, lit string) *ast.Code {
|
||
|
// Create new code
|
||
|
code := &ast.Code{}
|
||
|
|
||
|
// If token is not WORD or literal is not "=list"
|
||
|
if tok != scanner.WORD || lit != "=code" {
|
||
|
// Return nil as this code is invalid
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
// Scan token
|
||
|
tok, lit = p.scan()
|
||
|
|
||
|
// If token is not PUNCT or literal is not "["
|
||
|
if tok != scanner.PUNCT || lit != "[" {
|
||
|
// Unscan token
|
||
|
p.unscan()
|
||
|
// Return nil as this code is invalid
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
// Parse argument list
|
||
|
args := p.parseArgs()
|
||
|
|
||
|
// If 1 or more arguments provided
|
||
|
if len(args) >= 1 {
|
||
|
// Set language to first argument
|
||
|
code.Language = args[0]
|
||
|
}
|
||
|
// If 2 or more arguments provided
|
||
|
if len(args) >= 2 {
|
||
|
// Set style to second argument
|
||
|
code.Style = args[1]
|
||
|
}
|
||
|
|
||
|
// Create buffer for text
|
||
|
textBuf := &bytes.Buffer{}
|
||
|
|
||
|
for {
|
||
|
// Scan token
|
||
|
tok, lit = p.scan()
|
||
|
|
||
|
// If end of file
|
||
|
if tok == scanner.EOF {
|
||
|
// Return whatever waS parsed so far
|
||
|
return code
|
||
|
}
|
||
|
|
||
|
// If token is WORD and lit is "=end"
|
||
|
if tok == scanner.WORD && lit == "=end" {
|
||
|
// Scan token
|
||
|
tok, lit = p.scan()
|
||
|
// If token is not PUNCT and literal is not "["
|
||
|
if tok != scanner.PUNCT && lit != "[" {
|
||
|
// Return nil as this is not a valid code
|
||
|
return nil
|
||
|
}
|
||
|
// Scan token
|
||
|
tok, lit = p.scan()
|
||
|
// If token is not PUNCT and literal is not "]"
|
||
|
if tok != scanner.PUNCT && lit != "]" {
|
||
|
// Return nil as this is not a valid code
|
||
|
return nil
|
||
|
}
|
||
|
break
|
||
|
}
|
||
|
|
||
|
// Write literal to text buffer
|
||
|
textBuf.WriteString(lit)
|
||
|
}
|
||
|
|
||
|
// Set code text to contents of text buffer
|
||
|
code.Text = textBuf.String()
|
||
|
|
||
|
return code
|
||
|
}
|