shaderir: Add parsing expr and stmt

This commit is contained in:
Hajime Hoshi 2020-05-14 01:45:33 +09:00
parent c75a35fd64
commit d932787e36
3 changed files with 98 additions and 3 deletions

View File

@ -119,5 +119,53 @@ func (p *Program) glslBlock(b *Block, f *Func, level int) []string {
lines = append(lines, fmt.Sprintf("%s%s;", idt, p.glslVarDecl(&t, fmt.Sprintf("l%d", idx))))
idx++
}
var glslExpr func(e *Expr) string
glslExpr = func(e *Expr) string {
switch e.Type {
case Literal:
return e.Value
case Ident:
return e.Value
case Unary:
return fmt.Sprintf("%s(%s)", e.Op, glslExpr(&e.Exprs[0]))
case Binary:
return fmt.Sprintf("(%s) %s (%s)", glslExpr(&e.Exprs[0]), e.Op, glslExpr(&e.Exprs[1]))
case Call:
return fmt.Sprintf("(%s).(%s)", glslExpr(&e.Exprs[0]), glslExpr(&e.Exprs[1]))
case Selector:
return fmt.Sprintf("(%s).%s", glslExpr(&e.Exprs[0]), glslExpr(&e.Exprs[1]))
case Index:
return fmt.Sprintf("(%s)[%s]", glslExpr(&e.Exprs[0]), glslExpr(&e.Exprs[1]))
default:
return fmt.Sprintf("?(unexpected expr: %d)", e.Type)
}
}
for _, s := range b.Stmts {
switch s.Type {
case ExprStmt:
panic("not implemented")
case BlockStmt:
lines = append(lines, idt+"{")
lines = append(lines, p.glslBlock(s.Block, f, level+1)...)
lines = append(lines, idt+"}")
case Assign:
lines = append(lines, fmt.Sprintf("%s%s = %s;", idt, glslExpr(&s.Exprs[0]), glslExpr(&s.Exprs[1])))
case If:
panic("not implemented")
case For:
panic("not implemented")
case Continue:
lines = append(lines, idt+"continue;")
case Break:
lines = append(lines, idt+"break;")
case Discard:
lines = append(lines, idt+"discard;")
default:
lines = append(lines, fmt.Sprintf("%s?(unexpected stmt: %d)", idt, s.Type))
}
}
return lines
}

View File

@ -151,6 +151,53 @@ varying vec3 V0;`,
Glsl: `void F0(in float l0, inout float l1, out float l2) {
mat4 l3;
mat4 l4;
}`,
},
{
Name: "FuncAdd",
Program: Program{
Funcs: []Func{
{
Name: "F0",
InParams: []Type{
{Main: Float},
{Main: Float},
},
OutParams: []Type{
{Main: Float},
},
Block: Block{
Stmts: []Stmt{
{
Type: Assign,
Exprs: []Expr{
{
Type: Ident,
Value: "l2",
},
{
Type: Binary,
Op: Add,
Exprs: []Expr{
{
Type: Ident,
Value: "l0",
},
{
Type: Ident,
Value: "l1",
},
},
},
},
},
},
},
},
},
},
Glsl: `void F0(in float l0, in float l1, out float l2) {
l2 = (l0) + (l1);
}`,
},
}

View File

@ -48,21 +48,22 @@ type Stmt struct {
Type StmtType
Exprs []Expr
Condition Expr
ElseStmts []Expr
ElseExprs []Expr
ForInit Expr
ForRest Expr
Block *Block
}
type StmtType int
const (
ExprStmt StmtType = iota
BlockStmt
Assign
If
For
Continue
Break
Return
Discard
)
@ -78,7 +79,6 @@ type ExprType int
const (
Literal ExprType = iota
Ident
LocalVarID
Unary
Binary
Call