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)的更多相关文章

  1. Memcached source code analysis (threading model)--reference

    Look under the start memcahced threading process memcached multi-threaded mainly by instantiating mu ...

  2. 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 ...

  3. Apache Commons Pool2 源码分析 | Apache Commons Pool2 Source Code Analysis

    Apache Commons Pool实现了对象池的功能.定义了对象的生成.销毁.激活.钝化等操作及其状态转换,并提供几个默认的对象池实现.在讲述其实现原理前,先提一下其中有几个重要的对象: Pool ...

  4. Redis source code analysis

    http://zhangtielei.com/posts/blog-redis-dict.html http://zhangtielei.com/assets/photos_redis/redis_d ...

  5. linux kernel & source code analysis& hacking

    https://kernelnewbies.org/ http://www.tldp.org/LDP/lki/index.html https://kernelnewbies.org/ML https ...

  6. 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 ...

  7. 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- ...

  8. Top 40 Static Code Analysis Tools

    https://www.softwaretestinghelp.com/tools/top-40-static-code-analysis-tools/ In this article, I have ...

  9. 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 ...

随机推荐

  1. MVC系列学习(十)-生成URL与表单

    本次学习,在路由配置信息中,有两个路由规则,在网站第一次启动的时候,注册了两个路由表 1.动态生成url A.在路由规则中,因为Default在前面,所以最新找到该路由表,此时不管 自己定义的控制器名 ...

  2. 简述UIDatePicker的用法

    1.Locale 设置DatePicker的地区,即设置DatePicker显示的语言. 1.跟踪所有可用的地区,取出想要的地区 NSLog(@"%@", [NSLocale av ...

  3. CF830A/831D Office Keys

    思路: 问题的关键在于对钥匙按照位置排序之后,最终选择的n个钥匙一定是其中的一个连续的区间. 实现: #include <iostream> #include <cstdio> ...

  4. 一、CSS的基础样式

    CSS的基础样式 border 边框 复合写法 border:border-width  border-style border-color: border-width:边框宽度 top right ...

  5. Canvas清空

    当canvs与bitmap绑定时,canvas上绘制会导致bitmap改变内容,而且内容时叠加的.这时候需要清空bitmap上的内容,可以用以下做法. Paint paint = new Paint( ...

  6. Ajax——jq中ajax的使用

    格式化表单 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...

  7. 注释及Scriptlet

    1.显式注释 <!--xxxxxx-->,在正常页面上也看不出来,右键鼠标查看源代码可以看到 2.隐式注释 //xxxxx /*xxxxxx*/ <%--xxxxxxx--> ...

  8. 解决hash冲突的三个方法-考虑获取

    哈希表值的获取要考虑全部可能空间. 在链地址法中,可能空间就是具有相同hash值的链表.   目录 开放定址法 线性探测再散列 二次探测再散列 伪随机探测再散列 再哈希法 链地址法 建立公共溢出区 优 ...

  9. Springboot使用JdbcTemplate RowMapper查询,直接返回实体列表

    ManagerRowMapper.java public class ManagerRowMapper implements RowMapper<Manager>{ @Override p ...

  10. IDEA 基本配置

    idea使用基本配置 1配置JDK开发环境 File->project structure: 2取消自动更新 file->setting:Appearance &Behavior下 ...