Golang Template source code analysis(Parse)
This blog was written at go 1.3.1 version.
We know that we use template thought by followed way:
func main() {
name := "waynehu"
tmpl := template.New("test")
tmpl, err := tmpl.Parse("hello {{.}}") if err != nil {
panic(err)
} err = tmpl.Execute(os.Stdout, name)
if err != nil {
panic(err)
}
}
It mainly has three steps,the first is allow template,the second is tmpl.Parse,the third is tmpl.Execute(os.Stdout, name),the first step is simple.This blog introduces the second step.
- Major Class
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveXAxMjB5cA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
The ListNode struct:
// ListNode holds a sequence of nodes.
type ListNode struct {
NodeType
Pos
Nodes []Node // The element nodes in lexical order.
}
The "NodeType" and "Pos" is as same as int.
- Sequence Diagram
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveXAxMjB5cA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
- The key of parts of code
// lex creates a new scanner for the input string.
func lex(name, input, left, right string) *lexer {
if left == "" {
left = leftDelim
}
if right == "" {
right = rightDelim
}
l := &lexer{
name: name,
input: input,
leftDelim: left,
rightDelim: right,
items: make(chan item),
}
go l.run()
return l
}
// run runs the state machine for the lexer.
func (l *lexer) run() {
for l.state = lexText; l.state != nil; {
l.state = l.state(l)
}
}
l.emit(itemText) is handle static text information and lexLeftDelim is handle dynamic information.
// lexText scans until an opening action delimiter, "{{".
func lexText(l *lexer) stateFn {
for {
if strings.HasPrefix(l.input[l.pos:], l.leftDelim) {
if l.pos > l.start {
l.emit(itemText)
}
return lexLeftDelim
}
if l.next() == eof {
break
}
}
// Correctly reached EOF.
if l.pos > l.start {
l.emit(itemText)
}
l.emit(itemEOF)
return nil
}
lexComment is hande comment without analysis
// lexLeftDelim scans the left delimiter, which is known to be present.
func lexLeftDelim(l *lexer) stateFn {
l.pos += Pos(len(l.leftDelim))
if strings.HasPrefix(l.input[l.pos:], leftComment) {
return lexComment
}
l.emit(itemLeftDelim)
l.parenDepth = 0
return lexInsideAction
}
any syntax parsing are transmited by "chan item" is a channel.and take away it thought func (l *lexer) nextItem() item function.
put value in emit function.
// emit passes an item back to the client.
func (l *lexer) emit(t itemType) {
l.items <- item{t, l.start, l.input[l.start:l.pos]}
l.start = l.pos
}
followed function produce t.Root list thought nextNonSpace bring value to
// parse is the top-level parser for a template, essentially the same
// as itemList except it also parses {{define}} actions.
// It runs to EOF.
func (t *Tree) parse(treeSet map[string]*Tree) (next Node) {
t.Root = newList(t.peek().pos)
for t.peek().typ != itemEOF {
if t.peek().typ == itemLeftDelim {
delim := t.next()
if t.nextNonSpace().typ == itemDefine {
newT := New("definition") // name will be updated once we know it.
newT.text = t.text
newT.ParseName = t.ParseName
newT.startParse(t.funcs, t.lex)
newT.parseDefinition(treeSet)
continue
}
t.backup2(delim)
}
n := t.textOrAction()
if n.Type() == nodeEnd {
t.errorf("unexpected %s", n)
}
t.Root.append(n)
}
return nil
}
// nextNonSpace returns the next non-space token.
func (t *Tree) nextNonSpace() (token item) {
for {
token = t.next()
if token.typ != itemSpace {
break
}
}
return token
}
take away item in nextItem function
// nextItem returns the next item from the input.
func (l *lexer) nextItem() item {
item := <-l.items
l.lastPos = item.pos
return item
}
To be continued
Golang Template source code analysis(Parse)的更多相关文章
- Memcached source code analysis (threading model)--reference
Look under the start memcahced threading process memcached multi-threaded mainly by instantiating mu ...
- Memcached source code analysis -- Analysis of change of state--reference
This article mainly introduces the process of Memcached, libevent structure of the main thread and w ...
- Apache Commons Pool2 源码分析 | Apache Commons Pool2 Source Code Analysis
Apache Commons Pool实现了对象池的功能.定义了对象的生成.销毁.激活.钝化等操作及其状态转换,并提供几个默认的对象池实现.在讲述其实现原理前,先提一下其中有几个重要的对象: Pool ...
- Redis source code analysis
http://zhangtielei.com/posts/blog-redis-dict.html http://zhangtielei.com/assets/photos_redis/redis_d ...
- linux kernel & source code analysis& hacking
https://kernelnewbies.org/ http://www.tldp.org/LDP/lki/index.html https://kernelnewbies.org/ML https ...
- 2018.6.21 HOLTEK HT49R70A-1 Source Code analysis
Cange note: “Reading TMR1H will latch the contents of TMR1H and TMR1L counter to the destination”? F ...
- The Ultimate List of Open Source Static Code Analysis Security Tools
https://www.checkmarx.com/2014/11/13/the-ultimate-list-of-open-source-static-code-analysis-security- ...
- Top 40 Static Code Analysis Tools
https://www.softwaretestinghelp.com/tools/top-40-static-code-analysis-tools/ In this article, I have ...
- Source Code Reading for Vue 3: How does `hasChanged` work?
Hey, guys! The next generation of Vue has released already. There are not only the brand new composi ...
随机推荐
- java基础之吃货联盟
因为用的是普通数组,所以编写的代码可能比较长,而且有的功能还比较不健全,代码如下: 0.定义数组(因为用static修饰可以不用New,比较方便,但可能比较损耗性能) //订餐人名字 static S ...
- java中的结构--switch选择结构
if-switch 选择结构 switch结构可以更好的解决等值判断问题switch 选择结构的语法:switch (表达式){ case 常量 1: //代码块1: break; case 常量 2 ...
- [ Luogu Contest 10364 ] TG
\(\\\) \(\#A\) 小凯的数字 给出两个整数\(L,R\),从\(L\)到\(R\)按顺序写下来,求生成整数对\(9\)取模后的答案. 例如\(L=8,R=12\),生成的数字是\(8910 ...
- jsp之认识 servlet (基础、工作原理、容器请求处理)
Tomcat 的安装: eclipse 需要自行安装tomcat,这是web 项目运行的服务器.如果用的是MyEclipse,里面自带tomcat,方便清除部署垃圾,利于项目运行. Tomcat的安装 ...
- css图片特效
网站图片往往有很多显示效果,使用css是实现图片特效的比较简便的方式.下面记录一段css鼠标指向的多重特效: <!DOCTYPE html><html lang="en&q ...
- sql server 大数据跨服务器迁移表数据——使用链接服务器
1.创建链接服务器(填写链接服务器.远程登录.使用密码) 2.188.188.1.177是远程的 select count(*) from [188.188.1.177].BigDataAnalysi ...
- jQuery——jQuery选择器
基本选择器 # Id选择器 $(“#btnShow”)选择id为btnShow的一个元素 . 类选择器 $(“.liItem”)选择含有类liItem的所有元素 ele 标签选择器 $(“li”)选择 ...
- SQL server 2005中无法新建作用(Job)的问题
1.在使用sqlserver2005创建作业时,创建不了,提示 无法将类型为“Microsoft.SqlServer.Management.Smo.SimpleObjectKey”的对象强制转换为类型 ...
- iOS UIWebView 访问https绕过证书验证的方法
@implementation NSURLRequest (NSURLRequestWithIgnoreSSL) + (BOOL)allowsAnyHTTPSCertificateForHost:(N ...
- lldb e、@weakify(self) 网络请求400错误
lldb的问题属于调试器: 下面命令用于在调试时设值 e self.apiModel.apiParams = [NSDictionary dictionaryWithObjectsAndKeys:@& ...