編譯原理—詞法分析器(Java)

1.當運行程序時,程序會讀取項目下的program.txt文件
2. 程序將會逐行讀取program.txt中的源程序,進行詞法分析,并將分析的結果輸出。
3. 如果發現錯誤,程序將會中止讀取文件進行分析,并輸出錯誤提示

所用單詞的構詞規則

(1) 關鍵字:begin end while do if then
(2) 運算符和界符::= + - * / < <= > >= == != ; ( ) #
(3) 標識符(ID)和常數(NUM) ID=letter(letter | digit)
NUM=digit digit
**

測試樣例

begin
i:=5+i*(i/3-i);
i:=i+i;
end
#

在這里插入圖片描述

詞法分析

public class analyzer {final static String ID = "\\p{Alpha}(\\p{Alpha}|\\d)*";/** 整形常數 NUM >> 正則表達式*/final static String NUM = "\\d\\d*";/** token 詞法單元* <詞符號, 種別碼> *//** 關鍵字 token*/static Map<String, Integer> TOKEN_KEYWORDS;/** 運算符/界符 token */static Map<String, Integer> TOKEN_OPERATOR_BOUNDARY;/** 其他單詞 token*/static Map<String, Integer> TOKEN_ID_SUM;/** 文件根目錄*/static final String ROOT_DIRECTORY = "program.txt";/*** 初始化 token 單元*/private static void initToken(){//種別碼創建TOKEN_KEYWORDS = new HashMap<String, Integer>(){//關鍵字{put("begin", 1);put("if", 2);put("then", 3);put("while", 4);put("do", 5);put("end", 6);}};TOKEN_OPERATOR_BOUNDARY= new HashMap<String, Integer>(){//運算符和界符{put("+", 13);put("-", 14);put("*", 15);put("/", 16);put(":", 17);put(":=", 18);put("<", 20);put("<>", 21);put("<=", 22);put(">", 23);put(">=", 24);put("=", 25);put(";", 26);put("(", 27);put(")", 28);put("#", 0);}};TOKEN_ID_SUM= new HashMap<String, Integer>(){//標識符和整型常數{put(ID, 10);put(NUM, 11);}};}/*** 讀 源程序 文件*/public static void ReadFile1() {FileInputStream fis = null;InputStreamReader isr = null;BufferedReader br = null;try {fis = new FileInputStream(ROOT_DIRECTORY);isr = new InputStreamReader(fis, "UTF-8"); // 轉化類br = new BufferedReader(isr); // 裝飾類String line;/** 記錄 程序 行數 */int countLine = 1;while ((line = br.readLine()) != null) {  // 每次讀取一行,分析一行boolean answer = lexicalAnalysis(line);if(answer == false){System.out.printf("ERROR 編譯錯誤=== 第 %d 行出現 詞法錯誤 \n", countLine);break;}countLine++;}System.out.printf("===編譯完成===");} catch (Exception ex) {ex.printStackTrace();} finally {try {br.close(); // 關閉最后一個類,會將所有的底層流都關閉} catch (Exception ex) {ex.printStackTrace();}}}/** 判斷key是否是其他單詞*/private static boolean isIDOrSUM(String key){if (key.matches(ID) ) {System.out.printf("(%d, %s)\n", TOKEN_ID_SUM.get(ID), key);}else if (key.matches(NUM)) {System.out.printf("(%d, %s)\n", TOKEN_ID_SUM.get(NUM), key);}else {return false;}return true;}/*** 進行 詞法分析* @param word 要分析的字符串* @return 結果*/public static boolean  lexicalAnalysis(String word){word = word.trim(); // 去首尾空格String[] strings = word.split("\\p{Space}+"); // 分割字符串,保證處理的字符串沒有空格for (String string : strings) {/** 3種情況:*      1. 關鍵字 == end (關鍵字的后面一定是空格 )*      2. 運算符/ 分界符 == continue*      3. 其他單詞 == continue*/String key = "";for (int i = 0; i < string.length(); i++){String indexChar = String.valueOf(string.charAt(i)) ;if(i+1<string.length()){if((indexChar+string.charAt(i+1)).equals("//"))return true;}/** 是 運算符 或者 關鍵字*/if (TOKEN_OPERATOR_BOUNDARY.containsKey(indexChar) ||TOKEN_KEYWORDS.containsKey(string.substring(i, string.length()))){if (key.length() > 0) {if (isIDOrSUM(key) == false) {/** 詞法錯誤 */return false;}key = "";}if(TOKEN_OPERATOR_BOUNDARY.containsKey(indexChar)) {/**  1. 是 運算符/分界符 */key += indexChar;if(i + 1 < string.length() && TOKEN_OPERATOR_BOUNDARY.containsKey(indexChar + string.charAt(i+1))){ // 運算分界符key += string.charAt(++i);}System.out.printf("(%d, %s)\n",TOKEN_OPERATOR_BOUNDARY.get(key),key);key = "";}else if(TOKEN_KEYWORDS.containsKey(key = string.substring(i, string.length()))) {/** 2. 是關鍵字*/System.out.printf("(%d, %s)\n",TOKEN_KEYWORDS.get(key),key);key = "";break;}}else {/** 是其他單詞*/key += indexChar;/** 其他單詞后面是 1. 換行,2. 運算符/界符 3. 其他單詞*/if(i+1 >= string.length()){if (isIDOrSUM(key) == false) {/** 詞法錯誤 */return false;}}}}}return true;}public static void main(String[] args) {initToken();System.out.println("==詞法分析程序==");System.out.println("從文件中讀取程序");System.out.println("==============");ReadFile1();System.out.println();}}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/392145.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/392145.shtml
英文地址,請注明出處:http://en.pswp.cn/news/392145.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【BZOJ4653】[Noi2016]區間 雙指針法+線段樹

【BZOJ4653】[Noi2016]區間 Description 在數軸上有 n個閉區間 [l1,r1],[l2,r2],...,[ln,rn]。現在要從中選出 m 個區間&#xff0c;使得這 m個區間共同包含至少一個位置。換句話說&#xff0c;就是使得存在一個 x&#xff0c;使得對于每一個被選中的區間 [li,ri]&#xff0c;都…

為什么我們需要使用Pandas新字符串Dtype代替文本數據對象

We have to represent every bit of data in numerical values to be processed and analyzed by machine learning and deep learning models. However, strings do not usually come in a nice and clean format and require a lot preprocessing.我們必須以數值表示數據的每…

遞歸方程組解的漸進階的求法——代入法

遞歸方程組解的漸進階的求法——代入法 用這個辦法既可估計上界也可估計下界。如前面所指出&#xff0c;方法的關鍵步驟在于預先對解答作出推測&#xff0c;然后用數學歸納法證明推測的正確性。 例如&#xff0c;我們要估計T(n)的上界&#xff0c;T(n)滿足遞歸方程&#xff1a;…

【轉載】C# 理解泛型

術語表 generics&#xff1a;泛型type-safe&#xff1a;類型安全collection: 集合compiler&#xff1a;編譯器run time&#xff1a;程序運行時object: 對象.NET library&#xff1a;.Net類庫value type: 值類型box: 裝箱unbox: 拆箱implicity: 隱式explicity: 顯式linked list:…

javascript 作用_JavaScript承諾如何從內到外真正發揮作用

javascript 作用One of the most important questions I faced in interviews was how promises are implemented. Since async/await is becoming more popular, you need to understand promises.我在采訪中面臨的最重要的問題之一是如何實現承諾。 由于異步/等待變得越來越流…

linux 文件理解,對linux中文件系統的理解

首先在linux系統當中一個可被掛在的數據為一個文件系統1.在安裝linux過程中我們要進行磁盤分區&#xff0c;可以分根目錄/,‘/home‘&#xff0c;‘/boot’,swap等等這些分區&#xff0c;每一個分區(’/(根目錄)‘&#xff0c;’/home‘...)就是一個文件系統。2.文件系統分配完…

編譯原理—語法分析器(Java)

遞歸下降語法分析 1. 語法成分說明 <語句塊> :: begin<語句串> end <語句串> :: <語句>{&#xff1b;<語句>} <語句> :: <賦值語句> | <循環語句> | <條件語句> <關系運算符> :: < | < | > | > | |…

老筆記整理四:字符串的完美度

今天在寵果網上發現一道題目&#xff0c;求一個字符串的完美度http://hero.pongo.cn/home/index覺得這道題很有趣就挑戰了一下&#xff0c;結果沒有在規定的1小時里面寫完&#xff08;笑&#xff09;&#xff0c;多花了10分鐘終于做出來了。題目是這樣的&#xff1a;我們要給每…

nlp構建_使用NLP構建自殺性推文分類器

nlp構建Over the years, suicide has been one of the major causes of death worldwide, According to Wikipedia, Suicide resulted in 828,000 global deaths in 2015, an increase from 712,000 deaths in 1990. This makes suicide the 10th leading cause of death world…

域名跳轉

案例&#xff1a;當訪問lsx.com網站&#xff0c;是我最早論壇的域名。回車之后會自動跳轉到lshx.com。 為什么藥lsx跳轉到lshx.com呢&#xff1f; 為了統一品牌。建議換成了lshx.com。所有之前的lsx.com就不要用了&#xff0c;就讓它跳轉到lshx.com。是因為之前lsx.com上有很多…

Elastic Stack 安裝

Elastic Stack 是一套支持數據采集、存儲、分析、并可視化全面的分析工具&#xff0c;簡稱 ELK&#xff08;Elasticsearch&#xff0c;Logstash&#xff0c;Kibana&#xff09;的縮寫。 安裝Elastic Stack 時&#xff0c;必須相關組件使用相同的版本&#xff0c;例如&#xff1…

區塊鏈去中心化分布式_為什么漸進式去中心化是區塊鏈的最大希望

區塊鏈去中心化分布式by Arthur Camara通過亞瑟卡馬拉(Arthur Camara) 為什么漸進式去中心化是區塊鏈的最大希望 (Why Progressive Decentralization is blockchain’s best hope) 不變性是區塊鏈的最大優勢和最大障礙。 逐步分權可能是答案。 (Immutability is blockchain’s…

編譯原理—語義分析(Java)

遞歸下降語法制導翻譯 實現含多條簡單賦值語句的簡化語言的語義分析和中間代碼生成。 測試樣例 begin a:2; b:4; c:c-1; area:3.14*a*a; s:2*3.1416*r*(hr); end #詞法分析 public class analyzer {public static List<String> llistnew ArrayList<>();static …

linux問題總結

linux問題總結 編寫后臺進程的管理腳本&#xff0c;使用service deamon-name stop的時候&#xff0c;出現如下提示&#xff1a;/sbin/service: line 66: 23299 Terminated env -i LANG"$LANG" PATH"$PATH" TERM"$TERM" "${SERVICEDIR}/${SE…

linux vi行尾總是顯示顏色,【轉載】Linux 下使用 vi 沒有顏色的解決辦法

vi 是沒有顏色的&#xff0c;vim 是有顏色的。我們可以通過 rpm -qa |grep vim 看看系統中是否安裝了下面 3 個 rpm 包&#xff0c;如果有就是安裝了 vim 。[rootBetty ~]# rpm -qa |grep vimvim-minimal-7.0.109-7.el5vim-enhanced-7.0.109-7.el5vim-common-7.0.109-7.el5如果…

時間序列分析 lstm_LSTM —時間序列分析

時間序列分析 lstmNeural networks can be a hard concept to wrap your head around. I think this is mostly due to the fact that they can be used for so many different things such as classification, identification or just simply regression.神經網絡可能是一個難…

關于計算圓周率PI的經典程序

短短幾行代碼&#xff0c;卻也可圈可點。如把變量s放在PI表達式中&#xff0c;還有正負值的處理&#xff0c;都堪稱經典。尤其是處處考慮執行效率的思想令人敬佩。 /* pi/41-1/31/5-1/71/9-…… */ #include <stdio.h> int main(){ int s1; float pi0.,n1.,…

華為產品技術學習筆記之路由原理(一)

路由器&#xff1a;路由器是一種典型的網絡連接設備&#xff0c;用來進行路由選擇和報文轉發。路由器與它直接相連的網絡的跳數為0&#xff0c;通過一臺路由器可達的網絡的跳數為1.路由協議&#xff1a;路由器之間維護路由表的規則&#xff0c;用以發現路由&#xff0c;生成路由…

Linux網絡配置:設置IP地址、網關DNS、主機名

查看網絡信息 1、ifconfig eth0 2、ifconfig -a 3、ip add 設置主機名需改配置文件&#xff1a; /etc/hosts /etc/sysconfig/network vim /etc/sysconfig/network NETWORKINGyes NETWORKING_IPV6no HOSTNAMEwendyhost Linux配置網絡 方法一&#xff1a; 1、使用setup命令進入如…

編譯原理—小型(簡化)高級語言分析器前端(Java)

實現一個一遍掃描的編譯前端&#xff0c;將簡化高級語言的部分語法成分&#xff08;含賦值語句、分支語句、循環語句等&#xff09;翻譯成四元式&#xff08;或三地址代碼&#xff09;&#xff0c;還要求有合理的語法出錯報錯和錯誤恢復功能。 測試樣例 beginwhile a<b do…