2017-11-11 04:06:16 +00:00
package tmpl
2017-05-07 08:31:41 +00:00
2017-06-05 11:57:27 +00:00
import (
"bytes"
2019-03-21 22:59:41 +00:00
"fmt"
2017-06-05 11:57:27 +00:00
"io/ioutil"
2018-03-08 03:59:47 +00:00
"log"
2019-02-28 07:28:17 +00:00
"os"
2017-09-03 04:50:31 +00:00
"path/filepath"
"reflect"
2019-03-21 22:59:41 +00:00
"runtime/debug"
2018-03-08 03:59:47 +00:00
"strconv"
"strings"
2017-06-05 11:57:27 +00:00
"text/template/parse"
2019-02-28 07:28:17 +00:00
"time"
2019-10-06 05:32:08 +00:00
"unicode"
2017-06-05 11:57:27 +00:00
)
2016-12-16 10:37:42 +00:00
2017-09-10 16:57:22 +00:00
// TODO: Turn this file into a library
2017-09-03 04:50:31 +00:00
var textOverlapList = make ( map [ string ] int )
2018-11-17 02:36:02 +00:00
2018-11-01 06:43:56 +00:00
// TODO: Stop hard-coding this here
var langPkg = "github.com/Azareal/Gosora/common/phrases"
2017-01-01 15:45:43 +00:00
2017-09-03 04:50:31 +00:00
type VarItem struct {
Name string
2016-12-16 10:37:42 +00:00
Destination string
2017-09-03 04:50:31 +00:00
Type string
2016-12-16 10:37:42 +00:00
}
2018-03-08 03:59:47 +00:00
2017-09-03 04:50:31 +00:00
type VarItemReflect struct {
Name string
2016-12-16 10:37:42 +00:00
Destination string
2017-09-03 04:50:31 +00:00
Value reflect . Value
2016-12-16 10:37:42 +00:00
}
2018-03-08 03:59:47 +00:00
type CTemplateConfig struct {
2018-06-24 13:49:29 +00:00
Minify bool
Debug bool
SuperDebug bool
SkipHandles bool
SkipTmplPtrMap bool
SkipInitBlock bool
PackageName string
2018-03-08 03:59:47 +00:00
}
// nolint
2017-09-03 04:50:31 +00:00
type CTemplateSet struct {
2019-02-28 07:28:17 +00:00
templateList map [ string ] * parse . Tree
fileDir string
funcMap map [ string ] interface { }
importMap map [ string ] string
//templateFragmentCount map[string]int
fragOnce map [ string ] bool
fragmentCursor map [ string ] int
FragOut [ ] OutFrag
fragBuf [ ] Fragment
varList map [ string ] VarItem
localVars map [ string ] map [ string ] VarItemReflect
hasDispInt bool
localDispStructIndex int
langIndexToName [ ] string
guestOnly bool
memberOnly bool
stats map [ string ] int
2016-12-16 10:37:42 +00:00
//tempVars map[string]string
2018-04-22 12:33:56 +00:00
config CTemplateConfig
baseImportMap map [ string ] string
2018-06-24 13:49:29 +00:00
buildTags string
2019-02-10 05:52:26 +00:00
overridenTrack map [ string ] map [ string ] bool
overridenRoots map [ string ] map [ string ] bool
themeName string
perThemeTmpls map [ string ] bool
2019-02-28 07:28:17 +00:00
2019-03-21 22:59:41 +00:00
logger * log . Logger
loggerf * os . File
2019-05-13 09:17:44 +00:00
lang string
2018-04-22 12:33:56 +00:00
}
2019-02-28 07:28:17 +00:00
func NewCTemplateSet ( in string ) * CTemplateSet {
f , err := os . OpenFile ( "./logs/tmpls-" + in + "-" + strconv . FormatInt ( time . Now ( ) . Unix ( ) , 10 ) + ".log" , os . O_WRONLY | os . O_APPEND | os . O_CREATE , 0755 )
if err != nil {
panic ( err )
}
2018-04-22 12:33:56 +00:00
return & CTemplateSet {
config : CTemplateConfig {
PackageName : "main" ,
} ,
2019-02-10 05:52:26 +00:00
baseImportMap : map [ string ] string { } ,
overridenRoots : map [ string ] map [ string ] bool { } ,
2018-04-22 12:33:56 +00:00
funcMap : map [ string ] interface { } {
2019-02-28 09:31:13 +00:00
"and" : "&&" ,
"not" : "!" ,
"or" : "||" ,
"eq" : "==" ,
"ge" : ">=" ,
"gt" : ">" ,
"le" : "<=" ,
"lt" : "<" ,
"ne" : "!=" ,
"add" : "+" ,
"subtract" : "-" ,
"multiply" : "*" ,
"divide" : "/" ,
"dock" : true ,
"hasWidgets" : true ,
"elapsed" : true ,
"lang" : true ,
2019-10-06 05:32:08 +00:00
"langf" : true ,
"level" : true ,
"bunit" : true ,
"abstime" : true ,
"reltime" : true ,
"scope" : true ,
"dyntmpl" : true ,
"index" : true ,
"flush" : true ,
2018-04-22 12:33:56 +00:00
} ,
2019-03-21 22:59:41 +00:00
logger : log . New ( f , "" , log . LstdFlags ) ,
loggerf : f ,
2019-05-13 09:17:44 +00:00
lang : in ,
2018-04-22 12:33:56 +00:00
}
2017-11-11 04:06:16 +00:00
}
2018-03-08 03:59:47 +00:00
func ( c * CTemplateSet ) SetConfig ( config CTemplateConfig ) {
2018-04-22 12:33:56 +00:00
if config . PackageName == "" {
config . PackageName = "main"
}
2018-03-08 03:59:47 +00:00
c . config = config
2017-11-11 04:06:16 +00:00
}
2018-03-08 03:59:47 +00:00
func ( c * CTemplateSet ) GetConfig ( ) CTemplateConfig {
return c . config
2017-11-11 06:33:08 +00:00
}
2018-04-22 12:33:56 +00:00
func ( c * CTemplateSet ) SetBaseImportMap ( importMap map [ string ] string ) {
c . baseImportMap = importMap
}
2018-06-24 13:49:29 +00:00
func ( c * CTemplateSet ) SetBuildTags ( tags string ) {
c . buildTags = tags
}
2019-02-10 05:52:26 +00:00
func ( c * CTemplateSet ) SetOverrideTrack ( overriden map [ string ] map [ string ] bool ) {
c . overridenTrack = overriden
}
func ( c * CTemplateSet ) GetOverridenRoots ( ) map [ string ] map [ string ] bool {
return c . overridenRoots
}
func ( c * CTemplateSet ) SetThemeName ( name string ) {
c . themeName = name
}
func ( c * CTemplateSet ) SetPerThemeTmpls ( perThemeTmpls map [ string ] bool ) {
c . perThemeTmpls = perThemeTmpls
}
2019-02-28 07:28:17 +00:00
func ( c * CTemplateSet ) ResetLogs ( in string ) {
f , err := os . OpenFile ( "./logs/tmpls-" + in + "-" + strconv . FormatInt ( time . Now ( ) . Unix ( ) , 10 ) + ".log" , os . O_WRONLY | os . O_APPEND | os . O_CREATE , 0755 )
if err != nil {
panic ( err )
}
c . logger = log . New ( f , "" , log . LstdFlags )
2019-03-21 22:59:41 +00:00
c . loggerf = f
2019-02-28 07:28:17 +00:00
}
2018-11-19 23:06:15 +00:00
type SkipBlock struct {
Frags map [ int ] int
LastCount int
ClosestFragSkip int
}
type Skipper struct {
Count int
Index int
}
2018-12-14 04:08:53 +00:00
type OutFrag struct {
TmplName string
Index int
Body string
}
2018-11-26 05:08:10 +00:00
func ( c * CTemplateSet ) CompileByLoggedin ( name string , fileDir string , expects string , expectsInt interface { } , varList map [ string ] VarItem , imports ... string ) ( stub string , gout string , mout string , err error ) {
c . importMap = map [ string ] string { }
for index , item := range c . baseImportMap {
c . importMap [ index ] = item
}
2019-02-10 05:52:26 +00:00
for _ , importItem := range imports {
c . importMap [ importItem ] = importItem
2018-11-26 05:08:10 +00:00
}
var importList string
for _ , item := range c . importMap {
2019-10-06 05:32:08 +00:00
ispl := strings . Split ( item , " " )
2019-08-20 22:32:10 +00:00
if len ( ispl ) > 1 {
2019-10-06 05:32:08 +00:00
importList += "import " + ispl [ 0 ] + " \"" + ispl [ 1 ] + "\"\n"
2019-08-20 22:32:10 +00:00
} else {
importList += "import \"" + item + "\"\n"
}
2018-11-26 05:08:10 +00:00
}
fname := strings . TrimSuffix ( name , filepath . Ext ( name ) )
2019-02-10 05:52:26 +00:00
if c . themeName != "" {
_ , ok := c . perThemeTmpls [ fname ]
if ! ok {
return "" , "" , "" , nil
}
fname += "_" + c . themeName
}
2019-08-20 22:32:10 +00:00
c . importMap [ "github.com/Azareal/Gosora/common" ] = "c github.com/Azareal/Gosora/common"
2018-11-26 05:08:10 +00:00
stub = ` package ` + c . config . PackageName + `
` + importList + `
2019-02-10 05:52:26 +00:00
import "errors"
2018-11-26 05:08:10 +00:00
`
if ! c . config . SkipInitBlock {
stub += "// nolint\nfunc init() {\n"
2019-02-28 07:28:17 +00:00
if ! c . config . SkipHandles && c . themeName == "" {
2019-08-20 22:32:10 +00:00
stub += "\tc.Template_" + fname + "_handle = Template_" + fname + "\n"
stub += "\tc.Ctemplates = append(c.Ctemplates,\"" + fname + "\")\n"
2018-11-26 05:08:10 +00:00
}
if ! c . config . SkipTmplPtrMap {
2019-02-28 07:28:17 +00:00
stub += "tmpl := Template_" + fname + "\n"
2019-08-20 22:32:10 +00:00
stub += "\tc.TmplPtrMap[\"" + fname + "\"] = &tmpl\n"
stub += "\tc.TmplPtrMap[\"o_" + fname + "\"] = tmpl\n"
2018-11-26 05:08:10 +00:00
}
stub += "}\n\n"
}
2019-02-10 05:52:26 +00:00
// TODO: Try to remove this redundant interface cast
2018-11-26 05:08:10 +00:00
stub += `
// nolint
2019-02-10 05:52:26 +00:00
func Template_ ` + fname + ` ( tmpl_ ` + fname + ` _i interface { } , w io . Writer ) error {
tmpl_ ` + fname + ` _vars , ok := tmpl_ ` + fname + ` _i . ( ` + expects + ` )
if ! ok {
return errors . New ( "invalid page struct value" )
}
2018-11-26 05:08:10 +00:00
if tmpl_ ` + fname + ` _vars . CurrentUser . Loggedin {
2019-02-10 05:52:26 +00:00
return Template_ ` + fname + ` _member ( tmpl_ ` + fname + ` _i , w )
2018-11-26 05:08:10 +00:00
}
2019-02-10 05:52:26 +00:00
return Template_ ` + fname + ` _guest ( tmpl_ ` + fname + ` _i , w )
2018-11-26 05:08:10 +00:00
} `
c . fileDir = fileDir
content , err := c . loadTemplate ( c . fileDir , name )
if err != nil {
2019-02-28 07:28:17 +00:00
c . detail ( "bailing out: " , err )
2018-11-26 05:08:10 +00:00
return "" , "" , "" , err
}
c . guestOnly = true
gout , err = c . compile ( name , content , expects , expectsInt , varList , imports ... )
if err != nil {
return "" , "" , "" , err
}
c . guestOnly = false
c . memberOnly = true
mout , err = c . compile ( name , content , expects , expectsInt , varList , imports ... )
c . memberOnly = false
return stub , gout , mout , err
}
2018-03-08 03:59:47 +00:00
func ( c * CTemplateSet ) Compile ( name string , fileDir string , expects string , expectsInt interface { } , varList map [ string ] VarItem , imports ... string ) ( out string , err error ) {
if c . config . Debug {
2019-02-28 07:28:17 +00:00
c . logger . Println ( "Compiling template '" + name + "'" )
2017-08-06 15:22:18 +00:00
}
2018-11-26 05:08:10 +00:00
c . fileDir = fileDir
content , err := c . loadTemplate ( c . fileDir , name )
if err != nil {
2019-02-28 07:28:17 +00:00
c . detail ( "bailing out: " , err )
2018-11-26 05:08:10 +00:00
return "" , err
}
return c . compile ( name , content , expects , expectsInt , varList , imports ... )
}
2019-02-10 05:52:26 +00:00
func ( c * CTemplateSet ) compile ( name string , content string , expects string , expectsInt interface { } , varList map [ string ] VarItem , imports ... string ) ( out string , err error ) {
2019-03-21 22:59:41 +00:00
defer func ( ) {
2019-10-06 05:32:08 +00:00
if r := recover ( ) ; r != nil {
2019-03-21 22:59:41 +00:00
fmt . Println ( r )
debug . PrintStack ( )
2019-10-12 22:49:08 +00:00
if err := c . loggerf . Sync ( ) ; err != nil {
2019-03-21 22:59:41 +00:00
fmt . Println ( err )
}
log . Fatal ( "" )
return
}
} ( )
2019-02-28 07:28:17 +00:00
//c.dumpCall("compile", name, content, expects, expectsInt, varList, imports)
//c.detailf("c: %+v\n", c)
2018-04-22 12:33:56 +00:00
c . importMap = map [ string ] string { }
for index , item := range c . baseImportMap {
c . importMap [ index ] = item
2017-04-12 10:10:36 +00:00
}
2019-02-10 05:52:26 +00:00
c . importMap [ "errors" ] = "errors"
for _ , importItem := range imports {
c . importMap [ importItem ] = importItem
2017-11-11 06:33:08 +00:00
}
2016-12-16 10:37:42 +00:00
c . varList = varList
2017-11-23 05:37:08 +00:00
c . hasDispInt = false
c . localDispStructIndex = 0
2016-12-17 03:39:53 +00:00
c . stats = make ( map [ string ] int )
2017-06-16 10:41:30 +00:00
2019-10-12 22:49:08 +00:00
//tree := parse.New(name, c.funcMap)
//treeSet := make(map[string]*parse.Tree)
treeSet , err := parse . Parse ( name , content , "{{" , "}}" , c . funcMap )
2016-12-16 10:37:42 +00:00
if err != nil {
2017-08-13 11:22:34 +00:00
return "" , err
2016-12-16 10:37:42 +00:00
}
2018-03-21 05:56:33 +00:00
c . detail ( name )
2019-10-12 22:49:08 +00:00
c . detailf ( "treeSet: %+v\n" , treeSet )
2017-06-16 10:41:30 +00:00
2016-12-16 10:37:42 +00:00
fname := strings . TrimSuffix ( name , filepath . Ext ( name ) )
2019-02-10 05:52:26 +00:00
if c . themeName != "" {
_ , ok := c . perThemeTmpls [ fname ]
if ! ok {
2019-02-28 07:28:17 +00:00
c . detail ( "fname not in c.perThemeTmpls" )
c . detail ( "c.perThemeTmpls" , c . perThemeTmpls )
2019-02-10 05:52:26 +00:00
return "" , nil
}
fname += "_" + c . themeName
}
2018-11-26 05:08:10 +00:00
if c . guestOnly {
fname += "_guest"
} else if c . memberOnly {
fname += "_member"
}
2019-02-28 07:28:17 +00:00
c . detail ( "root overridenTrack loop" )
c . detail ( "fname:" , fname )
for themeName , track := range c . overridenTrack {
c . detail ( "themeName:" , themeName )
c . detailf ( "track: %+v\n" , track )
croot , ok := c . overridenRoots [ themeName ]
if ! ok {
croot = make ( map [ string ] bool )
c . overridenRoots [ themeName ] = croot
}
c . detailf ( "croot: %+v\n" , croot )
for tmplName , _ := range track {
cname := tmplName
if c . guestOnly {
cname += "_guest"
} else if c . memberOnly {
cname += "_member"
}
c . detail ( "cname:" , cname )
if fname == cname {
c . detail ( "match" )
croot [ strings . TrimSuffix ( strings . TrimSuffix ( fname , "_guest" ) , "_member" ) ] = true
} else {
c . detail ( "no match" )
}
}
}
c . detailf ( "c.overridenRoots: %+v\n" , c . overridenRoots )
2018-11-18 05:28:27 +00:00
var outBuf [ ] OutBufferFrame
2019-08-20 22:32:10 +00:00
rootHold := "tmpl_" + fname + "_vars"
2019-02-10 05:52:26 +00:00
con := CContext {
RootHolder : rootHold ,
VarHolder : rootHold ,
HoldReflect : reflect . ValueOf ( expectsInt ) ,
RootTemplateName : fname ,
TemplateName : fname ,
OutBuf : & outBuf ,
}
2019-10-12 22:49:08 +00:00
c . templateList = map [ string ] * parse . Tree { }
for nname , tree := range treeSet {
if name == nname {
c . templateList [ fname ] = tree
} else {
if ! strings . HasPrefix ( nname , ".html" ) {
c . templateList [ nname ] = tree
} else {
c . templateList [ strings . TrimSuffix ( nname , ".html" ) ] = tree
}
}
}
c . detailf ( "c.templateList: %+v\n" , c . templateList )
2016-12-16 10:37:42 +00:00
c . localVars = make ( map [ string ] map [ string ] VarItemReflect )
c . localVars [ fname ] = make ( map [ string ] VarItemReflect )
2018-11-18 05:28:27 +00:00
c . localVars [ fname ] [ "." ] = VarItemReflect { "." , con . VarHolder , con . HoldReflect }
2019-02-28 07:28:17 +00:00
if c . fragOnce == nil {
c . fragOnce = make ( map [ string ] bool )
2017-01-17 07:55:46 +00:00
}
2018-03-12 04:52:47 +00:00
c . fragmentCursor = map [ string ] int { fname : 0 }
2018-11-19 23:06:15 +00:00
c . fragBuf = nil
2018-03-08 03:59:47 +00:00
c . langIndexToName = nil
2017-06-16 10:41:30 +00:00
2018-03-12 04:52:47 +00:00
// TODO: Is this the first template loaded in? We really should have some sort of constructor for CTemplateSet
2019-02-28 07:28:17 +00:00
//if c.templateFragmentCount == nil {
// c.templateFragmentCount = make(map[string]int)
//}
//c.detailf("c: %+v\n", c)
2018-03-12 04:52:47 +00:00
2019-10-12 22:49:08 +00:00
c . detailf ( "name: %+v\n" , name )
c . detailf ( "fname: %+v\n" , fname )
2018-11-22 07:21:43 +00:00
startIndex := con . StartTemplate ( "" )
2019-10-12 22:49:08 +00:00
ttree := c . templateList [ fname ]
if ttree == nil {
panic ( "ttree is nil" )
}
c . rootIterate ( ttree , con )
2018-11-22 07:21:43 +00:00
con . EndTemplate ( "" )
c . afterTemplate ( con , startIndex )
2019-02-28 07:28:17 +00:00
//c.templateFragmentCount[fname] = c.fragmentCursor[fname] + 1
2017-06-16 10:41:30 +00:00
2019-02-28 07:28:17 +00:00
_ , ok := c . fragOnce [ fname ]
2018-11-19 23:06:15 +00:00
if ! ok {
2019-02-28 07:28:17 +00:00
c . fragOnce [ fname ] = true
2018-11-19 23:06:15 +00:00
}
2018-11-01 06:43:56 +00:00
if len ( c . langIndexToName ) > 0 {
c . importMap [ langPkg ] = langPkg
}
2019-06-03 05:26:27 +00:00
// TODO: Simplify this logic by doing some reordering?
if c . lang == "normal" {
c . importMap [ "net/http" ] = "net/http"
}
2016-12-16 10:37:42 +00:00
var importList string
2018-04-22 12:33:56 +00:00
for _ , item := range c . importMap {
2019-10-06 05:32:08 +00:00
ispl := strings . Split ( item , " " )
2019-08-20 22:32:10 +00:00
if len ( ispl ) > 1 {
2019-10-06 05:32:08 +00:00
importList += "import " + ispl [ 0 ] + " \"" + ispl [ 1 ] + "\"\n"
2019-08-20 22:32:10 +00:00
} else {
importList += "import \"" + item + "\"\n"
}
2016-12-16 10:37:42 +00:00
}
var varString string
for _ , varItem := range c . varList {
varString += "var " + varItem . Name + " " + varItem . Type + " = " + varItem . Destination + "\n"
}
2017-06-16 10:41:30 +00:00
2018-06-24 13:49:29 +00:00
var fout string
if c . buildTags != "" {
fout += "// +build " + c . buildTags + "\n\n"
}
fout += "// Code generated by Gosora. More below:\n/* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */\n"
2018-04-22 12:33:56 +00:00
fout += "package " + c . config . PackageName + "\n" + importList + "\n"
2017-11-11 06:33:08 +00:00
2019-11-07 03:53:29 +00:00
if c . lang == "js" {
var l string
if len ( c . langIndexToName ) > 0 {
for _ , name := range c . langIndexToName {
l += "\t" + ` " ` + name + ` " ` + ",\n"
}
}
if len ( l ) > 0 {
l = "\n" + l
}
fout += "if(tmplInits===undefined) var tmplInits = {}\n"
fout += "tmplInits[\"template_" + fname + "\"] = [" + l + "]\n"
} else if ! c . config . SkipInitBlock {
2018-04-22 12:33:56 +00:00
if len ( c . langIndexToName ) > 0 {
fout += "var " + fname + "_tmpl_phrase_id int\n\n"
}
fout += "// nolint\nfunc init() {\n"
2017-11-11 06:33:08 +00:00
2019-02-28 07:28:17 +00:00
if ! c . config . SkipHandles && c . themeName == "" {
2019-08-20 22:32:10 +00:00
fout += "\tc.Template_" + fname + "_handle = Template_" + fname + "\n"
fout += "\tc.Ctemplates = append(c.Ctemplates,\"" + fname + "\")\n"
2018-04-22 12:33:56 +00:00
}
2017-11-11 06:33:08 +00:00
2018-06-24 13:49:29 +00:00
if ! c . config . SkipTmplPtrMap {
2019-02-28 07:28:17 +00:00
fout += "tmpl := Template_" + fname + "\n"
2019-08-20 22:32:10 +00:00
fout += "\tc.TmplPtrMap[\"" + fname + "\"] = &tmpl\n"
fout += "\tc.TmplPtrMap[\"o_" + fname + "\"] = tmpl\n"
2018-06-24 13:49:29 +00:00
}
2018-04-22 12:33:56 +00:00
if len ( c . langIndexToName ) > 0 {
2018-11-01 06:43:56 +00:00
fout += "\t" + fname + "_tmpl_phrase_id = phrases.RegisterTmplPhraseNames([]string{\n"
2018-04-22 12:33:56 +00:00
for _ , name := range c . langIndexToName {
fout += "\t\t" + ` " ` + name + ` " ` + ",\n"
}
fout += "\t})\n"
2018-03-08 03:59:47 +00:00
}
2018-04-22 12:33:56 +00:00
fout += "}\n\n"
2018-03-08 03:59:47 +00:00
}
2017-11-11 06:33:08 +00:00
2019-04-28 10:08:05 +00:00
if c . lang == "normal" {
2019-05-13 09:17:44 +00:00
fout += "// nolint\nfunc Template_" + fname + "(tmpl_" + fname + "_i interface{}, w io.Writer) error {\n"
fout += ` tmpl_ ` + fname + ` _vars, ok := tmpl_ ` + fname + ` _i.( ` + expects + ` )
2019-02-10 05:52:26 +00:00
if ! ok {
return errors . New ( "invalid page struct value" )
}
`
2019-05-13 09:17:44 +00:00
fout += ` var iw http . ResponseWriter
2019-08-20 22:32:10 +00:00
gzw , ok := w . ( c . GzipResponseWriter )
2019-04-27 06:32:26 +00:00
if ok {
iw = gzw . ResponseWriter
}
_ = iw
`
2019-04-28 10:08:05 +00:00
} else {
fout += "// nolint\nfunc Template_" + fname + "(tmpl_" + fname + "_vars interface{}, w io.Writer) error {\n"
2019-04-27 06:32:26 +00:00
}
2018-03-08 03:59:47 +00:00
if len ( c . langIndexToName ) > 0 {
2018-11-01 06:43:56 +00:00
fout += "var plist = phrases.GetTmplPhrasesBytes(" + fname + "_tmpl_phrase_id)\n"
2018-03-08 03:59:47 +00:00
}
2018-11-18 05:28:27 +00:00
fout += varString
2018-11-19 23:06:15 +00:00
2019-10-06 05:32:08 +00:00
skipped := make ( map [ string ] * SkipBlock ) // map[templateName]*SkipBlock{map[atIndexAndAfter]skipThisMuch,lastCount}
2018-11-19 23:06:15 +00:00
2019-10-06 05:32:08 +00:00
writeTextFrame := func ( tmplName string , index int ) {
2018-11-19 23:06:15 +00:00
out := "w.Write(" + tmplName + "_frags[" + strconv . Itoa ( index ) + "]" + ")\n"
c . detail ( "writing " , out )
fout += out
}
for fid := 0 ; len ( outBuf ) > fid ; fid ++ {
frame := outBuf [ fid ]
2018-11-28 21:46:53 +00:00
c . detail ( frame . Type + " frame" )
2018-11-19 23:06:15 +00:00
if frame . Type == "text" {
c . detail ( frame )
oid := fid
2018-11-26 05:08:10 +00:00
c . detail ( "oid:" , oid )
2018-11-19 23:06:15 +00:00
skipBlock , ok := skipped [ frame . TemplateName ]
if ! ok {
skipBlock = & SkipBlock { make ( map [ int ] int ) , 0 , 0 }
skipped [ frame . TemplateName ] = skipBlock
}
skip := skipBlock . LastCount
c . detailf ( "skipblock %+v\n" , skipBlock )
2018-11-26 05:08:10 +00:00
//var count int
2018-11-19 23:06:15 +00:00
for len ( outBuf ) > fid + 1 && outBuf [ fid + 1 ] . Type == "text" && outBuf [ fid + 1 ] . TemplateName == frame . TemplateName {
2018-11-26 05:08:10 +00:00
c . detail ( "pre fid:" , fid )
//count++
2018-11-19 23:06:15 +00:00
next := outBuf [ fid + 1 ]
c . detail ( "next frame:" , next )
c . detail ( "frame frag:" , c . fragBuf [ frame . Extra2 . ( int ) ] )
c . detail ( "next frag:" , c . fragBuf [ next . Extra2 . ( int ) ] )
c . fragBuf [ frame . Extra2 . ( int ) ] . Body += c . fragBuf [ next . Extra2 . ( int ) ] . Body
c . fragBuf [ next . Extra2 . ( int ) ] . Seen = true
fid ++
2018-11-26 05:08:10 +00:00
skipBlock . LastCount ++
2018-11-19 23:06:15 +00:00
skipBlock . Frags [ frame . Extra . ( int ) ] = skipBlock . LastCount
2018-11-26 05:08:10 +00:00
c . detail ( "post fid:" , fid )
2018-11-19 23:06:15 +00:00
}
writeTextFrame ( frame . TemplateName , frame . Extra . ( int ) - skip )
2018-11-22 07:21:43 +00:00
} else if frame . Type == "varsub" || frame . Type == "cvarsub" {
fout += "w.Write(" + frame . Body + ")\n"
2018-11-26 05:08:10 +00:00
} else if frame . Type == "identifier" {
fout += frame . Body
2018-11-28 21:46:53 +00:00
} else if frame . Type == "lang" {
fout += "w.Write(plist[" + strconv . Itoa ( frame . Extra . ( int ) ) + "])\n"
2018-11-19 23:06:15 +00:00
} else {
fout += frame . Body
}
2018-11-18 05:28:27 +00:00
}
fout += "return nil\n}\n"
2017-06-16 10:41:30 +00:00
2019-10-06 05:32:08 +00:00
writeFrag := func ( tmplName string , index int , body string ) {
2018-12-14 04:08:53 +00:00
//c.detail("writing ", fragmentPrefix)
c . FragOut = append ( c . FragOut , OutFrag { tmplName , index , body } )
2018-11-19 23:06:15 +00:00
}
2018-11-18 07:14:18 +00:00
for _ , frag := range c . fragBuf {
2018-11-19 23:06:15 +00:00
c . detail ( "frag: " , frag )
if frag . Seen {
c . detail ( "invisible" )
continue
}
2018-12-08 06:49:14 +00:00
// TODO: What if the same template is invoked in multiple spots in a template?
2018-11-19 23:06:15 +00:00
skipBlock := skipped [ frag . TemplateName ]
skip := skipBlock . Frags [ skipBlock . ClosestFragSkip ]
_ , ok := skipBlock . Frags [ frag . Index ]
if ok {
skipBlock . ClosestFragSkip = frag . Index
}
c . detailf ( "skipblock %+v\n" , skipBlock )
c . detail ( "skipping " , skip )
2018-12-08 06:49:14 +00:00
index := frag . Index - skip
if index < 0 {
index = 0
}
writeFrag ( frag . TemplateName , index , frag . Body )
2018-11-18 07:14:18 +00:00
}
2017-06-16 10:41:30 +00:00
2018-11-19 23:06:15 +00:00
fout = strings . Replace ( fout , ` ) )
w . Write ( [ ] byte ( ` , " + " , - 1 )
fout = strings . Replace ( fout , "` + `" , "" , - 1 )
2018-03-08 03:59:47 +00:00
if c . config . Debug {
2017-05-07 08:31:41 +00:00
for index , count := range c . stats {
2019-02-28 07:28:17 +00:00
c . logger . Println ( index + ": " , strconv . Itoa ( count ) )
2017-05-07 08:31:41 +00:00
}
2019-02-28 07:28:17 +00:00
c . logger . Println ( " " )
2016-12-17 03:39:53 +00:00
}
2018-03-21 05:56:33 +00:00
c . detail ( "Output!" )
c . detail ( fout )
2017-08-13 11:22:34 +00:00
return fout , nil
2016-12-16 10:37:42 +00:00
}
2018-11-18 05:28:27 +00:00
func ( c * CTemplateSet ) rootIterate ( tree * parse . Tree , con CContext ) {
2018-11-19 23:06:15 +00:00
c . dumpCall ( "rootIterate" , tree , con )
2019-10-12 22:49:08 +00:00
if tree . Root == nil {
c . detailf ( "tree: %+v\n" , tree )
panic ( "tree root node is empty" )
}
2018-03-21 05:56:33 +00:00
c . detail ( tree . Root )
2018-11-26 05:08:10 +00:00
for _ , node := range tree . Root . Nodes {
2018-03-21 05:56:33 +00:00
c . detail ( "Node:" , node . String ( ) )
2018-11-18 05:28:27 +00:00
c . compileSwitch ( con , node )
2017-11-06 16:24:45 +00:00
}
2018-11-19 23:06:15 +00:00
c . retCall ( "rootIterate" )
2017-11-06 16:24:45 +00:00
}
2019-02-10 05:52:26 +00:00
func inSlice ( haystack [ ] string , expr string ) bool {
2018-12-15 04:39:50 +00:00
for _ , needle := range haystack {
if needle == expr {
return true
}
}
return false
}
2018-11-18 05:28:27 +00:00
func ( c * CTemplateSet ) compileSwitch ( con CContext , node parse . Node ) {
c . dumpCall ( "compileSwitch" , con , node )
2018-11-19 23:06:15 +00:00
defer c . retCall ( "compileSwitch" )
2016-12-16 10:37:42 +00:00
switch node := node . ( type ) {
2017-09-03 04:50:31 +00:00
case * parse . ActionNode :
2018-03-21 05:56:33 +00:00
c . detail ( "Action Node" )
2017-09-03 04:50:31 +00:00
if node . Pipe == nil {
break
}
for _ , cmd := range node . Pipe . Cmds {
2018-11-18 05:28:27 +00:00
c . compileSubSwitch ( con , cmd )
2017-09-03 04:50:31 +00:00
}
case * parse . IfNode :
2018-03-21 05:56:33 +00:00
c . detail ( "If Node:" )
c . detail ( "node.Pipe" , node . Pipe )
2017-09-03 04:50:31 +00:00
var expr string
for _ , cmd := range node . Pipe . Cmds {
2018-03-21 05:56:33 +00:00
c . detail ( "If Node Bit:" , cmd )
c . detail ( "Bit Type:" , reflect . ValueOf ( cmd ) . Type ( ) . Name ( ) )
2018-11-18 05:28:27 +00:00
expr += c . compileExprSwitch ( con , cmd )
c . detail ( "Expression Step:" , c . compileExprSwitch ( con , cmd ) )
2017-09-03 04:50:31 +00:00
}
2017-06-16 10:41:30 +00:00
2018-03-21 05:56:33 +00:00
c . detail ( "Expression:" , expr )
2018-11-26 05:08:10 +00:00
// Simple member / guest optimisation for now
// TODO: Expand upon this
2019-04-27 06:32:26 +00:00
userExprs , negUserExprs := buildUserExprs ( con . RootHolder )
2018-11-26 05:08:10 +00:00
if c . guestOnly {
c . detail ( "optimising away member branch" )
if inSlice ( userExprs , expr ) {
c . detail ( "positive conditional:" , expr )
if node . ElseList != nil {
c . compileSwitch ( con , node . ElseList )
}
return
} else if inSlice ( negUserExprs , expr ) {
c . detail ( "negative conditional:" , expr )
c . compileSwitch ( con , node . List )
return
}
} else if c . memberOnly {
c . detail ( "optimising away guest branch" )
if ( con . RootHolder + ".CurrentUser.Loggedin" ) == expr {
c . detail ( "positive conditional:" , expr )
c . compileSwitch ( con , node . List )
return
} else if ( "!" + con . RootHolder + ".CurrentUser.Loggedin" ) == expr {
c . detail ( "negative conditional:" , expr )
if node . ElseList != nil {
c . compileSwitch ( con , node . ElseList )
}
return
}
}
2018-11-18 05:28:27 +00:00
con . Push ( "startif" , "if " + expr + " {\n" )
c . compileSwitch ( con , node . List )
2017-09-03 04:50:31 +00:00
if node . ElseList == nil {
2018-03-21 05:56:33 +00:00
c . detail ( "Selected Branch 1" )
2018-11-18 05:28:27 +00:00
con . Push ( "endif" , "}\n" )
} else {
c . detail ( "Selected Branch 2" )
con . Push ( "endif" , "}" )
con . Push ( "startelse" , " else {\n" )
c . compileSwitch ( con , node . ElseList )
con . Push ( "endelse" , "}\n" )
2017-09-03 04:50:31 +00:00
}
case * parse . ListNode :
2018-11-26 05:08:10 +00:00
c . detailf ( "List Node: %+v\n" , node )
2017-09-03 04:50:31 +00:00
for _ , subnode := range node . Nodes {
2018-11-18 05:28:27 +00:00
c . compileSwitch ( con , subnode )
2017-09-03 04:50:31 +00:00
}
case * parse . RangeNode :
2018-11-18 05:28:27 +00:00
c . compileRangeNode ( con , node )
2017-09-03 04:50:31 +00:00
case * parse . TemplateNode :
2018-11-18 05:28:27 +00:00
c . compileSubTemplate ( con , node )
2017-09-03 04:50:31 +00:00
case * parse . TextNode :
2018-12-17 04:58:55 +00:00
c . addText ( con , node . Text )
2017-09-03 04:50:31 +00:00
default :
2018-11-18 05:28:27 +00:00
c . unknownNode ( node )
2016-12-16 10:37:42 +00:00
}
2017-11-07 22:38:15 +00:00
}
2018-12-17 04:58:55 +00:00
func ( c * CTemplateSet ) addText ( con CContext , text [ ] byte ) {
2019-02-28 07:28:17 +00:00
c . dumpCall ( "addText" , con , text )
2018-12-17 04:58:55 +00:00
tmpText := bytes . TrimSpace ( text )
if len ( tmpText ) == 0 {
return
}
nodeText := string ( text )
2019-02-28 07:28:17 +00:00
c . detail ( "con.TemplateName: " , con . TemplateName )
2018-12-17 04:58:55 +00:00
fragIndex := c . fragmentCursor [ con . TemplateName ]
2019-02-28 07:28:17 +00:00
_ , ok := c . fragOnce [ con . TemplateName ]
2018-12-17 04:58:55 +00:00
c . fragBuf = append ( c . fragBuf , Fragment { nodeText , con . TemplateName , fragIndex , ok } )
con . PushText ( strconv . Itoa ( fragIndex ) , fragIndex , len ( c . fragBuf ) - 1 )
c . fragmentCursor [ con . TemplateName ] = fragIndex + 1
}
2018-11-18 05:28:27 +00:00
func ( c * CTemplateSet ) compileRangeNode ( con CContext , node * parse . RangeNode ) {
c . dumpCall ( "compileRangeNode" , con , node )
2018-11-19 23:06:15 +00:00
defer c . retCall ( "compileRangeNode" )
2018-11-18 05:28:27 +00:00
c . detail ( "node.Pipe: " , node . Pipe )
var expr string
2017-11-07 22:38:15 +00:00
var outVal reflect . Value
for _ , cmd := range node . Pipe . Cmds {
2018-03-21 05:56:33 +00:00
c . detail ( "Range Bit:" , cmd )
2018-11-18 05:28:27 +00:00
// ! This bit is slightly suspect, hm.
expr , outVal = c . compileReflectSwitch ( con , cmd )
2017-11-07 22:38:15 +00:00
}
2018-11-18 05:28:27 +00:00
c . detail ( "Expr:" , expr )
2018-03-21 05:56:33 +00:00
c . detail ( "Range Kind Switch!" )
2017-11-07 22:38:15 +00:00
2019-10-06 05:32:08 +00:00
startIf := func ( item reflect . Value , useCopy bool ) {
2018-11-18 05:28:27 +00:00
con . Push ( "startif" , "if len(" + expr + ") != 0 {\n" )
2018-11-22 07:21:43 +00:00
startIndex := con . StartLoop ( "for _, item := range " + expr + " {\n" )
2018-11-18 05:28:27 +00:00
ccon := con
2018-11-22 07:21:43 +00:00
var depth string
if ccon . VarHolder == "item" {
depth = strings . TrimPrefix ( ccon . VarHolder , "item" )
if depth != "" {
idepth , err := strconv . Atoi ( depth )
if err != nil {
panic ( err )
}
depth = strconv . Itoa ( idepth + 1 )
}
}
ccon . VarHolder = "item" + depth
2018-11-18 05:28:27 +00:00
ccon . HoldReflect = item
c . compileSwitch ( ccon , node . List )
2018-11-26 05:08:10 +00:00
if con . LastBufIndex ( ) == startIndex {
con . DiscardAndAfter ( startIndex - 1 )
return
}
2018-11-22 07:21:43 +00:00
con . EndLoop ( "}\n" )
c . afterTemplate ( con , startIndex )
2018-11-18 05:28:27 +00:00
if node . ElseList != nil {
con . Push ( "endif" , "}" )
con . Push ( "startelse" , " else {\n" )
if ! useCopy {
ccon = con
}
c . compileSwitch ( ccon , node . ElseList )
con . Push ( "endelse" , "}\n" )
} else {
2018-11-22 07:21:43 +00:00
con . Push ( "endif" , "}\n" )
2018-11-18 05:28:27 +00:00
}
}
2017-11-07 22:38:15 +00:00
switch outVal . Kind ( ) {
case reflect . Map :
var item reflect . Value
for _ , key := range outVal . MapKeys ( ) {
item = outVal . MapIndex ( key )
}
2018-03-21 05:56:33 +00:00
c . detail ( "Range item:" , item )
2017-11-07 22:38:15 +00:00
if ! item . IsValid ( ) {
2019-02-10 05:52:26 +00:00
c . critical ( "expr:" , expr )
c . critical ( "con.VarHolder" , con . VarHolder )
2017-11-07 22:38:15 +00:00
panic ( "item" + "^\n" + "Invalid map. Maybe, it doesn't have any entries for the template engine to analyse?" )
}
2018-11-18 05:28:27 +00:00
startIf ( item , true )
2017-11-07 22:38:15 +00:00
case reflect . Slice :
if outVal . Len ( ) == 0 {
2019-02-10 05:52:26 +00:00
c . critical ( "expr:" , expr )
c . critical ( "con.VarHolder" , con . VarHolder )
2017-11-07 22:38:15 +00:00
panic ( "The sample data needs at-least one or more elements for the slices. We're looking into removing this requirement at some point!" )
}
2018-11-18 05:28:27 +00:00
startIf ( outVal . Index ( 0 ) , false )
2017-11-07 22:38:15 +00:00
case reflect . Invalid :
2018-11-18 05:28:27 +00:00
return
2017-11-07 22:38:15 +00:00
}
2016-12-16 10:37:42 +00:00
}
2018-12-28 11:13:06 +00:00
// ! Temporary, we probably want something that is good with non-struct pointers too
// For compileSubSwitch and compileSubTemplate
func ( c * CTemplateSet ) skipStructPointers ( cur reflect . Value , id string ) reflect . Value {
if cur . Kind ( ) == reflect . Ptr {
c . detail ( "Looping over pointer" )
for cur . Kind ( ) == reflect . Ptr {
cur = cur . Elem ( )
}
c . detail ( "Data Kind:" , cur . Kind ( ) . String ( ) )
c . detail ( "Field Bit:" , id )
}
return cur
}
// For compileSubSwitch and compileSubTemplate
func ( c * CTemplateSet ) checkIfValid ( cur reflect . Value , varHolder string , holdreflect reflect . Value , varBit string , multiline bool ) {
if ! cur . IsValid ( ) {
c . critical ( "Debug Data:" )
c . critical ( "Holdreflect:" , holdreflect )
c . critical ( "Holdreflect.Kind():" , holdreflect . Kind ( ) )
if ! c . config . SuperDebug {
c . critical ( "cur.Kind():" , cur . Kind ( ) . String ( ) )
}
c . critical ( "" )
if ! multiline {
panic ( varHolder + varBit + "^\n" + "Invalid value. Maybe, it doesn't exist?" )
}
panic ( varBit + "^\n" + "Invalid value. Maybe, it doesn't exist?" )
}
}
2018-11-18 05:28:27 +00:00
func ( c * CTemplateSet ) compileSubSwitch ( con CContext , node * parse . CommandNode ) {
c . dumpCall ( "compileSubSwitch" , con , node )
2018-12-28 11:13:06 +00:00
switch n := node . Args [ 0 ] . ( type ) {
2017-09-03 04:50:31 +00:00
case * parse . FieldNode :
2018-03-21 05:56:33 +00:00
c . detail ( "Field Node:" , n . Ident )
2017-09-03 04:50:31 +00:00
/* Use reflect to determine if the field is for a method, otherwise assume it's a variable. Variable declarations are coming soon! */
2018-11-18 05:28:27 +00:00
cur := con . HoldReflect
2017-06-16 10:41:30 +00:00
2018-11-18 05:28:27 +00:00
var varBit string
2017-09-03 04:50:31 +00:00
if cur . Kind ( ) == reflect . Interface {
cur = cur . Elem ( )
2018-11-18 05:28:27 +00:00
varBit += ".(" + cur . Type ( ) . Name ( ) + ")"
2017-09-03 04:50:31 +00:00
}
2017-11-23 05:37:08 +00:00
var assLines string
2019-10-06 05:32:08 +00:00
multiline := false
2017-11-23 05:37:08 +00:00
for _ , id := range n . Ident {
2018-03-21 05:56:33 +00:00
c . detail ( "Data Kind:" , cur . Kind ( ) . String ( ) )
c . detail ( "Field Bit:" , id )
2018-12-28 11:13:06 +00:00
cur = c . skipStructPointers ( cur , id )
c . checkIfValid ( cur , con . VarHolder , con . HoldReflect , varBit , multiline )
2017-09-10 16:57:22 +00:00
2018-11-18 05:28:27 +00:00
c . detail ( "in-loop varBit: " + varBit )
2017-11-23 05:37:08 +00:00
if cur . Kind ( ) == reflect . Map {
cur = cur . MapIndex ( reflect . ValueOf ( id ) )
2018-11-18 05:28:27 +00:00
varBit += "[\"" + id + "\"]"
2018-12-28 11:13:06 +00:00
cur = c . skipStructPointers ( cur , id )
2017-11-23 05:37:08 +00:00
if cur . Kind ( ) == reflect . Struct || cur . Kind ( ) == reflect . Interface {
// TODO: Move the newVarByte declaration to the top level or to the if level, if a dispInt is only used in a particular if statement
var dispStr , newVarByte string
if cur . Kind ( ) == reflect . Interface {
dispStr = "Int"
if ! c . hasDispInt {
newVarByte = ":"
c . hasDispInt = true
}
}
// TODO: De-dupe identical struct types rather than allocating a variable for each one
if cur . Kind ( ) == reflect . Struct {
dispStr = "Struct" + strconv . Itoa ( c . localDispStructIndex )
newVarByte = ":"
c . localDispStructIndex ++
}
2018-11-18 05:28:27 +00:00
con . VarHolder = "disp" + dispStr
varBit = con . VarHolder + " " + newVarByte + "= " + con . VarHolder + varBit + "\n"
2017-11-23 05:37:08 +00:00
multiline = true
} else {
continue
}
}
if cur . Kind ( ) != reflect . Interface {
cur = cur . FieldByName ( id )
2018-11-18 05:28:27 +00:00
varBit += "." + id
2016-12-16 10:37:42 +00:00
}
2017-09-03 04:50:31 +00:00
2017-11-23 05:37:08 +00:00
// TODO: Handle deeply nested pointers mixed with interfaces mixed with pointers better
2017-09-03 04:50:31 +00:00
if cur . Kind ( ) == reflect . Interface {
cur = cur . Elem ( )
2018-11-18 05:28:27 +00:00
varBit += ".("
2017-11-23 05:37:08 +00:00
// TODO: Surely, there's a better way of doing this?
2017-09-03 04:50:31 +00:00
if cur . Type ( ) . PkgPath ( ) != "main" && cur . Type ( ) . PkgPath ( ) != "" {
c . importMap [ "html/template" ] = "html/template"
2018-11-18 05:28:27 +00:00
varBit += strings . TrimPrefix ( cur . Type ( ) . PkgPath ( ) , "html/" ) + "."
2017-09-03 04:50:31 +00:00
}
2018-11-18 05:28:27 +00:00
varBit += cur . Type ( ) . Name ( ) + ")"
2016-12-16 10:37:42 +00:00
}
2018-11-18 05:28:27 +00:00
c . detail ( "End Cycle: " , varBit )
2017-09-03 04:50:31 +00:00
}
2017-11-23 05:37:08 +00:00
if multiline {
2018-11-18 05:28:27 +00:00
assSplit := strings . Split ( varBit , "\n" )
varBit = assSplit [ len ( assSplit ) - 1 ]
2017-11-23 05:37:08 +00:00
assSplit = assSplit [ : len ( assSplit ) - 1 ]
assLines = strings . Join ( assSplit , "\n" ) + "\n"
}
2018-11-18 05:28:27 +00:00
c . compileVarSub ( con , con . VarHolder + varBit , cur , assLines , func ( in string ) string {
for _ , varItem := range c . varList {
if strings . HasPrefix ( in , varItem . Destination ) {
in = strings . Replace ( in , varItem . Destination , varItem . Name , 1 )
}
2017-01-21 18:16:27 +00:00
}
2018-11-18 05:28:27 +00:00
return in
} )
2017-09-03 04:50:31 +00:00
case * parse . DotNode :
2018-03-21 05:56:33 +00:00
c . detail ( "Dot Node:" , node . String ( ) )
2018-11-18 05:28:27 +00:00
c . compileVarSub ( con , con . VarHolder , con . HoldReflect , "" , nil )
2017-09-03 04:50:31 +00:00
case * parse . NilNode :
panic ( "Nil is not a command x.x" )
case * parse . VariableNode :
2018-03-21 05:56:33 +00:00
c . detail ( "Variable Node:" , n . String ( ) )
c . detail ( n . Ident )
2018-11-18 05:28:27 +00:00
varname , reflectVal := c . compileIfVarSub ( con , n . String ( ) )
c . compileVarSub ( con , varname , reflectVal , "" , nil )
2017-09-03 04:50:31 +00:00
case * parse . StringNode :
2018-11-18 05:28:27 +00:00
con . Push ( "stringnode" , n . Quoted )
2017-09-03 04:50:31 +00:00
case * parse . IdentifierNode :
2018-03-21 05:56:33 +00:00
c . detail ( "Identifier Node:" , node )
c . detail ( "Identifier Node Args:" , node . Args )
2018-11-28 21:46:53 +00:00
out , outval , lit , noident := c . compileIdentSwitch ( con , node )
if noident {
return
} else if lit {
2018-11-18 05:28:27 +00:00
con . Push ( "identifier" , out )
return
2017-11-29 02:34:02 +00:00
}
2018-11-18 05:28:27 +00:00
c . compileVarSub ( con , out , outval , "" , nil )
2017-09-03 04:50:31 +00:00
default :
2018-11-18 05:28:27 +00:00
c . unknownNode ( node )
2016-12-16 10:37:42 +00:00
}
}
2018-11-18 05:28:27 +00:00
func ( c * CTemplateSet ) compileExprSwitch ( con CContext , node * parse . CommandNode ) ( out string ) {
2018-11-18 05:43:10 +00:00
c . dumpCall ( "compileExprSwitch" , con , node )
2016-12-16 10:37:42 +00:00
firstWord := node . Args [ 0 ]
switch n := firstWord . ( type ) {
2017-09-03 04:50:31 +00:00
case * parse . FieldNode :
2018-03-08 03:59:47 +00:00
if c . config . SuperDebug {
2019-02-28 07:28:17 +00:00
c . logger . Println ( "Field Node:" , n . Ident )
2017-09-03 04:50:31 +00:00
for _ , id := range n . Ident {
2019-02-28 07:28:17 +00:00
c . logger . Println ( "Field Bit:" , id )
2016-12-16 10:37:42 +00:00
}
2017-09-03 04:50:31 +00:00
}
/* Use reflect to determine if the field is for a method, otherwise assume it's a variable. Coming Soon. */
2018-11-18 05:43:10 +00:00
out = c . compileBoolSub ( con , n . String ( ) )
2017-09-03 04:50:31 +00:00
case * parse . ChainNode :
2018-03-21 05:56:33 +00:00
c . detail ( "Chain Node:" , n . Node )
c . detail ( "Node Args:" , node . Args )
2017-09-03 04:50:31 +00:00
case * parse . IdentifierNode :
2018-03-21 05:56:33 +00:00
c . detail ( "Identifier Node:" , node )
c . detail ( "Node Args:" , node . Args )
2018-11-18 05:43:10 +00:00
out = c . compileIdentSwitchN ( con , node )
2017-09-03 04:50:31 +00:00
case * parse . DotNode :
2018-11-18 05:43:10 +00:00
out = con . VarHolder
2017-09-03 04:50:31 +00:00
case * parse . VariableNode :
2018-03-21 05:56:33 +00:00
c . detail ( "Variable Node:" , n . String ( ) )
c . detail ( "Node Identifier:" , n . Ident )
2018-11-18 05:28:27 +00:00
out , _ = c . compileIfVarSub ( con , n . String ( ) )
2017-09-03 04:50:31 +00:00
case * parse . NilNode :
panic ( "Nil is not a command x.x" )
case * parse . PipeNode :
2018-03-21 05:56:33 +00:00
c . detail ( "Pipe Node!" )
c . detail ( n )
c . detail ( "Node Args:" , node . Args )
2018-11-18 05:28:27 +00:00
out += c . compileIdentSwitchN ( con , node )
2017-09-03 04:50:31 +00:00
default :
2018-11-18 05:28:27 +00:00
c . unknownNode ( firstWord )
2016-12-16 10:37:42 +00:00
}
2018-11-18 05:43:10 +00:00
c . retCall ( "compileExprSwitch" , out )
2017-11-07 22:38:15 +00:00
return out
}
2018-11-18 05:28:27 +00:00
func ( c * CTemplateSet ) unknownNode ( node parse . Node ) {
2019-11-07 03:53:29 +00:00
elem := reflect . ValueOf ( node ) . Elem ( )
c . logger . Println ( "Unknown Kind:" , elem . Kind ( ) )
c . logger . Println ( "Unknown Type:" , elem . Type ( ) . Name ( ) )
2017-11-07 22:38:15 +00:00
panic ( "I don't know what node this is! Grr..." )
2016-12-16 10:37:42 +00:00
}
2018-11-18 05:28:27 +00:00
func ( c * CTemplateSet ) compileIdentSwitchN ( con CContext , node * parse . CommandNode ) ( out string ) {
2018-03-21 05:56:33 +00:00
c . detail ( "in compileIdentSwitchN" )
2018-11-28 21:46:53 +00:00
out , _ , _ , _ = c . compileIdentSwitch ( con , node )
2017-01-21 18:16:27 +00:00
return out
}
2017-11-08 00:12:50 +00:00
func ( c * CTemplateSet ) dumpSymbol ( pos int , node * parse . CommandNode , symbol string ) {
2018-03-21 05:56:33 +00:00
c . detail ( "symbol: " , symbol )
2019-11-07 03:53:29 +00:00
c . detail ( "node.Args[pos+1]" , node . Args [ pos + 1 ] )
c . detail ( "node.Args[pos+2]" , node . Args [ pos + 2 ] )
2017-11-08 00:12:50 +00:00
}
2018-11-18 05:28:27 +00:00
func ( c * CTemplateSet ) compareFunc ( con CContext , pos int , node * parse . CommandNode , compare string ) ( out string ) {
2017-11-08 00:12:50 +00:00
c . dumpSymbol ( pos , node , compare )
2018-11-18 05:28:27 +00:00
return c . compileIfVarSubN ( con , node . Args [ pos + 1 ] . String ( ) ) + " " + compare + " " + c . compileIfVarSubN ( con , node . Args [ pos + 2 ] . String ( ) )
2017-11-07 22:38:15 +00:00
}
2018-11-18 05:28:27 +00:00
func ( c * CTemplateSet ) simpleMath ( con CContext , pos int , node * parse . CommandNode , symbol string ) ( out string , val reflect . Value ) {
leftParam , val2 := c . compileIfVarSub ( con , node . Args [ pos + 1 ] . String ( ) )
rightParam , val3 := c . compileIfVarSub ( con , node . Args [ pos + 2 ] . String ( ) )
2017-11-07 22:38:15 +00:00
if val2 . IsValid ( ) {
val = val2
} else if val3 . IsValid ( ) {
val = val3
} else {
// TODO: What does this do?
numSample := 1
val = reflect . ValueOf ( numSample )
}
2017-11-08 00:12:50 +00:00
c . dumpSymbol ( pos , node , symbol )
2017-11-07 22:38:15 +00:00
return leftParam + " " + symbol + " " + rightParam , val
}
2018-11-18 05:28:27 +00:00
func ( c * CTemplateSet ) compareJoin ( con CContext , pos int , node * parse . CommandNode , symbol string ) ( pos2 int , out string ) {
2018-03-21 05:56:33 +00:00
c . detailf ( "Building %s function" , symbol )
2017-11-07 22:38:15 +00:00
if pos == 0 {
2019-02-28 07:28:17 +00:00
c . logger . Println ( "pos:" , pos )
2017-11-07 22:38:15 +00:00
panic ( symbol + " is missing a left operand" )
}
if len ( node . Args ) <= pos {
2019-02-28 07:28:17 +00:00
c . logger . Println ( "post pos:" , pos )
c . logger . Println ( "len(node.Args):" , len ( node . Args ) )
2017-11-07 22:38:15 +00:00
panic ( symbol + " is missing a right operand" )
}
2018-11-18 05:43:10 +00:00
left := c . compileBoolSub ( con , node . Args [ pos - 1 ] . String ( ) )
2017-11-07 22:38:15 +00:00
_ , funcExists := c . funcMap [ node . Args [ pos + 1 ] . String ( ) ]
var right string
if ! funcExists {
2018-11-18 05:43:10 +00:00
right = c . compileBoolSub ( con , node . Args [ pos + 1 ] . String ( ) )
2017-11-07 22:38:15 +00:00
}
out = left + " " + symbol + " " + right
2018-03-21 05:56:33 +00:00
c . detail ( "Left operand:" , node . Args [ pos - 1 ] )
c . detail ( "Right operand:" , node . Args [ pos + 1 ] )
2017-11-07 22:38:15 +00:00
if ! funcExists {
pos ++
}
2018-03-21 05:56:33 +00:00
c . detail ( "pos:" , pos )
c . detail ( "len(node.Args):" , len ( node . Args ) )
2017-11-07 22:38:15 +00:00
return pos , out
}
2018-11-28 21:46:53 +00:00
func ( c * CTemplateSet ) compileIdentSwitch ( con CContext , node * parse . CommandNode ) ( out string , val reflect . Value , literal bool , notident bool ) {
2018-11-18 05:28:27 +00:00
c . dumpCall ( "compileIdentSwitch" , con , node )
2019-10-06 05:32:08 +00:00
litString := func ( inner string , bytes bool ) {
2018-11-19 23:06:15 +00:00
if ! bytes {
2018-12-15 04:39:50 +00:00
inner = "StringToBytes(" + inner + ")"
2018-11-19 23:06:15 +00:00
}
out = "w.Write(" + inner + ")\n"
2018-11-17 02:36:02 +00:00
literal = true
}
2017-09-03 04:50:31 +00:00
ArgLoop :
2017-06-05 11:57:27 +00:00
for pos := 0 ; pos < len ( node . Args ) ; pos ++ {
id := node . Args [ pos ]
2018-03-21 05:56:33 +00:00
c . detail ( "pos:" , pos )
c . detail ( "ID:" , id )
2016-12-16 10:37:42 +00:00
switch id . String ( ) {
2017-09-03 04:50:31 +00:00
case "not" :
out += "!"
2017-11-08 00:12:50 +00:00
case "or" , "and" :
2017-11-07 22:38:15 +00:00
var rout string
2018-11-18 05:28:27 +00:00
pos , rout = c . compareJoin ( con , pos , node , c . funcMap [ id . String ( ) ] . ( string ) ) // TODO: Test this
2017-11-07 22:38:15 +00:00
out += rout
2018-11-17 02:36:02 +00:00
case "le" , "lt" , "gt" , "ge" , "eq" , "ne" :
2018-11-18 05:28:27 +00:00
out += c . compareFunc ( con , pos , node , c . funcMap [ id . String ( ) ] . ( string ) )
2017-09-03 04:50:31 +00:00
break ArgLoop
2018-11-17 02:36:02 +00:00
case "add" , "subtract" , "divide" , "multiply" :
2018-11-18 05:28:27 +00:00
rout , rval := c . simpleMath ( con , pos , node , c . funcMap [ id . String ( ) ] . ( string ) )
2017-11-07 22:38:15 +00:00
out += rout
val = rval
2017-09-03 04:50:31 +00:00
break ArgLoop
2018-11-17 02:36:02 +00:00
case "elapsed" :
2019-11-07 03:53:29 +00:00
leftOp := node . Args [ pos + 1 ] . String ( )
leftParam , _ := c . compileIfVarSub ( con , leftOp )
2018-11-17 02:36:02 +00:00
// TODO: Refactor this
// TODO: Validate that this is actually a time.Time
2018-11-19 23:06:15 +00:00
litString ( "time.Since(" + leftParam + ").String()" , false )
2018-11-17 02:36:02 +00:00
c . importMap [ "time" ] = "time"
2017-09-03 04:50:31 +00:00
break ArgLoop
2017-11-29 02:34:02 +00:00
case "dock" :
// TODO: Implement string literals properly
2019-11-07 03:53:29 +00:00
leftOp := node . Args [ pos + 1 ] . String ( )
rightOp := node . Args [ pos + 2 ] . String ( )
if len ( leftOp ) == 0 || len ( rightOp ) == 0 {
2017-11-29 02:34:02 +00:00
panic ( "The left or right operand for function dock cannot be left blank" )
}
2019-11-07 03:53:29 +00:00
leftParam := leftOp
if leftOp [ 0 ] != '"' {
2018-11-18 05:28:27 +00:00
leftParam , _ = c . compileIfVarSub ( con , leftParam )
2017-11-29 02:34:02 +00:00
}
2019-11-07 03:53:29 +00:00
if rightOp [ 0 ] == '"' {
2017-11-29 02:34:02 +00:00
panic ( "The right operand for function dock cannot be a string" )
}
2019-11-07 03:53:29 +00:00
rightParam , val3 := c . compileIfVarSub ( con , rightOp )
2018-03-08 03:59:47 +00:00
if ! val3 . IsValid ( ) {
2017-11-29 02:34:02 +00:00
panic ( "val3 is invalid" )
}
2018-03-08 03:59:47 +00:00
val = val3
2017-11-29 02:34:02 +00:00
// TODO: Refactor this
2019-08-20 22:32:10 +00:00
litString ( "c.BuildWidget(" + leftParam + "," + rightParam + ")" , false )
2017-11-29 02:34:02 +00:00
break ArgLoop
2019-02-28 09:31:13 +00:00
case "hasWidgets" :
// TODO: Implement string literals properly
2019-11-07 03:53:29 +00:00
leftOp := node . Args [ pos + 1 ] . String ( )
rightOp := node . Args [ pos + 2 ] . String ( )
if len ( leftOp ) == 0 || len ( rightOp ) == 0 {
2019-02-28 09:31:13 +00:00
panic ( "The left or right operand for function dock cannot be left blank" )
}
2019-11-07 03:53:29 +00:00
leftParam := leftOp
if leftOp [ 0 ] != '"' {
2019-02-28 09:31:13 +00:00
leftParam , _ = c . compileIfVarSub ( con , leftParam )
}
2019-11-07 03:53:29 +00:00
if rightOp [ 0 ] == '"' {
2019-02-28 09:31:13 +00:00
panic ( "The right operand for function dock cannot be a string" )
}
2019-11-07 03:53:29 +00:00
rightParam , val3 := c . compileIfVarSub ( con , rightOp )
2019-02-28 09:31:13 +00:00
if ! val3 . IsValid ( ) {
panic ( "val3 is invalid" )
}
val = val3
// TODO: Refactor this
2019-08-20 22:32:10 +00:00
out = "c.HasWidgets(" + leftParam + "," + rightParam + ")"
2019-02-28 09:31:13 +00:00
literal = true
break ArgLoop
2018-03-08 03:59:47 +00:00
case "lang" :
// TODO: Implement string literals properly
2019-11-07 03:53:29 +00:00
leftOp := node . Args [ pos + 1 ] . String ( )
if len ( leftOp ) == 0 {
2018-03-08 03:59:47 +00:00
panic ( "The left operand for the language string cannot be left blank" )
}
2019-11-07 03:53:29 +00:00
if leftOp [ 0 ] == '"' {
2019-10-11 00:36:45 +00:00
// ! Slightly crude but it does the job
2019-11-07 03:53:29 +00:00
leftParam := strings . Replace ( leftOp , "\"" , "" , - 1 )
2019-10-11 00:36:45 +00:00
c . langIndexToName = append ( c . langIndexToName , leftParam )
notident = true
con . PushPhrase ( len ( c . langIndexToName ) - 1 )
} else {
2019-11-07 03:53:29 +00:00
leftParam := leftOp
if leftOp [ 0 ] != '"' {
2019-10-11 00:36:45 +00:00
leftParam , _ = c . compileIfVarSub ( con , leftParam )
}
// TODO: Add an optimisation if it's a string literal passsed in from a parent template rather than a true dynamic
litString ( "phrases.GetTmplPhrasef(" + leftParam + ")" , false )
c . importMap [ langPkg ] = langPkg
2018-03-08 03:59:47 +00:00
}
break ArgLoop
2019-06-16 23:36:31 +00:00
case "langf" :
// TODO: Implement string literals properly
2019-11-07 03:53:29 +00:00
leftOp := node . Args [ pos + 1 ] . String ( )
if len ( leftOp ) == 0 {
2019-06-16 23:36:31 +00:00
panic ( "The left operand for the language string cannot be left blank" )
}
2019-11-07 03:53:29 +00:00
if leftOp [ 0 ] != '"' {
2019-06-16 23:36:31 +00:00
panic ( "Phrase names cannot be dynamic" )
}
2019-10-06 05:32:08 +00:00
2019-06-16 23:36:31 +00:00
var olist [ ] string
2019-10-06 05:32:08 +00:00
for i := pos + 2 ; i < len ( node . Args ) ; i ++ {
2019-06-16 23:36:31 +00:00
op := node . Args [ i ] . String ( )
if op != "" {
2020-01-14 05:07:00 +00:00
if /*op[0] == '.' || */ op [ 0 ] == '$' {
2019-06-16 23:36:31 +00:00
panic ( "langf args cannot be dynamic" )
}
2020-01-14 05:07:00 +00:00
if op [ 0 ] != '.' && op [ 0 ] != '"' && ! unicode . IsDigit ( rune ( op [ 0 ] ) ) {
2019-06-16 23:36:31 +00:00
break
}
2019-10-06 05:32:08 +00:00
olist = append ( olist , op )
2019-06-16 23:36:31 +00:00
}
}
if len ( olist ) == 0 {
panic ( "You must provide parameters for langf" )
}
2019-10-06 05:32:08 +00:00
ob := ","
2019-06-16 23:36:31 +00:00
for _ , op := range olist {
2020-01-14 05:07:00 +00:00
if op [ 0 ] == '.' {
param , val3 := c . compileIfVarSub ( con , op )
if ! val3 . IsValid ( ) {
panic ( "val3 is invalid" )
}
ob += param + ","
continue
}
2019-06-16 23:36:31 +00:00
allNum := true
for _ , o := range op {
if ! unicode . IsDigit ( o ) {
allNum = false
}
}
if allNum {
2019-10-06 05:32:08 +00:00
ob += strings . Replace ( op , "\"" , "\\\"" , - 1 ) + ","
2019-06-16 23:36:31 +00:00
} else {
ob += ob + ","
}
}
if ob != "" {
ob = ob [ : len ( ob ) - 1 ]
}
// TODO: Implement string literals properly
// ! Slightly crude but it does the job
2019-11-07 03:53:29 +00:00
litString ( "phrases.GetTmplPhrasef(" + leftOp + ob + ")" , false )
2019-06-16 23:36:31 +00:00
c . importMap [ langPkg ] = langPkg
break ArgLoop
2018-10-10 07:33:51 +00:00
case "level" :
// TODO: Implement level literals
2019-11-07 03:53:29 +00:00
leftOp := node . Args [ pos + 1 ] . String ( )
if len ( leftOp ) == 0 {
2018-10-10 07:33:51 +00:00
panic ( "The leftoperand for function level cannot be left blank" )
}
2019-11-07 03:53:29 +00:00
leftParam , _ := c . compileIfVarSub ( con , leftOp )
2018-10-10 07:33:51 +00:00
// TODO: Refactor this
2018-11-19 23:06:15 +00:00
litString ( "phrases.GetLevelPhrase(" + leftParam + ")" , false )
2018-11-01 06:43:56 +00:00
c . importMap [ langPkg ] = langPkg
2018-10-10 07:33:51 +00:00
break ArgLoop
2019-05-13 09:17:44 +00:00
case "bunit" :
// TODO: Implement bunit literals
2019-11-07 03:53:29 +00:00
leftOp := node . Args [ pos + 1 ] . String ( )
if len ( leftOp ) == 0 {
2019-05-13 09:17:44 +00:00
panic ( "The leftoperand for function buint cannot be left blank" )
}
2019-11-07 03:53:29 +00:00
leftParam , _ := c . compileIfVarSub ( con , leftOp )
2019-08-20 22:32:10 +00:00
out = "{\nbyteFloat, unit := c.ConvertByteUnit(float64(" + leftParam + "))\n"
2019-10-12 22:49:08 +00:00
out += "w.Write(StringToBytes(fmt.Sprintf(\"%.1f\", byteFloat) + unit))\n}\n"
2019-05-13 09:17:44 +00:00
literal = true
2019-10-12 22:49:08 +00:00
c . importMap [ "fmt" ] = "fmt"
2019-05-13 09:17:44 +00:00
break ArgLoop
2018-12-14 04:08:53 +00:00
case "abstime" :
// TODO: Implement level literals
2019-11-07 03:53:29 +00:00
leftOp := node . Args [ pos + 1 ] . String ( )
if len ( leftOp ) == 0 {
2018-12-14 04:08:53 +00:00
panic ( "The leftoperand for function abstime cannot be left blank" )
}
2019-11-07 03:53:29 +00:00
leftParam , _ := c . compileIfVarSub ( con , leftOp )
2018-12-14 04:08:53 +00:00
// TODO: Refactor this
litString ( leftParam + ".Format(\"2006-01-02 15:04:05\")" , false )
break ArgLoop
2018-12-27 05:42:41 +00:00
case "reltime" :
// TODO: Implement level literals
2019-11-07 03:53:29 +00:00
leftOp := node . Args [ pos + 1 ] . String ( )
if len ( leftOp ) == 0 {
2018-12-27 05:42:41 +00:00
panic ( "The leftoperand for function reltime cannot be left blank" )
}
2019-11-07 03:53:29 +00:00
leftParam , _ := c . compileIfVarSub ( con , leftOp )
2018-12-27 05:42:41 +00:00
// TODO: Refactor this
2019-08-20 22:32:10 +00:00
litString ( "c.RelativeTime(" + leftParam + ")" , false )
2018-12-27 05:42:41 +00:00
break ArgLoop
2018-03-31 05:25:27 +00:00
case "scope" :
literal = true
break ArgLoop
2018-07-13 11:27:58 +00:00
case "dyntmpl" :
2018-11-18 05:28:27 +00:00
var pageParam , headParam string
2018-10-27 03:21:02 +00:00
// TODO: Implement string literals properly
// TODO: Should we check to see if pos+3 is within the bounds of the slice?
2019-11-07 03:53:29 +00:00
nameOp := node . Args [ pos + 1 ] . String ( )
pageOp := node . Args [ pos + 2 ] . String ( )
headOp := node . Args [ pos + 3 ] . String ( )
if len ( nameOp ) == 0 || len ( pageOp ) == 0 || len ( headOp ) == 0 {
2018-10-27 03:21:02 +00:00
panic ( "None of the three operands for function dyntmpl can be left blank" )
}
2019-11-07 03:53:29 +00:00
nameParam := nameOp
if nameOp [ 0 ] != '"' {
2018-11-18 05:28:27 +00:00
nameParam , _ = c . compileIfVarSub ( con , nameParam )
2018-10-27 03:21:02 +00:00
}
2019-11-07 03:53:29 +00:00
if pageOp [ 0 ] == '"' {
2018-10-27 03:21:02 +00:00
panic ( "The page operand for function dyntmpl cannot be a string" )
}
2019-11-07 03:53:29 +00:00
if headOp [ 0 ] == '"' {
2018-10-27 03:21:02 +00:00
panic ( "The head operand for function dyntmpl cannot be a string" )
}
2019-11-07 03:53:29 +00:00
pageParam , val3 := c . compileIfVarSub ( con , pageOp )
2018-10-27 03:21:02 +00:00
if ! val3 . IsValid ( ) {
panic ( "val3 is invalid" )
}
2019-11-07 03:53:29 +00:00
headParam , val4 := c . compileIfVarSub ( con , headOp )
2018-10-27 03:21:02 +00:00
if ! val4 . IsValid ( ) {
panic ( "val4 is invalid" )
}
val = val4
// TODO: Refactor this
// TODO: Call the template function directly rather than going through RunThemeTemplate to eliminate a round of indirection?
2018-12-08 00:45:27 +00:00
out = "{\nerr := " + headParam + ".Theme.RunTmpl(" + nameParam + "," + pageParam + ",w)\n"
2018-10-27 03:21:02 +00:00
out += "if err != nil {\nreturn err\n}\n}\n"
2018-07-13 11:27:58 +00:00
literal = true
break ArgLoop
2019-04-27 06:32:26 +00:00
case "flush" :
if c . lang == "js" {
continue
}
2019-11-07 03:53:29 +00:00
out = "if fl, ok := iw.(http.Flusher); ok {\nfl.Flush()\n}\n"
2019-04-27 06:32:26 +00:00
literal = true
c . importMap [ "net/http" ] = "net/http"
break ArgLoop
2017-09-03 04:50:31 +00:00
default :
2018-03-21 05:56:33 +00:00
c . detail ( "Variable!" )
2017-09-03 04:50:31 +00:00
if len ( node . Args ) > ( pos + 1 ) {
nextNode := node . Args [ pos + 1 ] . String ( )
if nextNode == "or" || nextNode == "and" {
continue
2017-06-05 11:57:27 +00:00
}
2017-09-03 04:50:31 +00:00
}
2018-11-18 05:28:27 +00:00
out += c . compileIfVarSubN ( con , id . String ( ) )
2016-12-16 10:37:42 +00:00
}
}
2018-11-18 05:28:27 +00:00
c . retCall ( "compileIdentSwitch" , out , val , literal )
2018-11-28 21:46:53 +00:00
return out , val , literal , notident
2016-12-16 10:37:42 +00:00
}
2018-11-18 05:28:27 +00:00
func ( c * CTemplateSet ) compileReflectSwitch ( con CContext , node * parse . CommandNode ) ( out string , outVal reflect . Value ) {
2018-11-18 05:43:10 +00:00
c . dumpCall ( "compileReflectSwitch" , con , node )
2016-12-16 10:37:42 +00:00
firstWord := node . Args [ 0 ]
switch n := firstWord . ( type ) {
2017-09-03 04:50:31 +00:00
case * parse . FieldNode :
2018-03-08 03:59:47 +00:00
if c . config . SuperDebug {
2019-02-28 07:28:17 +00:00
c . logger . Println ( "Field Node:" , n . Ident )
2017-09-03 04:50:31 +00:00
for _ , id := range n . Ident {
2019-02-28 07:28:17 +00:00
c . logger . Println ( "Field Bit:" , id )
2016-12-16 10:37:42 +00:00
}
2017-09-03 04:50:31 +00:00
}
/* Use reflect to determine if the field is for a method, otherwise assume it's a variable. Coming Soon. */
2018-11-18 05:28:27 +00:00
return c . compileIfVarSub ( con , n . String ( ) )
2017-09-03 04:50:31 +00:00
case * parse . ChainNode :
2018-03-21 05:56:33 +00:00
c . detail ( "Chain Node:" , n . Node )
c . detail ( "node.Args:" , node . Args )
2017-09-03 04:50:31 +00:00
case * parse . DotNode :
2018-11-18 05:28:27 +00:00
return con . VarHolder , con . HoldReflect
2017-09-03 04:50:31 +00:00
case * parse . NilNode :
panic ( "Nil is not a command x.x" )
default :
//panic("I don't know what node this is")
2016-12-16 10:37:42 +00:00
}
2018-11-18 05:43:10 +00:00
return out , outVal
2016-12-16 10:37:42 +00:00
}
2018-11-18 05:28:27 +00:00
func ( c * CTemplateSet ) compileIfVarSubN ( con CContext , varname string ) ( out string ) {
c . dumpCall ( "compileIfVarSubN" , con , varname )
out , _ = c . compileIfVarSub ( con , varname )
2016-12-16 10:37:42 +00:00
return out
}
2018-11-18 05:28:27 +00:00
func ( c * CTemplateSet ) compileIfVarSub ( con CContext , varname string ) ( out string , val reflect . Value ) {
c . dumpCall ( "compileIfVarSub" , con , varname )
cur := con . HoldReflect
2016-12-16 10:37:42 +00:00
if varname [ 0 ] != '.' && varname [ 0 ] != '$' {
return varname , cur
}
2017-06-16 10:41:30 +00:00
2019-10-06 05:32:08 +00:00
stepInterface := func ( ) {
nobreak := ( cur . Type ( ) . Name ( ) == "nobreak" )
2018-12-17 04:58:55 +00:00
c . detailf ( "cur.Type().Name(): %+v\n" , cur . Type ( ) . Name ( ) )
if cur . Kind ( ) == reflect . Interface && ! nobreak {
2018-11-18 05:28:27 +00:00
cur = cur . Elem ( )
out += ".(" + cur . Type ( ) . Name ( ) + ")"
}
}
2018-12-17 04:58:55 +00:00
2017-09-03 04:50:31 +00:00
bits := strings . Split ( varname , "." )
2016-12-16 10:37:42 +00:00
if varname [ 0 ] == '$' {
var res VarItemReflect
if varname [ 1 ] == '.' {
2018-11-18 05:28:27 +00:00
res = c . localVars [ con . TemplateName ] [ "." ]
2016-12-16 10:37:42 +00:00
} else {
2018-11-18 05:28:27 +00:00
res = c . localVars [ con . TemplateName ] [ strings . TrimPrefix ( bits [ 0 ] , "$" ) ]
2016-12-16 10:37:42 +00:00
}
out += res . Destination
cur = res . Value
2017-06-16 10:41:30 +00:00
2016-12-16 10:37:42 +00:00
if cur . Kind ( ) == reflect . Interface {
cur = cur . Elem ( )
}
} else {
2018-11-18 05:28:27 +00:00
out += con . VarHolder
stepInterface ( )
2016-12-16 10:37:42 +00:00
}
2017-09-03 04:50:31 +00:00
bits [ 0 ] = strings . TrimPrefix ( bits [ 0 ] , "$" )
2017-06-16 10:41:30 +00:00
2019-10-06 05:32:08 +00:00
dumpKind := func ( pre string ) {
2018-11-18 05:28:27 +00:00
c . detail ( pre + " Kind:" , cur . Kind ( ) )
c . detail ( pre + " Type:" , cur . Type ( ) . Name ( ) )
}
dumpKind ( "Cur" )
2016-12-16 10:37:42 +00:00
for _ , bit := range bits {
2018-03-21 05:56:33 +00:00
c . detail ( "Variable Field:" , bit )
2016-12-16 10:37:42 +00:00
if bit == "" {
continue
}
2017-06-16 10:41:30 +00:00
2017-09-10 16:57:22 +00:00
// TODO: Fix this up so that it works for regular pointers and not just struct pointers. Ditto for the other cur.Kind() == reflect.Ptr we have in this file
2017-08-06 15:22:18 +00:00
if cur . Kind ( ) == reflect . Ptr {
2018-03-21 05:56:33 +00:00
c . detail ( "Looping over pointer" )
2017-08-06 15:22:18 +00:00
for cur . Kind ( ) == reflect . Ptr {
cur = cur . Elem ( )
}
2018-03-21 05:56:33 +00:00
c . detail ( "Data Kind:" , cur . Kind ( ) . String ( ) )
c . detail ( "Field Bit:" , bit )
2017-08-06 15:22:18 +00:00
}
2016-12-16 10:37:42 +00:00
cur = cur . FieldByName ( bit )
2017-11-08 00:12:50 +00:00
out += "." + bit
2018-12-31 09:03:49 +00:00
if ! cur . IsValid ( ) {
2019-02-28 07:28:17 +00:00
c . logger . Println ( "cur: " , cur )
2018-12-31 09:03:49 +00:00
panic ( out + "^\n" + "Invalid value. Maybe, it doesn't exist?" )
}
2018-11-18 05:28:27 +00:00
stepInterface ( )
2017-06-19 08:06:54 +00:00
if ! cur . IsValid ( ) {
2019-02-28 07:28:17 +00:00
c . logger . Println ( "cur: " , cur )
2017-06-19 08:06:54 +00:00
panic ( out + "^\n" + "Invalid value. Maybe, it doesn't exist?" )
}
2018-11-18 05:28:27 +00:00
dumpKind ( "Data" )
2016-12-16 10:37:42 +00:00
}
2017-06-16 10:41:30 +00:00
2018-03-21 05:56:33 +00:00
c . detail ( "Out Value:" , out )
2018-11-18 05:28:27 +00:00
dumpKind ( "Out" )
2016-12-16 10:37:42 +00:00
for _ , varItem := range c . varList {
if strings . HasPrefix ( out , varItem . Destination ) {
out = strings . Replace ( out , varItem . Destination , varItem . Name , 1 )
}
}
2017-06-16 10:41:30 +00:00
2016-12-17 03:39:53 +00:00
_ , ok := c . stats [ out ]
if ok {
c . stats [ out ] ++
} else {
c . stats [ out ] = 1
}
2017-06-16 10:41:30 +00:00
2018-11-18 05:43:10 +00:00
c . retCall ( "compileIfVarSub" , out , cur )
2016-12-16 10:37:42 +00:00
return out , cur
}
2018-11-18 05:43:10 +00:00
func ( c * CTemplateSet ) compileBoolSub ( con CContext , varname string ) string {
c . dumpCall ( "compileBoolSub" , con , varname )
2018-11-18 05:28:27 +00:00
out , val := c . compileIfVarSub ( con , varname )
Added Quick Topic.
Added Attachments.
Added Attachment Media Embeds.
Renamed a load of *Store and *Cache methods to reduce the amount of unneccesary typing.
Added petabytes as a unit and cleaned up a few of the friendly units.
Refactored the username change logic to make it easier to maintain.
Refactored the avatar change logic to make it easier to maintain.
Shadow now uses CSS Variables for most of it's colours. We have plans to transpile this to support older browsers later on!
Snuck some CSS Variables into Tempra Conflux.
Added the GroupCache interface to MemoryGroupStore.
Added the Length method to MemoryGroupStore.
Added support for a site short name.
Added the UploadFiles permission.
Renamed more functions.
Fixed the background for the left gutter on the postbit for Tempra Simple and Shadow.
Added support for if statements operating on int8, int16, int32, int32, int64, uint, uint8, uint16, uint32, uint64, float32, and float64 for the template compiler.
Added support for if statements operating on slices and maps for the template compiler.
Fixed a security exploit in reply editing.
Fixed a bug in the URL detector in the parser where it couldn't find URLs with non-standard ports.
Fixed buttons having blue outlines on focus on Shadow.
Refactored the topic creation logic to make it easier to maintain.
Made a few responsive fixes, but there's still more to do in the following commits!
2017-10-05 10:20:28 +00:00
// TODO: What if it's a pointer or an interface? I *think* we've got pointers handled somewhere, but not interfaces which we don't know the types of at compile time
2016-12-16 10:37:42 +00:00
switch val . Kind ( ) {
Added Quick Topic.
Added Attachments.
Added Attachment Media Embeds.
Renamed a load of *Store and *Cache methods to reduce the amount of unneccesary typing.
Added petabytes as a unit and cleaned up a few of the friendly units.
Refactored the username change logic to make it easier to maintain.
Refactored the avatar change logic to make it easier to maintain.
Shadow now uses CSS Variables for most of it's colours. We have plans to transpile this to support older browsers later on!
Snuck some CSS Variables into Tempra Conflux.
Added the GroupCache interface to MemoryGroupStore.
Added the Length method to MemoryGroupStore.
Added support for a site short name.
Added the UploadFiles permission.
Renamed more functions.
Fixed the background for the left gutter on the postbit for Tempra Simple and Shadow.
Added support for if statements operating on int8, int16, int32, int32, int64, uint, uint8, uint16, uint32, uint64, float32, and float64 for the template compiler.
Added support for if statements operating on slices and maps for the template compiler.
Fixed a security exploit in reply editing.
Fixed a bug in the URL detector in the parser where it couldn't find URLs with non-standard ports.
Fixed buttons having blue outlines on focus on Shadow.
Refactored the topic creation logic to make it easier to maintain.
Made a few responsive fixes, but there's still more to do in the following commits!
2017-10-05 10:20:28 +00:00
case reflect . Int , reflect . Int8 , reflect . Int16 , reflect . Int32 , reflect . Int64 , reflect . Uint , reflect . Uint8 , reflect . Uint16 , reflect . Uint32 , reflect . Uint64 , reflect . Float32 , reflect . Float64 :
2017-09-03 04:50:31 +00:00
out += " > 0"
case reflect . Bool : // Do nothing
case reflect . String :
out += " != \"\""
Added Quick Topic.
Added Attachments.
Added Attachment Media Embeds.
Renamed a load of *Store and *Cache methods to reduce the amount of unneccesary typing.
Added petabytes as a unit and cleaned up a few of the friendly units.
Refactored the username change logic to make it easier to maintain.
Refactored the avatar change logic to make it easier to maintain.
Shadow now uses CSS Variables for most of it's colours. We have plans to transpile this to support older browsers later on!
Snuck some CSS Variables into Tempra Conflux.
Added the GroupCache interface to MemoryGroupStore.
Added the Length method to MemoryGroupStore.
Added support for a site short name.
Added the UploadFiles permission.
Renamed more functions.
Fixed the background for the left gutter on the postbit for Tempra Simple and Shadow.
Added support for if statements operating on int8, int16, int32, int32, int64, uint, uint8, uint16, uint32, uint64, float32, and float64 for the template compiler.
Added support for if statements operating on slices and maps for the template compiler.
Fixed a security exploit in reply editing.
Fixed a bug in the URL detector in the parser where it couldn't find URLs with non-standard ports.
Fixed buttons having blue outlines on focus on Shadow.
Refactored the topic creation logic to make it easier to maintain.
Made a few responsive fixes, but there's still more to do in the following commits!
2017-10-05 10:20:28 +00:00
case reflect . Slice , reflect . Map :
out = "len(" + out + ") != 0"
2017-09-03 04:50:31 +00:00
default :
2019-02-28 07:28:17 +00:00
c . logger . Println ( "Variable Name:" , varname )
c . logger . Println ( "Variable Holder:" , con . VarHolder )
c . logger . Println ( "Variable Kind:" , con . HoldReflect . Kind ( ) )
2017-09-03 04:50:31 +00:00
panic ( "I don't know what this variable's type is o.o\n" )
2016-12-16 10:37:42 +00:00
}
2018-11-18 05:43:10 +00:00
c . retCall ( "compileBoolSub" , out )
2016-12-16 10:37:42 +00:00
return out
}
2018-11-18 05:28:27 +00:00
// For debugging the template generator
func ( c * CTemplateSet ) debugParam ( param interface { } , depth int ) ( pstr string ) {
switch p := param . ( type ) {
case CContext :
return "con,"
case reflect . Value :
if p . Kind ( ) == reflect . Ptr || p . Kind ( ) == reflect . Interface {
for p . Kind ( ) == reflect . Ptr || p . Kind ( ) == reflect . Interface {
if p . Kind ( ) == reflect . Ptr {
pstr += "*"
} else {
pstr += "£"
}
p = p . Elem ( )
}
}
kind := p . Kind ( ) . String ( )
if kind != "struct" {
pstr += kind
} else {
pstr += p . Type ( ) . Name ( )
}
return pstr + ","
case string :
return "\"" + p + "\","
case int :
return strconv . Itoa ( p ) + ","
case bool :
if p {
return "true,"
}
return "false,"
case func ( string ) string :
if p == nil {
return "nil,"
}
return "func(string) string),"
default :
return "?,"
}
}
func ( c * CTemplateSet ) dumpCall ( name string , params ... interface { } ) {
var pstr string
for _ , param := range params {
pstr += c . debugParam ( param , 0 )
}
if len ( pstr ) > 0 {
pstr = pstr [ : len ( pstr ) - 1 ]
}
c . detail ( "called " + name + "(" + pstr + ")" )
}
func ( c * CTemplateSet ) retCall ( name string , params ... interface { } ) {
var pstr string
for _ , param := range params {
pstr += c . debugParam ( param , 0 )
}
if len ( pstr ) > 0 {
pstr = pstr [ : len ( pstr ) - 1 ]
}
c . detail ( "returned from " + name + " => (" + pstr + ")" )
}
2019-05-13 09:17:44 +00:00
func buildUserExprs ( holder string ) ( [ ] string , [ ] string ) {
2019-10-06 05:32:08 +00:00
userExprs := [ ] string {
2019-04-27 06:32:26 +00:00
holder + ".CurrentUser.Loggedin" ,
holder + ".CurrentUser.IsSuperMod" ,
holder + ".CurrentUser.IsAdmin" ,
}
2019-10-06 05:32:08 +00:00
negUserExprs := [ ] string {
2019-04-27 06:32:26 +00:00
"!" + holder + ".CurrentUser.Loggedin" ,
"!" + holder + ".CurrentUser.IsSuperMod" ,
"!" + holder + ".CurrentUser.IsAdmin" ,
}
return userExprs , negUserExprs
}
2018-11-18 05:28:27 +00:00
func ( c * CTemplateSet ) compileVarSub ( con CContext , varname string , val reflect . Value , assLines string , onEnd func ( string ) string ) {
c . dumpCall ( "compileVarSub" , con , varname , val , assLines , onEnd )
2018-11-19 23:06:15 +00:00
defer c . retCall ( "compileVarSub" )
2018-11-18 05:28:27 +00:00
if onEnd == nil {
onEnd = func ( in string ) string {
return in
}
}
2017-11-29 02:34:02 +00:00
// Is this a literal string?
if len ( varname ) != 0 && varname [ 0 ] == '"' {
2018-12-15 04:39:50 +00:00
con . Push ( "lvarsub" , onEnd ( assLines + "w.Write(StringToBytes(" + varname + "))\n" ) )
2018-11-18 05:28:27 +00:00
return
2017-11-29 02:34:02 +00:00
}
2016-12-16 10:37:42 +00:00
for _ , varItem := range c . varList {
if strings . HasPrefix ( varname , varItem . Destination ) {
varname = strings . Replace ( varname , varItem . Destination , varItem . Name , 1 )
}
}
2017-06-16 10:41:30 +00:00
2016-12-17 03:39:53 +00:00
_ , ok := c . stats [ varname ]
if ok {
c . stats [ varname ] ++
} else {
c . stats [ varname ] = 1
}
2016-12-16 10:37:42 +00:00
if val . Kind ( ) == reflect . Interface {
val = val . Elem ( )
}
2018-11-18 05:28:27 +00:00
if val . Kind ( ) == reflect . Ptr {
for val . Kind ( ) == reflect . Ptr {
val = val . Elem ( )
varname = "*" + varname
}
}
2017-06-16 10:41:30 +00:00
2018-03-21 05:56:33 +00:00
c . detail ( "varname: " , varname )
c . detail ( "assLines: " , assLines )
2018-11-18 05:28:27 +00:00
var base string
2016-12-16 10:37:42 +00:00
switch val . Kind ( ) {
2017-09-03 04:50:31 +00:00
case reflect . Int :
c . importMap [ "strconv" ] = "strconv"
2018-12-15 04:39:50 +00:00
base = "StringToBytes(strconv.Itoa(" + varname + "))"
2017-09-03 04:50:31 +00:00
case reflect . Bool :
2018-12-15 04:39:50 +00:00
// TODO: Take c.memberOnly into account
// TODO: Make this a template fragment so more optimisations can be applied to this
// TODO: De-duplicate this logic
2019-04-27 06:32:26 +00:00
userExprs , negUserExprs := buildUserExprs ( con . RootHolder )
2018-12-15 04:39:50 +00:00
if c . guestOnly {
c . detail ( "optimising away member branch" )
if inSlice ( userExprs , varname ) {
c . detail ( "positive conditional:" , varname )
2018-12-17 04:58:55 +00:00
c . addText ( con , [ ] byte ( "false" ) )
2018-12-15 04:39:50 +00:00
return
} else if inSlice ( negUserExprs , varname ) {
c . detail ( "negative conditional:" , varname )
2018-12-17 04:58:55 +00:00
c . addText ( con , [ ] byte ( "true" ) )
2018-12-15 04:39:50 +00:00
return
}
} else if c . memberOnly {
c . detail ( "optimising away guest branch" )
if ( con . RootHolder + ".CurrentUser.Loggedin" ) == varname {
c . detail ( "positive conditional:" , varname )
2018-12-17 04:58:55 +00:00
c . addText ( con , [ ] byte ( "true" ) )
2018-12-15 04:39:50 +00:00
return
} else if ( "!" + con . RootHolder + ".CurrentUser.Loggedin" ) == varname {
c . detail ( "negative conditional:" , varname )
2018-12-17 04:58:55 +00:00
c . addText ( con , [ ] byte ( "false" ) )
2018-12-15 04:39:50 +00:00
return
}
}
2018-11-19 23:06:15 +00:00
con . Push ( "startif" , "if " + varname + " {\n" )
2018-12-17 04:58:55 +00:00
c . addText ( con , [ ] byte ( "true" ) )
2018-11-19 23:06:15 +00:00
con . Push ( "endif" , "} " )
con . Push ( "startelse" , "else {\n" )
2018-12-17 04:58:55 +00:00
c . addText ( con , [ ] byte ( "false" ) )
2018-11-19 23:06:15 +00:00
con . Push ( "endelse" , "}\n" )
return
2019-03-21 22:59:41 +00:00
case reflect . Slice :
if val . Len ( ) == 0 {
c . critical ( "varname:" , varname )
panic ( "The sample data needs at-least one or more elements for the slices. We're looking into removing this requirement at some point!" )
}
item := val . Index ( 0 )
if item . Type ( ) . Name ( ) != "uint8" { // uint8 == byte, complicated because it's a type alias
panic ( "unable to format " + item . Type ( ) . Name ( ) + " as text" )
}
base = varname
2017-09-03 04:50:31 +00:00
case reflect . String :
if val . Type ( ) . Name ( ) != "string" && ! strings . HasPrefix ( varname , "string(" ) {
2017-11-23 05:37:08 +00:00
varname = "string(" + varname + ")"
2017-09-03 04:50:31 +00:00
}
2018-12-15 04:39:50 +00:00
base = "StringToBytes(" + varname + ")"
2018-11-26 05:08:10 +00:00
// We don't to waste time on this conversion / w.Write call when guests don't have sessions
// TODO: Implement this properly
2018-12-15 04:39:50 +00:00
if c . guestOnly && base == "StringToBytes(" + con . RootHolder + ".CurrentUser.Session))" {
2018-11-26 05:08:10 +00:00
return
}
2019-10-12 22:49:08 +00:00
case reflect . Int8 , reflect . Int16 , reflect . Int32 :
c . importMap [ "strconv" ] = "strconv"
base = "StringToBytes(strconv.FormatInt(int64(" + varname + "), 10))"
2017-09-03 04:50:31 +00:00
case reflect . Int64 :
c . importMap [ "strconv" ] = "strconv"
2018-12-15 04:39:50 +00:00
base = "StringToBytes(strconv.FormatInt(" + varname + ", 10))"
2019-10-12 22:49:08 +00:00
case reflect . Uint , reflect . Uint8 , reflect . Uint16 , reflect . Uint32 :
c . importMap [ "strconv" ] = "strconv"
base = "StringToBytes(strconv.FormatUint(uint64(" + varname + "), 10))"
case reflect . Uint64 :
c . importMap [ "strconv" ] = "strconv"
base = "StringToBytes(strconv.FormatUint(" + varname + ", 10))"
2018-12-14 04:08:53 +00:00
case reflect . Struct :
// TODO: Avoid clashing with other packages which have structs named Time
if val . Type ( ) . Name ( ) == "Time" {
2018-12-15 04:39:50 +00:00
base = "StringToBytes(" + varname + ".String())"
2018-12-14 04:08:53 +00:00
} else {
if ! val . IsValid ( ) {
panic ( assLines + varname + "^\n" + "Invalid value. Maybe, it doesn't exist?" )
}
2019-02-28 07:28:17 +00:00
c . logger . Println ( "Unknown Struct Name:" , varname )
c . logger . Println ( "Unknown Struct:" , val . Type ( ) . Name ( ) )
2018-12-14 04:08:53 +00:00
panic ( "-- I don't know what this variable's type is o.o\n" )
}
2017-09-03 04:50:31 +00:00
default :
if ! val . IsValid ( ) {
2017-11-23 05:37:08 +00:00
panic ( assLines + varname + "^\n" + "Invalid value. Maybe, it doesn't exist?" )
2017-09-03 04:50:31 +00:00
}
2019-02-28 07:28:17 +00:00
c . logger . Println ( "Unknown Variable Name:" , varname )
c . logger . Println ( "Unknown Kind:" , val . Kind ( ) )
c . logger . Println ( "Unknown Type:" , val . Type ( ) . Name ( ) )
2017-11-29 02:34:02 +00:00
panic ( "-- I don't know what this variable's type is o.o\n" )
2016-12-16 10:37:42 +00:00
}
2018-11-18 05:28:27 +00:00
c . detail ( "base: " , base )
2018-11-19 23:06:15 +00:00
if assLines == "" {
con . Push ( "varsub" , base )
} else {
con . Push ( "lvarsub" , onEnd ( assLines + base ) )
}
2016-12-16 10:37:42 +00:00
}
2018-11-18 05:28:27 +00:00
func ( c * CTemplateSet ) compileSubTemplate ( pcon CContext , node * parse . TemplateNode ) {
2018-11-19 23:06:15 +00:00
c . dumpCall ( "compileSubTemplate" , pcon , node )
2019-02-10 05:52:26 +00:00
defer c . retCall ( "compileSubTemplate" )
2018-03-21 05:56:33 +00:00
c . detail ( "Template Node: " , node . Name )
2017-06-16 10:41:30 +00:00
2016-12-16 10:37:42 +00:00
fname := strings . TrimSuffix ( node . Name , filepath . Ext ( node . Name ) )
2019-02-28 07:28:17 +00:00
if c . themeName != "" {
_ , ok := c . perThemeTmpls [ fname ]
if ! ok {
c . detail ( "fname not in c.perThemeTmpls" )
c . detail ( "c.perThemeTmpls" , c . perThemeTmpls )
}
fname += "_" + c . themeName
}
2018-11-26 05:08:10 +00:00
if c . guestOnly {
fname += "_guest"
} else if c . memberOnly {
fname += "_member"
}
2019-10-12 22:49:08 +00:00
_ , ok := c . templateList [ fname ]
if ! ok {
// TODO: Cascade errors back up the tree to the caller?
content , err := c . loadTemplate ( c . fileDir , node . Name )
if err != nil {
c . logger . Fatal ( err )
}
//tree := parse.New(node.Name, c.funcMap)
//treeSet := make(map[string]*parse.Tree)
treeSet , err := parse . Parse ( node . Name , content , "{{" , "}}" , c . funcMap )
if err != nil {
c . logger . Fatal ( err )
}
c . detailf ( "treeSet: %+v\n" , treeSet )
for nname , tree := range treeSet {
if node . Name == nname {
c . templateList [ fname ] = tree
} else {
if ! strings . HasPrefix ( nname , ".html" ) {
c . templateList [ nname ] = tree
} else {
c . templateList [ strings . TrimSuffix ( nname , ".html" ) ] = tree
}
}
}
c . detailf ( "c.templateList: %+v\n" , c . templateList )
}
2018-11-18 05:28:27 +00:00
con := pcon
con . VarHolder = "tmpl_" + fname + "_vars"
con . TemplateName = fname
2016-12-16 10:37:42 +00:00
if node . Pipe != nil {
for _ , cmd := range node . Pipe . Cmds {
2018-12-28 11:13:06 +00:00
switch p := cmd . Args [ 0 ] . ( type ) {
case * parse . FieldNode :
// TODO: Incomplete but it should cover the basics
cur := pcon . HoldReflect
var varBit string
if cur . Kind ( ) == reflect . Interface {
cur = cur . Elem ( )
varBit += ".(" + cur . Type ( ) . Name ( ) + ")"
}
for _ , id := range p . Ident {
c . detail ( "Data Kind:" , cur . Kind ( ) . String ( ) )
c . detail ( "Field Bit:" , id )
cur = c . skipStructPointers ( cur , id )
c . checkIfValid ( cur , pcon . VarHolder , pcon . HoldReflect , varBit , false )
if cur . Kind ( ) != reflect . Interface {
cur = cur . FieldByName ( id )
varBit += "." + id
}
// TODO: Handle deeply nested pointers mixed with interfaces mixed with pointers better
if cur . Kind ( ) == reflect . Interface {
cur = cur . Elem ( )
varBit += ".("
// TODO: Surely, there's a better way of doing this?
if cur . Type ( ) . PkgPath ( ) != "main" && cur . Type ( ) . PkgPath ( ) != "" {
c . importMap [ "html/template" ] = "html/template"
varBit += strings . TrimPrefix ( cur . Type ( ) . PkgPath ( ) , "html/" ) + "."
}
varBit += cur . Type ( ) . Name ( ) + ")"
}
}
con . VarHolder = pcon . VarHolder + varBit
con . HoldReflect = cur
2019-10-12 22:49:08 +00:00
case * parse . StringNode :
//con.VarHolder = pcon.VarHolder
//con.HoldReflect = pcon.HoldReflect
con . VarHolder = p . Quoted
con . HoldReflect = reflect . ValueOf ( p . Quoted )
2017-09-03 04:50:31 +00:00
case * parse . DotNode :
2018-11-18 05:28:27 +00:00
con . VarHolder = pcon . VarHolder
con . HoldReflect = pcon . HoldReflect
2017-09-03 04:50:31 +00:00
case * parse . NilNode :
panic ( "Nil is not a command x.x" )
default :
2018-12-28 11:13:06 +00:00
c . critical ( "Unknown Param Type:" , p )
pvar := reflect . ValueOf ( p )
c . critical ( "param kind:" , pvar . Kind ( ) . String ( ) )
c . critical ( "param type:" , pvar . Type ( ) . Name ( ) )
if pvar . Kind ( ) == reflect . Ptr {
c . critical ( "Looping over pointer" )
for pvar . Kind ( ) == reflect . Ptr {
pvar = pvar . Elem ( )
}
c . critical ( "concrete kind:" , pvar . Kind ( ) . String ( ) )
c . critical ( "concrete type:" , pvar . Type ( ) . Name ( ) )
}
2017-11-29 02:34:02 +00:00
panic ( "" )
2016-12-16 10:37:42 +00:00
}
}
}
2017-06-16 10:41:30 +00:00
2019-10-12 22:49:08 +00:00
//c.templateList[fname] = tree
2018-03-08 03:59:47 +00:00
subtree := c . templateList [ fname ]
2018-03-21 05:56:33 +00:00
c . detail ( "subtree.Root" , subtree . Root )
2016-12-16 10:37:42 +00:00
c . localVars [ fname ] = make ( map [ string ] VarItemReflect )
2018-11-18 05:28:27 +00:00
c . localVars [ fname ] [ "." ] = VarItemReflect { "." , con . VarHolder , con . HoldReflect }
2018-03-12 04:52:47 +00:00
c . fragmentCursor [ fname ] = 0
2018-11-22 07:21:43 +00:00
var startBit , endBit string
if con . LoopDepth != 0 {
startBit = "{\n"
endBit = "}\n"
}
con . StartTemplate ( startBit )
2018-11-18 05:28:27 +00:00
c . rootIterate ( subtree , con )
2018-11-22 07:21:43 +00:00
con . EndTemplate ( endBit )
2019-02-28 07:28:17 +00:00
//c.templateFragmentCount[fname] = c.fragmentCursor[fname] + 1
2019-10-12 22:49:08 +00:00
if _ , ok := c . fragOnce [ fname ] ; ! ok {
2019-02-28 07:28:17 +00:00
c . fragOnce [ fname ] = true
2018-11-19 23:06:15 +00:00
}
2019-02-10 05:52:26 +00:00
// map[string]map[string]bool
c . detail ( "overridenTrack loop" )
c . detail ( "fname:" , fname )
for themeName , track := range c . overridenTrack {
c . detail ( "themeName:" , themeName )
c . detailf ( "track: %+v\n" , track )
croot , ok := c . overridenRoots [ themeName ]
if ! ok {
croot = make ( map [ string ] bool )
c . overridenRoots [ themeName ] = croot
}
c . detailf ( "croot: %+v\n" , croot )
for tmplName , _ := range track {
cname := tmplName
if c . guestOnly {
cname += "_guest"
} else if c . memberOnly {
cname += "_member"
}
c . detail ( "cname:" , cname )
if fname == cname {
c . detail ( "match" )
croot [ strings . TrimSuffix ( strings . TrimSuffix ( con . RootTemplateName , "_guest" ) , "_member" ) ] = true
} else {
c . detail ( "no match" )
}
}
}
c . detailf ( "c.overridenRoots: %+v\n" , c . overridenRoots )
2016-12-16 10:37:42 +00:00
}
2018-11-26 05:08:10 +00:00
func ( c * CTemplateSet ) loadTemplate ( fileDir string , name string ) ( content string , err error ) {
2019-02-28 07:28:17 +00:00
c . dumpCall ( "loadTemplate" , fileDir , name )
c . detail ( "c.themeName: " , c . themeName )
2019-02-10 05:52:26 +00:00
if c . themeName != "" {
2019-10-12 22:49:08 +00:00
t := "./themes/" + c . themeName + "/overrides/" + name
c . detail ( "per-theme override: " , true )
res , err := ioutil . ReadFile ( t )
2019-02-10 05:52:26 +00:00
if err == nil {
content = string ( res )
if c . config . Minify {
2019-02-28 07:28:17 +00:00
content = Minify ( content )
2019-02-10 05:52:26 +00:00
}
return content , nil
}
c . detail ( "override err: " , err )
}
2018-11-26 05:08:10 +00:00
res , err := ioutil . ReadFile ( c . fileDir + "overrides/" + name )
if err != nil {
c . detail ( "override path: " , c . fileDir + "overrides/" + name )
c . detail ( "override err: " , err )
res , err = ioutil . ReadFile ( c . fileDir + name )
if err != nil {
return "" , err
}
}
content = string ( res )
if c . config . Minify {
2019-02-28 07:28:17 +00:00
content = Minify ( content )
2018-11-26 05:08:10 +00:00
}
return content , nil
}
2018-11-22 07:21:43 +00:00
func ( c * CTemplateSet ) afterTemplate ( con CContext , startIndex int ) {
c . dumpCall ( "afterTemplate" , con , startIndex )
defer c . retCall ( "afterTemplate" )
2019-10-12 22:49:08 +00:00
loopDepth := 0
2018-11-22 07:21:43 +00:00
var outBuf = * con . OutBuf
2019-10-12 22:49:08 +00:00
varcounts := make ( map [ string ] int )
loopStart := startIndex
2018-11-22 07:21:43 +00:00
if outBuf [ startIndex ] . Type == "startloop" && ( len ( outBuf ) > startIndex + 1 ) {
loopStart ++
}
// Exclude varsubs within loops for now
for i := loopStart ; i < len ( outBuf ) ; i ++ {
item := outBuf [ i ]
c . detail ( "item:" , item )
if item . Type == "startloop" {
loopDepth ++
c . detail ( "loopDepth:" , loopDepth )
} else if item . Type == "endloop" {
loopDepth --
c . detail ( "loopDepth:" , loopDepth )
if loopDepth == - 1 {
break
}
} else if item . Type == "varsub" && loopDepth == 0 {
count := varcounts [ item . Body ]
varcounts [ item . Body ] = count + 1
c . detail ( "count " + strconv . Itoa ( count ) + " for " + item . Body )
c . detail ( "loopDepth:" , loopDepth )
}
}
var varstr string
var i int
2019-10-12 22:49:08 +00:00
varmap := make ( map [ string ] int )
2018-11-22 07:21:43 +00:00
for name , count := range varcounts {
if count > 1 {
varstr += "var cached_var_" + strconv . Itoa ( i ) + " = " + name + "\n"
varmap [ name ] = i
i ++
}
}
// Exclude varsubs within loops for now
loopDepth = 0
for i := loopStart ; i < len ( outBuf ) ; i ++ {
item := outBuf [ i ]
if item . Type == "startloop" {
loopDepth ++
} else if item . Type == "endloop" {
loopDepth --
if loopDepth == - 1 {
break
}
} else if item . Type == "varsub" && loopDepth == 0 {
index , ok := varmap [ item . Body ]
if ok {
item . Body = "cached_var_" + strconv . Itoa ( index )
item . Type = "cvarsub"
outBuf [ i ] = item
}
}
}
con . AttachVars ( varstr , startIndex )
}
2018-03-08 03:59:47 +00:00
// TODO: Should we rethink the way the log methods work or their names?
2018-03-21 05:56:33 +00:00
func ( c * CTemplateSet ) detail ( args ... interface { } ) {
2018-03-08 03:59:47 +00:00
if c . config . SuperDebug {
2019-02-28 07:28:17 +00:00
c . logger . Println ( args ... )
2017-11-08 00:12:50 +00:00
}
}
2018-03-21 05:56:33 +00:00
func ( c * CTemplateSet ) detailf ( left string , args ... interface { } ) {
2018-03-08 03:59:47 +00:00
if c . config . SuperDebug {
2019-02-28 07:28:17 +00:00
c . logger . Printf ( left , args ... )
2017-11-29 02:34:02 +00:00
}
}
2017-11-23 05:37:08 +00:00
func ( c * CTemplateSet ) error ( args ... interface { } ) {
2018-03-08 03:59:47 +00:00
if c . config . Debug {
2019-02-28 07:28:17 +00:00
c . logger . Println ( args ... )
2017-11-23 05:37:08 +00:00
}
}
2018-12-28 11:13:06 +00:00
func ( c * CTemplateSet ) critical ( args ... interface { } ) {
2019-02-28 07:28:17 +00:00
c . logger . Println ( args ... )
2019-05-13 09:17:44 +00:00
}