《crafting interpreters》阅读笔记:4.6.1
《crafting interpreters》阅读第 26 天,4.6.1 总结。
一、内容
章:04.Scanning,节:4.6.1 String literals
内容:词法分析之处理字符串。
二、开发总结
1.处理字符串
- 字符串的形式
1."lox";
2.左双引号和右双引号是一样的;
3.支持跨行。
- 处理逻辑
遇到双引号开始遍历,直到遇到下一个双引号。如果遇到换行符,line + 1。STRING是一种 Token。异常处理:缺失右双引号。
- 测试用例
// 普通字符串
"lox"
// 字符串包含空格
"hello lox"
// 字符串跨行
"hello
lox"
// 普通字符串
"line 13"
// 异常字符串:没有右双引号
"123
2.源代码点评
private void string() {
while (peek() != '"' && !isAtEnd()) {
if (peek() == '\n') {
line++;
}
advance();
}
if (isAtEnd()) {
Lox.error(line, "Unterminated string.");
return;
}
// The closing ".
advance();
// Trim the surrounding quotes.
String value = source.substring(start + 1, current - 1);
addToken(STRING, value);
}
书上把这段代码封装到函数里面,我没有封装,因为习惯于用到两次以上再封装。
自己写的时候没有用到 source.substring(start + 1, current - 1),因为之前不理解 start 的作用,采用了叠加,书上这里写的比我好。
3.Java vs Python
无。
4.Python 代码实现
https://github.com/codists/pylox
三、Python 技术总结
1.retun 语句
return_stmt: "return" [expression_list]
四、其它
4.6.1 String literals 在技术实现上不复杂,只用到控制流语句(while, if, return),难在业务梳理与分析,如:是否支持换行?如果支持换行,那么 Token 的 line 属性应该记录首行还是末行?有哪些异常情况?.....看代码能看懂,但是自己亲自实现的时候还是挺耗费时间的。
4.6.1小节的学习,自己还是有些纠结,例如: Token 的 line 属性应该记录首行还是末行其实不那么重要,没必要纠结,先整完。这样很容易导致阅读被拖延。工作中有其它人监督,当没人监督的时候很容易就犯老毛病了,得反复的训练纠正。
五、参考资料
1. 编程
(1) 豆瓣,Robert Nystrom,《Crafting Interpreters》:https://book.douban.com/subject/35548379/
(2)Github,craftinginterpreters: https://github.com/munificent/craftinginterpreters
(3)Github,Python 实现:https://github.com/munificent/craftinginterpreters/wiki/Lox-implementations#python
2. 英语
(1) Etymology Dictionary:https://www.etymonline.com
(2) Cambridge Dictionary:https://dictionary.cambridge.org

欢迎搜索及关注:编程人(a_codists)
浙公网安备 33010602011771号