程序员要如何创建一门编程语言?( 二 )
keyword:printstring
因此 , 我们来创建一个parse方法 , 循环遍历codes并提取标记 , 看看是否形成了有效的语法 , 并根据需要采用采取必要的行动 。
classMagenta{constructor(codes){this.codes=codes}tokenize(){/*previouscodesfortokenizer*/}parse(tokens){constlen=tokens.lengthletpos=0while(pos<len){consttoken=tokens[pos]//iftokenisaprintkeywordif(token.type==="keyword"&&token.valuehttps://pcff.toutiao.jxnews.com.cn/p/20220530/==="print"){//ifthenexttokendoesn'texistif(!tokens[pos+1]){returnconsole.log("Unexpectedendofline,expectedstring")}//checkifthenexttokenisastringletisString=tokens[pos+1].type==="string"//ifthenexttokenisnotastringif(!isString){returnconsole.log(`Unexpectedtoken${tokens[pos+1].type},expectedstring`)}//ifwereachthispoint,wehavevalidsyntax//sowecanprintthestringconsole.log('x1b[35m%sx1b[0m',tokens[pos+1].value)//weadd2becausewealsocheckthetokenafterprintkeywordpos+=2}else{//ifwedidn'tmatchanyrulesreturnconsole.log(`Unexpectedtoken${token.type}`)}}}run(){const{tokens,error}=this.tokenize()if(error){console.log(error)return}this.parse(tokens)}}如下所示 , 我们的编程语言已经能够正常工作了!

文章图片
由于字符串变量codes是硬编码的 , 因此输出其中包含的字符串意义也不大 。 因此 , 我们将codes放入一个名为code.m的文件中 。 这样 , 变量codes(输出数据)与编译器的实现逻辑就互相分离了 。 我们使用.m作为文件扩展名 , 以此来表明该文件包含Magenta语言的代码 。
下面 , 我们来修改代码 , 从该文件中读取codes:
//importingfilesystemmoduleconstfs=require('fs')//importingpathmoduleforconvenientpathjoiningconstpath=require('path')classMagenta{constructor(codes){this.codes=codes}tokenize(){/*previouscodesfortokenizer*/}parse(tokens){/*previouscodesforparsemethod*/}run(){/*previouscodesforrunmethod*/}}//Readingcode.mfile//Sometexteditorsusernfornewlineinsteadofn,soweareremovingrconstcodes=fs.readFileSync(path.join(__dirname,'code.m'),'utf8').toString().replace(/r/g,"")constmagenta=newMagenta(codes)magenta.run()创建一门编程语言
到这里 , 我们就成功地从零开始创建了一种微型编程语言 。 其实 , 编程语言也可以非常简单 。 当然 , 像Magenta这样的语言不太可能用于实践 , 也不足以成为流行框架 , 但我们可以通过这个例子学习如何创建一门编程语言 。
【程序员要如何创建一门编程语言?】原文地址:https://css-tricks.com/lets-create-a-tiny-programming-language/
- iqoo|卡贴机大降价,iPhone13只要3000出头,网友都说“真香”
- 显卡|这就是RTX 4090 Ti显卡?又厚又重,超过三槽要1200W电源
- 土耳其发现四肢爬行人群,这是咋回事?科学家警告:人类要留心了
- 苹果要大涨价!iPhone 14量产工作就绪:四款齐发 供应商已出货
- ios16|一步到位能用5年,目前这3款手机能闭眼入,买手机不要太小气
- 创投圈|抖音小店无货源适合新手小白么?如何精细化运营?新手小白看来
- 土星环比恐龙还要年轻?这些宇宙冷知识很少有人知道
- 和真的几乎一样,这个仿生蜻蜓,要实现《沙丘》里的扑翼机了
- 宇宙中有多少维度,人类为何想要进入四维空间?科学家给出了解释
- 苹果|苹果要大涨价!iPhone 14量产工作就绪:四款齐发 供应商已出货
