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

    Microsoft SQL Server 2012 Internals 把 SQL 语句的处理分为四个阶段,分别是 解析.绑定.优化.执行,如图所示:     解析(Parse)主要是语法分析,比较简 ...

  2. V-SQL的简单使用

    V-SQL概述: V-SQL,是对同望V3平台时间多数据支持非常重要的基础引擎.因为各个数据库的查询语句的语法有所不同,V-SQL的功能是把查询语句解析为执行系统连接的数据库(MSSQL,Oracle ...

  3. Android_撕衣服小案例

    一直都觉得做安卓开发挺有意思,最近一段时间都在学习这方面的知识以及练习敲代码这次要说的是一个简单有趣的案例,相信大家也是看了标题才进来的吧,是不是有点迫不及待的想看看效果图,嘿嘿,算了还是直接给上源码 ...

  4. C#——工厂模式

    之前我们接介绍了简单工厂,这次我们介绍一种更为常用的模式——工厂模式. 工厂方法模式Factory Method,又称多态性工厂模式.在工厂方法模式中,核心的工厂类不再负责所有的产品的创建,而是将具体 ...

  5. PHP 之simple_html_dom实现网页数据采集

    <?php set_time_limit(0); include './simple_html_dom.php'; $url = 'https://price.pcauto.com.cn/pri ...

  6. 如何将本地项目上传到gitlab上?

    git push后需要输入用户名,密码 这是上传成功显示的页面 打开gitLab项目地址检查代码是否被正确上传 上传前: 上传后 这就完成将项目上传到gitlab了

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

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

  8. Origin C调用GSL

    GSL (GNU Scientific Library, http://www.gnu.org/software/gsl/)是C.C++的数值算法库,提供了范围宽广的数学程序,包括随机数字生成器.数理 ...

  9. Android获取SD卡路径/内存的几种方法

    Android获取SD卡路径 本篇将会带领大家学习如何获取android路径的几种常见用法,但在我开始bb之前需要大家清楚android中内存和外存之间的区别,下面进行简短介绍:android中的内存 ...

  10. 棋盘DP三连——洛谷 P1004 方格取数 &&洛谷 P1006 传纸条 &&Codevs 2853 方格游戏

    P1004 方格取数 题目描述 设有N $\times N$N×N的方格图(N $\le 9$)(N≤9),我们将其中的某些方格中填入正整数,而其他的方格中则放入数字00.如下图所示(见样例): A ...