add: data-structure-lab & compiler-lab
This commit is contained in:
commit
eb8c4fa451
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
.idea/
|
||||||
|
cmake-*/
|
||||||
|
build/
|
338
GrammarParser/LlParser.cpp
Normal file
338
GrammarParser/LlParser.cpp
Normal file
|
@ -0,0 +1,338 @@
|
||||||
|
#include <iostream>
|
||||||
|
#include <vector>
|
||||||
|
#include <string>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <unordered_set>
|
||||||
|
#include <list>
|
||||||
|
|
||||||
|
#define EMPTY L'ε'
|
||||||
|
#define END L'$'
|
||||||
|
|
||||||
|
struct Grammar
|
||||||
|
{
|
||||||
|
std::unordered_map<wchar_t, std::vector<std::wstring>> Generators;
|
||||||
|
std::unordered_set<wchar_t> Nonterminators;
|
||||||
|
wchar_t Begin;
|
||||||
|
std::unordered_map<wchar_t, std::unordered_set<wchar_t>> FirstSet;
|
||||||
|
std::unordered_map<wchar_t, std::unordered_set<wchar_t>> FollowSet;
|
||||||
|
std::unordered_map<wchar_t, std::unordered_map<wchar_t, std::wstring>> AnalysisTable;
|
||||||
|
|
||||||
|
Grammar(const std::unordered_map<wchar_t, std::vector<std::wstring>>&generators, const wchar_t begin)
|
||||||
|
{
|
||||||
|
Generators = generators;
|
||||||
|
Begin = begin;
|
||||||
|
|
||||||
|
for (const auto&[key, value]: generators)
|
||||||
|
{
|
||||||
|
Nonterminators.emplace(key);
|
||||||
|
FirstSet.emplace(key, std::unordered_set<wchar_t>());
|
||||||
|
FollowSet.emplace(key, std::unordered_set<wchar_t>());
|
||||||
|
AnalysisTable.emplace(key, std::unordered_map<wchar_t, std::wstring>());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 求非终结符的FIRST集合
|
||||||
|
bool changed = true;
|
||||||
|
while (changed)
|
||||||
|
{
|
||||||
|
changed = false;
|
||||||
|
|
||||||
|
for (const auto&[key, value]: generators)
|
||||||
|
{
|
||||||
|
for (const auto&expression: value)
|
||||||
|
{
|
||||||
|
if (Nonterminators.count(expression.front()) != 0)
|
||||||
|
{
|
||||||
|
// 合并其他非终结符的FIRST集合
|
||||||
|
for (const auto&c: FirstSet[expression.front()])
|
||||||
|
{
|
||||||
|
if (c != EMPTY and FirstSet[key].count(c) == 0)
|
||||||
|
{
|
||||||
|
FirstSet[key].emplace(c);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (FirstSet[key].count(expression.front()) == 0)
|
||||||
|
{
|
||||||
|
FirstSet[key].emplace(expression.front());
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 求非终结符的FOLLOW集合
|
||||||
|
changed = true;
|
||||||
|
FollowSet[begin].emplace(END);
|
||||||
|
while (changed)
|
||||||
|
{
|
||||||
|
changed = false;
|
||||||
|
|
||||||
|
for (const auto&[key, value]: generators)
|
||||||
|
{
|
||||||
|
for (const auto&expression: value)
|
||||||
|
{
|
||||||
|
for (auto i = expression.begin(); i != expression.end(); ++i)
|
||||||
|
{
|
||||||
|
if (Nonterminators.count(*i) != 0)
|
||||||
|
{
|
||||||
|
// 发现非终结符
|
||||||
|
auto next = i;
|
||||||
|
++next;
|
||||||
|
|
||||||
|
if (next == expression.end())
|
||||||
|
{
|
||||||
|
// 非终结符在表达式末尾
|
||||||
|
for (const auto&c: FollowSet[key])
|
||||||
|
{
|
||||||
|
if (FollowSet[*i].count(c) == 0)
|
||||||
|
{
|
||||||
|
FollowSet[*i].emplace(c);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::wstring newExpression;
|
||||||
|
while (next != expression.end())
|
||||||
|
{
|
||||||
|
newExpression += *next;
|
||||||
|
++next;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto&firstSet = GetFirstSet(newExpression);
|
||||||
|
|
||||||
|
for (const auto&c: firstSet)
|
||||||
|
{
|
||||||
|
if (c == EMPTY)
|
||||||
|
{
|
||||||
|
for (const auto&j: FollowSet[key])
|
||||||
|
{
|
||||||
|
if (FollowSet[*i].count(j) == 0)
|
||||||
|
{
|
||||||
|
FollowSet[*i].emplace(j);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (FollowSet[*i].count(c) == 0)
|
||||||
|
{
|
||||||
|
FollowSet[*i].emplace(c);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成预测分析表
|
||||||
|
for (const auto&[key, array]: Generators)
|
||||||
|
{
|
||||||
|
for (const auto&expression: array)
|
||||||
|
{
|
||||||
|
const auto&firstSet = GetFirstSet(expression);
|
||||||
|
|
||||||
|
for (const auto&c: firstSet)
|
||||||
|
{
|
||||||
|
if (c == EMPTY)
|
||||||
|
{
|
||||||
|
for (const auto&i: FollowSet.at(key))
|
||||||
|
{
|
||||||
|
if (!AnalysisTable[key].emplace(i, expression).second)
|
||||||
|
{
|
||||||
|
std::cout << "Error, not LL(1) grammar!" << std::endl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (!AnalysisTable[key].emplace(c, expression).second)
|
||||||
|
{
|
||||||
|
std::cout << "Error, not LL(1) grammar!" << std::endl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::unordered_set<wchar_t> GetFirstSet(const std::wstring&expression) const
|
||||||
|
{
|
||||||
|
std::unordered_set<wchar_t> set;
|
||||||
|
|
||||||
|
if (Nonterminators.count(expression.front()) != 0)
|
||||||
|
{
|
||||||
|
// 起手是非终结符
|
||||||
|
for (const auto&c: FirstSet.at(expression.front()))
|
||||||
|
{
|
||||||
|
// 只有所有的符号都能推出空串 才添加
|
||||||
|
if (c == EMPTY)
|
||||||
|
{
|
||||||
|
bool flag = true;
|
||||||
|
for (const auto&i: expression)
|
||||||
|
{
|
||||||
|
if (Nonterminators.count(i) != 0)
|
||||||
|
{
|
||||||
|
flag = FirstSet.at(i).count(EMPTY) != 0;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
flag = i == EMPTY;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!flag)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (flag)
|
||||||
|
{
|
||||||
|
set.emplace(EMPTY);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
set.emplace(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
set.emplace(expression.front());
|
||||||
|
}
|
||||||
|
|
||||||
|
return set;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Analyse(const std::wstring& input, const std::unordered_map<std::wstring, int>& numbers)
|
||||||
|
{
|
||||||
|
std::list<wchar_t> states;
|
||||||
|
auto i = input.begin();
|
||||||
|
|
||||||
|
states.emplace_back(END);
|
||||||
|
states.emplace_back(Begin);
|
||||||
|
|
||||||
|
do
|
||||||
|
{
|
||||||
|
for (const auto c : states)
|
||||||
|
{
|
||||||
|
std::wcout << c;
|
||||||
|
}
|
||||||
|
std::wcout << L'\t';
|
||||||
|
|
||||||
|
for (auto j = i; j != input.end(); ++j)
|
||||||
|
{
|
||||||
|
std::wcout << *j;
|
||||||
|
}
|
||||||
|
std::wcout << L'\t';
|
||||||
|
|
||||||
|
if (auto top = states.back(); Nonterminators.count(top) != 0)
|
||||||
|
{
|
||||||
|
// 栈顶是非终结符
|
||||||
|
if (AnalysisTable[top].count(*i) == 0)
|
||||||
|
{
|
||||||
|
std::wcout << L"error" << std::endl;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
states.pop_back();
|
||||||
|
if (AnalysisTable[top][*i].front() != EMPTY)
|
||||||
|
{
|
||||||
|
// 如果是空串还是不要加了
|
||||||
|
for (auto j = AnalysisTable[top][*i].rbegin(); j != AnalysisTable[top][*i].rend(); ++j)
|
||||||
|
{
|
||||||
|
states.emplace_back(*j);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
auto expression = top + AnalysisTable[top][*i];
|
||||||
|
std::wcout << numbers.at(expression);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (top == *i)
|
||||||
|
{
|
||||||
|
if (top == END)
|
||||||
|
{
|
||||||
|
std::wcout << L"accept";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
std::wcout << L"match";
|
||||||
|
}
|
||||||
|
|
||||||
|
states.pop_back();
|
||||||
|
++i;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
std::wcout << L"error" << std::endl;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::wcout << std::endl;
|
||||||
|
}
|
||||||
|
while (!states.empty());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
const std::unordered_map<wchar_t, std::vector<std::wstring>> map = {
|
||||||
|
{'E', {L"TA"}},
|
||||||
|
{'A', {L"+TA", L"-TA", L"ε"}},
|
||||||
|
{'T', {L"FB"}},
|
||||||
|
{'B', {L"ε", L"*FB", L"/FB"}},
|
||||||
|
{'F', {L"(E)", L"n"}}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 通过另外的表输入产生式编号
|
||||||
|
const std::unordered_map<std::wstring, int> numbers = {
|
||||||
|
{L"ETA", 1},
|
||||||
|
{L"A+TA", 2},
|
||||||
|
{L"A-TA", 3},
|
||||||
|
{L"Aε", 4},
|
||||||
|
{L"TFB", 5},
|
||||||
|
{L"B*FB", 6},
|
||||||
|
{L"B/FB", 7},
|
||||||
|
{L"Bε", 8},
|
||||||
|
{L"F(E)", 9},
|
||||||
|
{L"Fn", 10}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
FIRST
|
||||||
|
E -> n (
|
||||||
|
A -> e - +
|
||||||
|
T -> ( n
|
||||||
|
B -> / * e
|
||||||
|
F -> n (
|
||||||
|
FOLLOW
|
||||||
|
E -> ) $
|
||||||
|
A -> $ )
|
||||||
|
T -> $ ) - +
|
||||||
|
B -> + - ) $
|
||||||
|
F -> + - ) $ / *
|
||||||
|
*/
|
||||||
|
Grammar grammar(map, 'E');
|
||||||
|
|
||||||
|
std::wstring input;
|
||||||
|
std::wcin >> input;
|
||||||
|
|
||||||
|
input += END;
|
||||||
|
|
||||||
|
grammar.Analyse(input, numbers);
|
||||||
|
return 0;
|
||||||
|
}
|
443
GrammarParser/LrParser.cpp
Normal file
443
GrammarParser/LrParser.cpp
Normal file
|
@ -0,0 +1,443 @@
|
||||||
|
// ReSharper disable CppTooWideScopeInitStatement
|
||||||
|
// ReSharper disable CppUseStructuredBinding
|
||||||
|
#include <iostream>
|
||||||
|
#include <sstream>
|
||||||
|
#include <memory>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <string>
|
||||||
|
#include <unordered_set>
|
||||||
|
#include <algorithm>
|
||||||
|
#include <vector>
|
||||||
|
#include <list>
|
||||||
|
|
||||||
|
#define END L'$'
|
||||||
|
|
||||||
|
struct Expression
|
||||||
|
{
|
||||||
|
char Left;
|
||||||
|
char LookAhead;
|
||||||
|
std::string Right;
|
||||||
|
int Pos;
|
||||||
|
|
||||||
|
Expression(const char left, const std::string& right, const char lookAhead)
|
||||||
|
{
|
||||||
|
Left = left;
|
||||||
|
LookAhead = lookAhead;
|
||||||
|
Right = std::string(right);
|
||||||
|
Pos = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string GetHashCode() const
|
||||||
|
{
|
||||||
|
std::stringstream hash;
|
||||||
|
|
||||||
|
hash << Left << Right << Pos << LookAhead;
|
||||||
|
|
||||||
|
return hash.str();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ExpressionHash
|
||||||
|
{
|
||||||
|
std::size_t operator() (const Expression & expression) const
|
||||||
|
{
|
||||||
|
return std::hash<std::string>()(expression.GetHashCode());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ExpressionEqual
|
||||||
|
{
|
||||||
|
bool operator() (const Expression& a, const Expression& b) const
|
||||||
|
{
|
||||||
|
return a.GetHashCode() == b.GetHashCode();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct State
|
||||||
|
{
|
||||||
|
std::unordered_set<Expression, ExpressionHash, ExpressionEqual> Expressions;
|
||||||
|
std::unordered_map<char, std::shared_ptr<State>> Transformers;
|
||||||
|
|
||||||
|
explicit State(const std::unordered_set<Expression, ExpressionHash, ExpressionEqual>& expressions)
|
||||||
|
{
|
||||||
|
Expressions = expressions;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string GetHashCode() const
|
||||||
|
{
|
||||||
|
std::unordered_map<std::string, std::vector<char>> map;
|
||||||
|
|
||||||
|
for (const auto &e : Expressions)
|
||||||
|
{
|
||||||
|
std::stringstream stream;
|
||||||
|
stream << e.Left;
|
||||||
|
|
||||||
|
for (size_t i =0 ; i < e.Pos; ++i)
|
||||||
|
{
|
||||||
|
stream << e.Right[i];
|
||||||
|
}
|
||||||
|
stream << '^';
|
||||||
|
for (size_t i = e.Pos; i < e.Right.size(); ++i)
|
||||||
|
{
|
||||||
|
stream << e.Right[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto expression = stream.str();
|
||||||
|
if (map.count(expression) == 0)
|
||||||
|
{
|
||||||
|
map[expression] = std::vector<char>();
|
||||||
|
map[expression].emplace_back(e.LookAhead);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
map[expression].emplace_back(e.LookAhead);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> list;
|
||||||
|
for (auto& pair: map)
|
||||||
|
{
|
||||||
|
std::string hash(pair.first);
|
||||||
|
std::sort(pair.second.begin(), pair.second.end());
|
||||||
|
|
||||||
|
for (const auto c : pair.second)
|
||||||
|
{
|
||||||
|
hash += c;
|
||||||
|
}
|
||||||
|
|
||||||
|
list.emplace_back(hash);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::sort(list.begin(), list.end());
|
||||||
|
|
||||||
|
std::string hash;
|
||||||
|
|
||||||
|
for (const auto& s : list)
|
||||||
|
{
|
||||||
|
hash += s;
|
||||||
|
}
|
||||||
|
|
||||||
|
return hash;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct StateHash
|
||||||
|
{
|
||||||
|
std::size_t operator() (const std::shared_ptr<State>& s) const
|
||||||
|
{
|
||||||
|
return std::hash<std::string>()(s->GetHashCode());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct StateEqual
|
||||||
|
{
|
||||||
|
bool operator() (const std::shared_ptr<State>& a, const std::shared_ptr<State>& b) const
|
||||||
|
{
|
||||||
|
return a->GetHashCode() == b->GetHashCode();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Grammar
|
||||||
|
{
|
||||||
|
std::unordered_map<char, std::vector<std::string>> Generators;
|
||||||
|
char Begin;
|
||||||
|
std::shared_ptr<State> BeginState;
|
||||||
|
|
||||||
|
std::unordered_set<char> Nonterminators;
|
||||||
|
std::unordered_map<char, std::unordered_set<char>> FirstSet;
|
||||||
|
std::unordered_set<std::shared_ptr<State>, StateHash, StateEqual> DFA;
|
||||||
|
|
||||||
|
Grammar(const std::unordered_map<char, std::vector<std::string>>& map, const char begin)
|
||||||
|
{
|
||||||
|
Generators = map;
|
||||||
|
Begin = begin;
|
||||||
|
|
||||||
|
for (const auto& pair : Generators)
|
||||||
|
{
|
||||||
|
Nonterminators.emplace(pair.first);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构造FirstSet
|
||||||
|
bool changed = true;
|
||||||
|
while (changed)
|
||||||
|
{
|
||||||
|
changed = false;
|
||||||
|
|
||||||
|
for (const auto& pair: Generators)
|
||||||
|
{
|
||||||
|
for (const auto&expression: pair.second)
|
||||||
|
{
|
||||||
|
if (Nonterminators.count(expression.front()) != 0)
|
||||||
|
{
|
||||||
|
// 合并其他非终结符的FIRST集合
|
||||||
|
for (const auto&c: FirstSet[expression.front()])
|
||||||
|
{
|
||||||
|
if (FirstSet[pair.first].count(c) == 0)
|
||||||
|
{
|
||||||
|
FirstSet[pair.first].emplace(c);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (FirstSet[pair.first].count(expression.front()) == 0)
|
||||||
|
{
|
||||||
|
FirstSet[pair.first].emplace(expression.front());
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
~Grammar()
|
||||||
|
{
|
||||||
|
DFA.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* \brief 计算句子的First集合
|
||||||
|
* \param expression 需要计算的句子
|
||||||
|
* \return 句子的First集合
|
||||||
|
*/
|
||||||
|
std::unordered_set<char> GetFirstSet(const std::string& expression) const
|
||||||
|
{
|
||||||
|
std::unordered_set<char> result;
|
||||||
|
|
||||||
|
if (Nonterminators.count(expression.front()) != 0)
|
||||||
|
{
|
||||||
|
// 起手是非终结符
|
||||||
|
for (const char c : FirstSet.at(expression.front()))
|
||||||
|
{
|
||||||
|
result.emplace(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
result.emplace(expression.front());
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::unordered_set<Expression, ExpressionHash, ExpressionEqual> ConstructClosure(const Expression& expression) const
|
||||||
|
{
|
||||||
|
std::unordered_set<Expression, ExpressionHash, ExpressionEqual> result;
|
||||||
|
result.emplace(expression);
|
||||||
|
|
||||||
|
bool changed = true;
|
||||||
|
while (changed)
|
||||||
|
{
|
||||||
|
changed = false;
|
||||||
|
|
||||||
|
for (const auto& e : result)
|
||||||
|
{
|
||||||
|
const char next = e.Right[e.Pos];
|
||||||
|
|
||||||
|
if (Nonterminators.count(next) == 0)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string ahead;
|
||||||
|
|
||||||
|
for (size_t i = e.Pos + 1; i < e.Right.size(); ++i)
|
||||||
|
{
|
||||||
|
ahead += e.Right[i];
|
||||||
|
}
|
||||||
|
ahead += e.LookAhead;
|
||||||
|
|
||||||
|
std::unordered_set<char> lookAheadSet = GetFirstSet(ahead);
|
||||||
|
|
||||||
|
for (const auto& i : Generators.at(next))
|
||||||
|
{
|
||||||
|
for (const char lookAhead : lookAheadSet)
|
||||||
|
{
|
||||||
|
Expression newExpression(next, i, lookAhead);
|
||||||
|
if (result.count(newExpression) == 0)
|
||||||
|
{
|
||||||
|
result.emplace(newExpression);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ConstructDFA()
|
||||||
|
{
|
||||||
|
const Expression begin = Expression(Begin, Generators.at(Begin).front(), END);
|
||||||
|
int id = 0;
|
||||||
|
|
||||||
|
BeginState = std::make_shared<State>(ConstructClosure(begin));
|
||||||
|
DFA.emplace(BeginState);
|
||||||
|
++id;
|
||||||
|
|
||||||
|
bool added = true;
|
||||||
|
while (added)
|
||||||
|
{
|
||||||
|
added = false;
|
||||||
|
|
||||||
|
for (const auto& state : DFA)
|
||||||
|
{
|
||||||
|
// 表示使用key 进行移进可以生成的新LR(1)句型
|
||||||
|
std::unordered_map<char, std::vector<Expression>> nextExpressions;
|
||||||
|
|
||||||
|
for (const auto& e : state->Expressions)
|
||||||
|
{
|
||||||
|
Expression nextExpression = Expression(e);
|
||||||
|
if (nextExpression.Pos >= nextExpression.Right.size())
|
||||||
|
{
|
||||||
|
// 移进符号已经到达句型的末尾
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
nextExpression.Pos++;
|
||||||
|
|
||||||
|
if (nextExpressions.count(e.Right[e.Pos]) == 0)
|
||||||
|
{
|
||||||
|
std::vector<Expression> list;
|
||||||
|
list.emplace_back(nextExpression);
|
||||||
|
nextExpressions.emplace(e.Right[e.Pos], list);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
nextExpressions.at(e.Right[e.Pos]).emplace_back(nextExpression);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const auto& pair : nextExpressions)
|
||||||
|
{
|
||||||
|
// 针对每个构建项目集闭包
|
||||||
|
std::unordered_set<Expression, ExpressionHash, ExpressionEqual> closure;
|
||||||
|
|
||||||
|
for (const auto& i : pair.second)
|
||||||
|
{
|
||||||
|
for (const auto& e : ConstructClosure(i))
|
||||||
|
{
|
||||||
|
closure.emplace(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
auto nextState = std::make_shared<State>(closure);
|
||||||
|
|
||||||
|
auto iter = DFA.find(nextState);
|
||||||
|
if (iter == DFA.end())
|
||||||
|
{
|
||||||
|
// 不存在这个项目集闭包
|
||||||
|
DFA.emplace(nextState);
|
||||||
|
state->Transformers.emplace(pair.first, nextState);
|
||||||
|
|
||||||
|
++id;
|
||||||
|
added = true;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// 存在这个项目集闭包
|
||||||
|
state->Transformers.emplace(pair.first, *iter);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Analyse(const std::unordered_map<std::string, int>& numbers, const std::string& input) const
|
||||||
|
{
|
||||||
|
std::list<std::shared_ptr<State>> stateStack;
|
||||||
|
stateStack.emplace_back(BeginState);
|
||||||
|
|
||||||
|
std::string buffer(input);
|
||||||
|
buffer += END;
|
||||||
|
auto iter = buffer.begin();
|
||||||
|
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
const auto& top = stateStack.back();
|
||||||
|
|
||||||
|
// 尝试进行移进
|
||||||
|
bool acceptFlag = false;
|
||||||
|
bool reduceFlag = false;
|
||||||
|
for (const auto& expression : top->Expressions)
|
||||||
|
{
|
||||||
|
if (expression.Pos == expression.Right.size() and expression.LookAhead == *iter)
|
||||||
|
{
|
||||||
|
if (expression.Left == Begin)
|
||||||
|
{
|
||||||
|
acceptFlag = true;
|
||||||
|
std::cout << "accept" << std::endl;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
reduceFlag = true;
|
||||||
|
std::cout << numbers.at(expression.Left + expression.Right) << std::endl;
|
||||||
|
|
||||||
|
for (size_t i = 0; i < expression.Right.size(); ++i)
|
||||||
|
{
|
||||||
|
stateStack.pop_back();
|
||||||
|
}
|
||||||
|
|
||||||
|
stateStack.emplace_back(stateStack.back()->Transformers.at(expression.Left));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (acceptFlag)
|
||||||
|
{
|
||||||
|
// 接受
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (reduceFlag)
|
||||||
|
{
|
||||||
|
// reduce
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (top->Transformers.count(*iter) != 0)
|
||||||
|
{
|
||||||
|
stateStack.emplace_back(top->Transformers.at(*iter));
|
||||||
|
++iter;
|
||||||
|
|
||||||
|
std::cout << "shift" << std::endl;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::cout << "error" << std::endl;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
const std::unordered_map<char, std::vector<std::string>> map = {
|
||||||
|
{'S', {"E"}},
|
||||||
|
{'E', {"E+T", "E-T", "T"}},
|
||||||
|
{'T', {"T*F", "T/F", "F"}},
|
||||||
|
{'F', {"(E)", "n"}}
|
||||||
|
};
|
||||||
|
|
||||||
|
const std::unordered_map<std::string, int> numbers = {
|
||||||
|
{"SE", 0},
|
||||||
|
{"EE+T", 1},
|
||||||
|
{"EE-T", 2},
|
||||||
|
{"ET", 3},
|
||||||
|
{"TT*F", 4},
|
||||||
|
{"TT/F", 5},
|
||||||
|
{"TF", 6},
|
||||||
|
{"F(E)", 7},
|
||||||
|
{"Fn", 8}
|
||||||
|
};
|
||||||
|
|
||||||
|
Grammar grammar(map, 'S');
|
||||||
|
grammar.ConstructDFA();
|
||||||
|
|
||||||
|
std::string input;
|
||||||
|
std::cin >> input;
|
||||||
|
|
||||||
|
grammar.Analyse(numbers, input);
|
||||||
|
return 0;
|
||||||
|
}
|
674
LICENSE
Normal file
674
LICENSE
Normal file
|
@ -0,0 +1,674 @@
|
||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
751
LexicalParser/LexicalParser.cpp
Normal file
751
LexicalParser/LexicalParser.cpp
Normal file
|
@ -0,0 +1,751 @@
|
||||||
|
#include <cstdio>
|
||||||
|
#include <list>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <unordered_set>
|
||||||
|
#include <vector>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
class LexicalParser
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
int LineCount = 0;
|
||||||
|
int KeywordCount = 0;
|
||||||
|
int IdentifierCount = 0;
|
||||||
|
int OperatorCount = 0;
|
||||||
|
int DelimiterCount = 0;
|
||||||
|
int CharCount = 0;
|
||||||
|
int StringCount = 0;
|
||||||
|
int NumberCount = 0;
|
||||||
|
int ErrorCount = 0;
|
||||||
|
|
||||||
|
explicit LexicalParser(FILE *file)
|
||||||
|
{
|
||||||
|
this->File = file;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Loop()
|
||||||
|
{
|
||||||
|
bool mark = false;
|
||||||
|
|
||||||
|
while (Readline())
|
||||||
|
{
|
||||||
|
while (!Buffer.empty())
|
||||||
|
{
|
||||||
|
if (mark)
|
||||||
|
{
|
||||||
|
// 多行注释
|
||||||
|
for (auto i = Buffer.begin(); i != Buffer.end(); i++)
|
||||||
|
{
|
||||||
|
if (*i == '*')
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
if (i != Buffer.end() and *i == '/')
|
||||||
|
{
|
||||||
|
mark = false;
|
||||||
|
|
||||||
|
i++;
|
||||||
|
if (i == Buffer.end())
|
||||||
|
{
|
||||||
|
Buffer.clear();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Buffer.erase(Buffer.begin(), i);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mark)
|
||||||
|
{
|
||||||
|
// 说明在这行没有找到结束符
|
||||||
|
Buffer.clear();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 这行读取完成了
|
||||||
|
if (Buffer.empty())
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
auto pos = Buffer.begin();
|
||||||
|
if (*pos == '/')
|
||||||
|
{
|
||||||
|
pos++;
|
||||||
|
if (pos != Buffer.end())
|
||||||
|
{
|
||||||
|
// 判断单行注释
|
||||||
|
if (*pos == '/')
|
||||||
|
{
|
||||||
|
Buffer.clear();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
else if (*pos == '*')
|
||||||
|
{
|
||||||
|
mark = true;
|
||||||
|
pos++;
|
||||||
|
Buffer.erase(Buffer.begin(), pos);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (*Buffer.begin() == ' ' or *Buffer.begin() == '\t')
|
||||||
|
{
|
||||||
|
Buffer.pop_front();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理特殊错误 @
|
||||||
|
if (*Buffer.begin() == '@')
|
||||||
|
{
|
||||||
|
Buffer.pop_front();
|
||||||
|
|
||||||
|
ErrorCount++;
|
||||||
|
printf("%d <ERROR,@>\n", LineCount);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Parse())
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::list<char> Buffer;
|
||||||
|
FILE *File;
|
||||||
|
|
||||||
|
bool Parse()
|
||||||
|
{
|
||||||
|
if (ParseCharacter() or ParseString())
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ParseNumber())
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ParseOperator() or ParseDelimiter())
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ParseKeyword())
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ParseIdentifier();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Readline()
|
||||||
|
{
|
||||||
|
// 标记是否是最后一行
|
||||||
|
bool read = false;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
int c = fgetc(File);
|
||||||
|
|
||||||
|
if (c == EOF)
|
||||||
|
{
|
||||||
|
if (read)
|
||||||
|
{
|
||||||
|
LineCount++;
|
||||||
|
}
|
||||||
|
return read;
|
||||||
|
}
|
||||||
|
else if (c == '\n')
|
||||||
|
{
|
||||||
|
LineCount++;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
Buffer.emplace_back((char) c);
|
||||||
|
read = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ParseKeyword()
|
||||||
|
{
|
||||||
|
auto begin = Buffer.begin();
|
||||||
|
|
||||||
|
if (KeywordsMap.count(*begin) != 0)
|
||||||
|
{
|
||||||
|
const auto &array = KeywordsMap.at(*begin);
|
||||||
|
|
||||||
|
|
||||||
|
for (const auto &i: array)
|
||||||
|
{
|
||||||
|
if (i.length() > Buffer.size())
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto pos = Buffer.begin();
|
||||||
|
bool flag = true;
|
||||||
|
for (auto c: i)
|
||||||
|
{
|
||||||
|
if (c != *pos)
|
||||||
|
{
|
||||||
|
flag = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (flag)
|
||||||
|
{
|
||||||
|
// 同标识符吻合的字符串
|
||||||
|
// 如果是标识符,应该是分隔符或者空格
|
||||||
|
if (pos == Buffer.end() or *pos == ' ' or DelimitersSet.count(*pos) != 0
|
||||||
|
or OperatorsMap.count(*pos) != 0)
|
||||||
|
{
|
||||||
|
KeywordCount++;
|
||||||
|
|
||||||
|
std::string output;
|
||||||
|
for (auto j = Buffer.begin(); j != pos; j++)
|
||||||
|
{
|
||||||
|
output += *j;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("%d <KEYWORD,%s>\n", LineCount, output.c_str());
|
||||||
|
|
||||||
|
Buffer.erase(Buffer.begin(), pos);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ParseIdentifier()
|
||||||
|
{
|
||||||
|
auto pos = Buffer.begin();
|
||||||
|
|
||||||
|
if (*pos == '_' or (*pos >= 'A' and *pos <= 'Z') or (*pos >= 'a' and *pos <= 'z'))
|
||||||
|
{
|
||||||
|
while (*pos == '_' or (*pos >= 'A' and *pos <= 'Z') or (*pos >= 'a' and *pos <= 'z')
|
||||||
|
or (*pos >= '0' and *pos <= '9'))
|
||||||
|
{
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pos == Buffer.end() or *pos == ' ' or DelimitersSet.count(*pos) != 0
|
||||||
|
or OperatorsMap.count(*pos) != 0)
|
||||||
|
{
|
||||||
|
IdentifierCount++;
|
||||||
|
|
||||||
|
std::string output;
|
||||||
|
for (auto i = Buffer.begin(); i != pos; i++)
|
||||||
|
{
|
||||||
|
output += *i;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("%d <IDENTIFIER,%s>\n", LineCount, output.c_str());
|
||||||
|
|
||||||
|
Buffer.erase(Buffer.begin(), pos);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ParseDelimiter()
|
||||||
|
{
|
||||||
|
auto pos = Buffer.begin();
|
||||||
|
|
||||||
|
if (DelimitersSet.count(*pos) != 0)
|
||||||
|
{
|
||||||
|
DelimiterCount++;
|
||||||
|
printf("%d <DELIMITER,%c>\n", LineCount, *pos);
|
||||||
|
|
||||||
|
Buffer.pop_front();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ParseOperator()
|
||||||
|
{
|
||||||
|
auto begin = Buffer.begin();
|
||||||
|
|
||||||
|
if (OperatorsMap.count(*begin))
|
||||||
|
{
|
||||||
|
const auto &array = OperatorsMap.at(*begin);
|
||||||
|
|
||||||
|
for (const auto &s: array)
|
||||||
|
{
|
||||||
|
if (s.length() > Buffer.size())
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto pos = Buffer.begin();
|
||||||
|
bool flag = true;
|
||||||
|
|
||||||
|
for (auto i: s)
|
||||||
|
{
|
||||||
|
if (i != *pos)
|
||||||
|
{
|
||||||
|
flag = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (flag)
|
||||||
|
{
|
||||||
|
OperatorCount++;
|
||||||
|
// 感觉,,,,
|
||||||
|
// 可以不用判断运算符的后面是什么
|
||||||
|
std::string output;
|
||||||
|
for (auto i = Buffer.begin(); i != pos; i++)
|
||||||
|
{
|
||||||
|
output += *i;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("%d <OPERATOR,%s>\n", LineCount, output.c_str());
|
||||||
|
|
||||||
|
Buffer.erase(Buffer.begin(), pos);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ParseCharacter()
|
||||||
|
{
|
||||||
|
std::string output;
|
||||||
|
|
||||||
|
auto first = Buffer.begin();
|
||||||
|
auto second = first;
|
||||||
|
second++;
|
||||||
|
|
||||||
|
if (*first == 'L' or *first == 'u' or *first == 'U')
|
||||||
|
{
|
||||||
|
if (*second == '\'')
|
||||||
|
{
|
||||||
|
output += *first;
|
||||||
|
Buffer.erase(first, second);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
auto pos = Buffer.begin();
|
||||||
|
|
||||||
|
if (*pos == '\'')
|
||||||
|
{
|
||||||
|
pos++;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
//处理本行没有闭合的错误
|
||||||
|
if (pos == Buffer.end())
|
||||||
|
{
|
||||||
|
for (auto c: Buffer)
|
||||||
|
{
|
||||||
|
output += c;
|
||||||
|
}
|
||||||
|
|
||||||
|
Buffer.clear();
|
||||||
|
ErrorCount++;
|
||||||
|
printf("%d <ERROR,%s>\n", LineCount, output.c_str());
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (*pos == '\'')
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (*pos == '\\')
|
||||||
|
{
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
pos++;
|
||||||
|
|
||||||
|
CharCount++;
|
||||||
|
for (auto i = Buffer.begin(); i != pos; i++)
|
||||||
|
{
|
||||||
|
output += *i;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("%d <CHARCON,%s>\n", LineCount, output.c_str());
|
||||||
|
|
||||||
|
Buffer.erase(Buffer.begin(), pos);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ParseString()
|
||||||
|
{
|
||||||
|
auto first = Buffer.begin();
|
||||||
|
auto second = first;
|
||||||
|
second++;
|
||||||
|
|
||||||
|
std::string output;
|
||||||
|
|
||||||
|
if (*first == 'u' or *first == 'U' or *first == 'L')
|
||||||
|
{
|
||||||
|
auto third = second;
|
||||||
|
third++;
|
||||||
|
if (*second == '\"')
|
||||||
|
{
|
||||||
|
output += *first;
|
||||||
|
Buffer.erase(first, second);
|
||||||
|
}
|
||||||
|
else if (*first == 'u' and *second == '8')
|
||||||
|
{
|
||||||
|
if (*third == '\"')
|
||||||
|
{
|
||||||
|
output = "u8";
|
||||||
|
Buffer.erase(first, third);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
auto pos = Buffer.begin();
|
||||||
|
|
||||||
|
if (*pos == '"')
|
||||||
|
{
|
||||||
|
pos++;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
//处理本行没有闭合的错误
|
||||||
|
if (pos == Buffer.end())
|
||||||
|
{
|
||||||
|
for (auto c: Buffer)
|
||||||
|
{
|
||||||
|
output += c;
|
||||||
|
}
|
||||||
|
|
||||||
|
Buffer.clear();
|
||||||
|
ErrorCount++;
|
||||||
|
printf("%d <ERROR,%s>\n", LineCount, output.c_str());
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (*pos == '"')
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (*pos == '\\')
|
||||||
|
{
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
pos++;
|
||||||
|
|
||||||
|
StringCount++;
|
||||||
|
for (auto i = Buffer.begin(); i != pos; i++)
|
||||||
|
{
|
||||||
|
output += *i;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("%d <STRING,%s>\n", LineCount, output.c_str());
|
||||||
|
Buffer.erase(Buffer.begin(), pos);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ParseNumber()
|
||||||
|
{
|
||||||
|
auto first = Buffer.begin();
|
||||||
|
auto second = first;
|
||||||
|
second++;
|
||||||
|
auto third = second;
|
||||||
|
third++;
|
||||||
|
|
||||||
|
if ((*first >= '0' and *first <= '9') or *first == '.')
|
||||||
|
{
|
||||||
|
if (*first == '0' and (*second == 'x' or *second == 'X'))
|
||||||
|
{
|
||||||
|
// 处理十六进制数据
|
||||||
|
ParseHexadecimalNumber();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto pos = Buffer.begin();
|
||||||
|
if (*first == '.')
|
||||||
|
{
|
||||||
|
// 区分小数点和访问符
|
||||||
|
if (*second < '0' or *second > '9')
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (pos != Buffer.end() and *pos >= '0' and *pos <= '9' or *pos == '.')
|
||||||
|
{
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pos != Buffer.end() and (*pos == 'e' or *pos == 'E' or *pos == '.'))
|
||||||
|
{
|
||||||
|
pos++;
|
||||||
|
|
||||||
|
if (*pos == '+' or *pos == '-')
|
||||||
|
{
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pos == Buffer.end() or *pos < '0' or *pos > '9')
|
||||||
|
{
|
||||||
|
// 坏了
|
||||||
|
while (pos != Buffer.end() and *pos != ' ' and *pos != '\t' and
|
||||||
|
OperatorsMap.count(*pos) == 0 and
|
||||||
|
DelimitersSet.count(*pos) == 0)
|
||||||
|
{
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string output;
|
||||||
|
for (auto i = Buffer.begin(); i != pos; i++)
|
||||||
|
{
|
||||||
|
output += *i;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("%d <ERROR,%s>\n", LineCount, output.c_str());
|
||||||
|
ErrorCount++;
|
||||||
|
Buffer.erase(Buffer.begin(), pos);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
while (pos != Buffer.end() and *pos >= '0' and *pos <= '9' or *pos == '.')
|
||||||
|
{
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::unordered_set<char> suffixSet = {'u', 'l', 'U', 'L', 'f', 'F'};
|
||||||
|
|
||||||
|
if (pos != Buffer.end() and suffixSet.count(*pos) != 0)
|
||||||
|
{
|
||||||
|
while (pos != Buffer.end() and suffixSet.count(*pos) != 0)
|
||||||
|
{
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pos != Buffer.end() and *pos != ' ' and *pos != '\t' and
|
||||||
|
OperatorsMap.count(*pos) == 0 and
|
||||||
|
DelimitersSet.count(*pos) == 0)
|
||||||
|
{
|
||||||
|
while (pos != Buffer.end() and *pos != ' ' and *pos != '\t' and
|
||||||
|
OperatorsMap.count(*pos) == 0 and
|
||||||
|
DelimitersSet.count(*pos) == 0)
|
||||||
|
{
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string output;
|
||||||
|
for (auto i = Buffer.begin(); i != pos; i++)
|
||||||
|
{
|
||||||
|
output += *i;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("%d <ERROR,%s>\n", LineCount, output.c_str());
|
||||||
|
ErrorCount++;
|
||||||
|
Buffer.erase(Buffer.begin(), pos);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string output;
|
||||||
|
for (auto i = Buffer.begin(); i != pos; i++)
|
||||||
|
{
|
||||||
|
output += *i;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("%d <NUMBER,%s>\n", LineCount, output.c_str());
|
||||||
|
NumberCount++;
|
||||||
|
Buffer.erase(Buffer.begin(), pos);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
else if (pos != Buffer.end() and *pos != ' ' and *pos != '\t' and
|
||||||
|
OperatorsMap.count(*pos) == 0 and
|
||||||
|
DelimitersSet.count(*pos) == 0)
|
||||||
|
{
|
||||||
|
while (pos != Buffer.end() and *pos != ' ' and *pos != '\t' and
|
||||||
|
OperatorsMap.count(*pos) == 0 and
|
||||||
|
DelimitersSet.count(*pos) == 0)
|
||||||
|
{
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string output;
|
||||||
|
for (auto i = Buffer.begin(); i != pos; i++)
|
||||||
|
{
|
||||||
|
output += *i;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("%d <ERROR,%s>\n", LineCount, output.c_str());
|
||||||
|
ErrorCount++;
|
||||||
|
Buffer.erase(Buffer.begin(), pos);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string output;
|
||||||
|
for (auto i = Buffer.begin(); i != pos; i++)
|
||||||
|
{
|
||||||
|
output += *i;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("%d <NUMBER,%s>\n", LineCount, output.c_str());
|
||||||
|
NumberCount++;
|
||||||
|
Buffer.erase(Buffer.begin(), pos);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ParseHexadecimalNumber()
|
||||||
|
{
|
||||||
|
auto pos = Buffer.begin();
|
||||||
|
pos++;
|
||||||
|
pos++;
|
||||||
|
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
if ((*pos >= '0' and *pos <= '9') or
|
||||||
|
(*pos >= 'A' and *pos <= 'F') or
|
||||||
|
(*pos >= 'a' and *pos <= 'f'))
|
||||||
|
{
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
else if (pos == Buffer.end() or *pos == ' ' or *pos == '\t' or
|
||||||
|
OperatorsMap.count(*pos) != 0 or
|
||||||
|
DelimitersSet.count(*pos) != 0)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// 遇到错误
|
||||||
|
while (pos != Buffer.end() and *pos != ' ' and *pos != '\t' and
|
||||||
|
OperatorsMap.count(*pos) == 0 and
|
||||||
|
DelimitersSet.count(*pos) == 0)
|
||||||
|
{
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string output;
|
||||||
|
for (auto i = Buffer.begin(); i != pos; i++)
|
||||||
|
{
|
||||||
|
output += *i;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("%d <ERROR,%s>\n", LineCount, output.c_str());
|
||||||
|
Buffer.erase(Buffer.begin(), pos);
|
||||||
|
ErrorCount++;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string output;
|
||||||
|
for (auto i = Buffer.begin(); i != pos; i++)
|
||||||
|
{
|
||||||
|
output += *i;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("%d <NUMBER,%s>\n", LineCount, output.c_str());
|
||||||
|
NumberCount++;
|
||||||
|
Buffer.erase(Buffer.begin(), pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::unordered_map<char, std::vector<std::string>> KeywordsMap = {
|
||||||
|
{'a', {"auto"}},
|
||||||
|
{'b', {"break"}},
|
||||||
|
{'c', {"case", "char", "const", "continue"}},
|
||||||
|
{'d', {"double", "default", "do"}},
|
||||||
|
{'e', {"else", "extern", "enum"}},
|
||||||
|
{'f', {"float", "for"}},
|
||||||
|
{'g', {"goto"}},
|
||||||
|
{'i', {"if", "int"}},
|
||||||
|
{'l', {"long"}},
|
||||||
|
{'s', {"struct", "static", "switch", "short", "signed", "sizeof"}},
|
||||||
|
{'r', {"register", "return"}},
|
||||||
|
{'t', {"typedef",}},
|
||||||
|
{'u', {"union", "unsigned"}},
|
||||||
|
{'v', {"void", "volatile"}},
|
||||||
|
{'w', {"while"}}
|
||||||
|
};
|
||||||
|
|
||||||
|
const std::unordered_map<char, std::vector<std::string>> OperatorsMap = {
|
||||||
|
{'+', {"++", "+=", "+"}},
|
||||||
|
{'-', {"--", "-=", "->", "-"}},
|
||||||
|
{'*', {"*=", "*"}},
|
||||||
|
{'/', {"/=", "/"}},
|
||||||
|
{'%', {"%=", "%"}},
|
||||||
|
{'=', {"==", "="}},
|
||||||
|
{'!', {"!=", "!"}},
|
||||||
|
{'>', {">>=", ">>", ">=", ">"}},
|
||||||
|
{'<', {"<<=", "<<", "<=", "<"}},
|
||||||
|
{'&', {"&&", "&=", "&"}},
|
||||||
|
{'|', {"||", "|=", "|"}},
|
||||||
|
{'^', {"^=", "^"}},
|
||||||
|
{'.', {"."}},
|
||||||
|
{'~', {"~"}}
|
||||||
|
};
|
||||||
|
|
||||||
|
const std::unordered_set<char> DelimitersSet = {
|
||||||
|
';', ',', ':', '?', '(', ')', '[', ']', '{', '}'
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
int main(int argc, char *argv[])
|
||||||
|
{
|
||||||
|
FILE *source_file = fopen(argv[1], "r");
|
||||||
|
|
||||||
|
if (source_file == nullptr || argc != 2)
|
||||||
|
{
|
||||||
|
printf("Failed to open source File.\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
LexicalParser parser(source_file);
|
||||||
|
|
||||||
|
parser.Loop();
|
||||||
|
|
||||||
|
printf("%d\n", parser.LineCount);
|
||||||
|
printf("%d %d %d %d %d %d %d\n", parser.KeywordCount,
|
||||||
|
parser.IdentifierCount,
|
||||||
|
parser.OperatorCount,
|
||||||
|
parser.DelimiterCount,
|
||||||
|
parser.CharCount,
|
||||||
|
parser.StringCount,
|
||||||
|
parser.NumberCount);
|
||||||
|
printf("%d", parser.ErrorCount);
|
||||||
|
|
||||||
|
fclose(source_file);
|
||||||
|
return 0;
|
||||||
|
}
|
27
LexicalParser/pl_start.l
Normal file
27
LexicalParser/pl_start.l
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
/* 简单词法分析器 */
|
||||||
|
/* 功能:能够识别出以小写字母ab结尾的所有字符串(仅含大小写字母)并给打印'Hit!' */
|
||||||
|
/* 说明:在下面的begin和end之间添加代码,注意格式 */
|
||||||
|
/* 提示:你只需要保证合法的输入(以ab结尾的字符串)有结果,不合法的输入将会包含在.规则中~ */
|
||||||
|
%{
|
||||||
|
#include <stdio.h>
|
||||||
|
%}
|
||||||
|
|
||||||
|
%%
|
||||||
|
/* begin */
|
||||||
|
[a-zA-Z]*ab {printf("%s: Hit!\n", yytext);}
|
||||||
|
/* end */
|
||||||
|
\n {}
|
||||||
|
. {}
|
||||||
|
%%
|
||||||
|
int yywrap() { return 1; }
|
||||||
|
int main(int argc, char **argv)
|
||||||
|
{
|
||||||
|
if (argc > 1) {
|
||||||
|
if (!(yyin = fopen(argv[1], "r"))) {
|
||||||
|
perror(argv[1]);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (yylex());
|
||||||
|
return 0;
|
||||||
|
}
|
117
LexicalParser/pl_test.l
Normal file
117
LexicalParser/pl_test.l
Normal file
|
@ -0,0 +1,117 @@
|
||||||
|
/* PL词法分析器 */
|
||||||
|
/* 功能:能够识别出PL支持的所有单词符号并给出种别值 */
|
||||||
|
/* 说明:在下面的begin和end之间添加代码,已经实现了标识符和整常量的识别,你需要完成剩下的部分,加油吧! */
|
||||||
|
/* 提示:因为是顺序匹配,即从上至下依次匹配规则,所以需要合理安排顺序~ */
|
||||||
|
%{
|
||||||
|
#include <stdio.h>
|
||||||
|
%}
|
||||||
|
/* begin */
|
||||||
|
INTCON [\-]?[1-9][0-9]*|0
|
||||||
|
IDENT [A-Za-z][A-Za-z0-9]*
|
||||||
|
CHARCON \'[^\']*\'
|
||||||
|
OFSYM of
|
||||||
|
ARRAYSYM array
|
||||||
|
PROGRAMSYM program
|
||||||
|
MODSYM mod
|
||||||
|
ANDSYM and
|
||||||
|
ORSYM or
|
||||||
|
NOTSYM not
|
||||||
|
BEGINSYM begin
|
||||||
|
ENDSYM end
|
||||||
|
IFSYM if
|
||||||
|
THENSYM then
|
||||||
|
ELSESYM else
|
||||||
|
WHILESYM while
|
||||||
|
DOSYM do
|
||||||
|
CALLSYM call
|
||||||
|
CONSTSYM const
|
||||||
|
TYPESYM type
|
||||||
|
VARSYM var
|
||||||
|
PROCSYM procedure
|
||||||
|
NEQ \<\>
|
||||||
|
LEQ \<\=
|
||||||
|
GEQ \>\=
|
||||||
|
BECOME \:\=
|
||||||
|
PLUS \+
|
||||||
|
MINUS \-
|
||||||
|
TIMES \*
|
||||||
|
DIVSYM \/
|
||||||
|
EQL \=
|
||||||
|
LSS \<
|
||||||
|
GTR \>
|
||||||
|
LBRACK \[
|
||||||
|
RBRACK \]
|
||||||
|
LPAREN \(
|
||||||
|
RPAREN \)
|
||||||
|
COMMA \,
|
||||||
|
SEMICOLON \;
|
||||||
|
PERIOD \.
|
||||||
|
COLON \:
|
||||||
|
ERROR [\~\!\@\#\$\%\^\&\_\\]
|
||||||
|
|
||||||
|
/* end */
|
||||||
|
|
||||||
|
%%
|
||||||
|
/* begin */
|
||||||
|
{OFSYM} {printf("%s: OFSYM\n", yytext);}
|
||||||
|
{ARRAYSYM} {printf("%s: ARRAYSYM\n", yytext);}
|
||||||
|
{PROGRAMSYM} {printf("%s: PROGRAMSYM\n", yytext);}
|
||||||
|
{MODSYM} {printf("%s: MODSYM\n", yytext);}
|
||||||
|
{ANDSYM} {printf("%s: ANDSYM\n", yytext);}
|
||||||
|
{ORSYM} {printf("%s: ORSYM\n", yytext);}
|
||||||
|
{NOTSYM} {printf("%s: NOTSYM\n", yytext);}
|
||||||
|
{BEGINSYM} {printf("%s: BEGINSYM\n", yytext);}
|
||||||
|
{ENDSYM} {printf("%s: ENDSYM\n", yytext);}
|
||||||
|
{IFSYM} {printf("%s: IFSYM\n", yytext);}
|
||||||
|
{THENSYM} {printf("%s: THENSYM\n", yytext);}
|
||||||
|
{ELSESYM} {printf("%s: ELSESYM\n", yytext);}
|
||||||
|
{WHILESYM} {printf("%s: WHILESYM\n", yytext);}
|
||||||
|
{DOSYM} {printf("%s: DOSYM\n", yytext);}
|
||||||
|
{CALLSYM} {printf("%s: CALLSYM\n", yytext);}
|
||||||
|
{CONSTSYM} {printf("%s: CONSTSYM\n", yytext);}
|
||||||
|
{TYPESYM} {printf("%s: TYPESYM\n", yytext);}
|
||||||
|
{VARSYM} {printf("%s: VARSYM\n", yytext);}
|
||||||
|
{PROCSYM} {printf("%s: PROCSYM\n", yytext);}
|
||||||
|
|
||||||
|
{NEQ} {printf("%s: NEQ\n", yytext);}
|
||||||
|
{LEQ} {printf("%s: LEQ\n", yytext);}
|
||||||
|
{GEQ} {printf("%s: GEQ\n", yytext);}
|
||||||
|
{BECOME} {printf("%s: BECOME\n", yytext);}
|
||||||
|
|
||||||
|
{PLUS} {printf("%s: PLUS\n", yytext);}
|
||||||
|
{MINUS} {printf("%s: MINUS\n", yytext);}
|
||||||
|
{TIMES} {printf("%s: TIMES\n", yytext);}
|
||||||
|
{DIVSYM} {printf("%s: DIVSYM\n", yytext);}
|
||||||
|
{EQL} {printf("%s: EQL\n", yytext);}
|
||||||
|
{LSS} {printf("%s: LSS\n", yytext);}
|
||||||
|
{GTR} {printf("%s: GTR\n", yytext);}
|
||||||
|
{LBRACK} {printf("%s: LBRACK\n", yytext);}
|
||||||
|
{RBRACK} {printf("%s: RBRACK\n", yytext);}
|
||||||
|
{LPAREN} {printf("%s: LPAREN\n", yytext);}
|
||||||
|
{RPAREN} {printf("%s: RPAREN\n", yytext);}
|
||||||
|
{COMMA} {printf("%s: COMMA\n", yytext);}
|
||||||
|
{SEMICOLON} {printf("%s: SEMICOLON\n", yytext);}
|
||||||
|
{PERIOD} {printf("%s: PERIOD\n", yytext);}
|
||||||
|
{COLON} {printf("%s: COLON\n", yytext);}
|
||||||
|
|
||||||
|
{CHARCON} {printf("%s: CHARCON\n", yytext);}
|
||||||
|
{INTCON} {printf("%s: INTCON\n", yytext);}
|
||||||
|
{IDENT} {printf("%s: IDENT\n", yytext);}
|
||||||
|
{ERROR} {printf("%s: ERROR\n", yytext);}
|
||||||
|
/* end */
|
||||||
|
|
||||||
|
\n {}
|
||||||
|
. {}
|
||||||
|
%%
|
||||||
|
int yywrap() { return 1; }
|
||||||
|
int main(int argc, char **argv)
|
||||||
|
{
|
||||||
|
if (argc > 1) {
|
||||||
|
if (!(yyin = fopen(argv[1], "r"))) {
|
||||||
|
perror(argv[1]);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (yylex());
|
||||||
|
return 0;
|
||||||
|
}
|
14
README.md
Normal file
14
README.md
Normal file
|
@ -0,0 +1,14 @@
|
||||||
|
# Rubbish Bin
|
||||||
|
|
||||||
|
大学四年总有一些时候需要用C++写一些答辩代码。
|
||||||
|
|
||||||
|
## 数据结构实验代码
|
||||||
|
|
||||||
|
- 实验一:约瑟夫问题`josephus`
|
||||||
|
- 实验二:迷宫问题`maze`
|
||||||
|
- 实验三:哈夫曼压缩解压缩搜索`zip-unzip-search`
|
||||||
|
|
||||||
|
## 编译原理实验代码
|
||||||
|
|
||||||
|
- 实验一:词法分析问题`LexicalParser`
|
||||||
|
- 实验二:语法分析问题`GrammarParser`
|
1
josephus/.gitignore
vendored
Normal file
1
josephus/.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
||||||
|
.idea/
|
12
josephus/CMakeLists.txt
Normal file
12
josephus/CMakeLists.txt
Normal file
|
@ -0,0 +1,12 @@
|
||||||
|
cmake_minimum_required(VERSION 3.16)
|
||||||
|
|
||||||
|
set(CMAKE_CXX_STANDARD 11)
|
||||||
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
|
||||||
|
|
||||||
|
project(josephus)
|
||||||
|
|
||||||
|
include_directories(${PROJECT_SOURCE_DIR}/include)
|
||||||
|
|
||||||
|
aux_source_directory(${PROJECT_SOURCE_DIR}/src SRC)
|
||||||
|
|
||||||
|
add_executable(josephus main.cpp ${SRC})
|
82
josephus/include/LinkedList.h
Normal file
82
josephus/include/LinkedList.h
Normal file
|
@ -0,0 +1,82 @@
|
||||||
|
//
|
||||||
|
// Created by ricardo on 9/26/22.
|
||||||
|
//
|
||||||
|
|
||||||
|
#ifndef JOSEPHUS_LINKED_LIST_H
|
||||||
|
#define JOSEPHUS_LINKED_LIST_H
|
||||||
|
#include "cstdlib"
|
||||||
|
#include "cstring"
|
||||||
|
#include "cstdio"
|
||||||
|
|
||||||
|
#include "define.h"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 列表节点结构体
|
||||||
|
*/
|
||||||
|
struct node {
|
||||||
|
int ID;
|
||||||
|
char Name[MAX_NAME_LENGTH];
|
||||||
|
int Age;
|
||||||
|
int Gender;
|
||||||
|
struct node* next;
|
||||||
|
};
|
||||||
|
|
||||||
|
typedef struct node node_t;
|
||||||
|
typedef struct node* node_p;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建循环列表
|
||||||
|
* @param head 头节点地址的引用
|
||||||
|
* @return true 创建成功
|
||||||
|
* @return false 创建失败
|
||||||
|
*/
|
||||||
|
bool init_linked_list(node_p& head);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 销毁链表
|
||||||
|
* @param head 链表头节点的地址
|
||||||
|
*/
|
||||||
|
void destroy_linked_list(node_p& head);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建一个链表中的节点
|
||||||
|
* @param node 新节点地址引用
|
||||||
|
* @param id 人的编号
|
||||||
|
* @param age 人的年龄
|
||||||
|
* @param gender 人的性别
|
||||||
|
* @param name 人的姓名字符串
|
||||||
|
* @return true 创建成功
|
||||||
|
* @return false 创建失败
|
||||||
|
*/
|
||||||
|
bool create_node(node_p& node, int id, int age, int gender, char* name);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在链表的末尾插入新节点
|
||||||
|
* 虽然是循环链表 我们不妨认为头节点前的节点
|
||||||
|
* @param head 链表头节点的引用
|
||||||
|
* @param new_node 需要插入的新节点
|
||||||
|
*/
|
||||||
|
void append_node(const node_p& head, node_p new_node);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从链表中删除指定的节点
|
||||||
|
* @param head 链表头节点的引用
|
||||||
|
* @param target_node 需要删除的目标节点
|
||||||
|
* @return true 删除成功
|
||||||
|
* @return false 删除失败 一般是目标节点非法
|
||||||
|
*/
|
||||||
|
bool delete_node(const node_p& head, node_p target_node);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打印指定节点记录人员的信息
|
||||||
|
* @param node 对指定节点的引用
|
||||||
|
*/
|
||||||
|
void print_node(const node_p& node);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打印链表中每个节点的值
|
||||||
|
* @param head 链表头节点的引用
|
||||||
|
*/
|
||||||
|
void print_linked_list(const node_p& head);
|
||||||
|
|
||||||
|
#endif //JOSEPHUS_LINKED_LIST_H
|
16
josephus/include/define.h
Normal file
16
josephus/include/define.h
Normal file
|
@ -0,0 +1,16 @@
|
||||||
|
//
|
||||||
|
// Created by ricardo on 2022/9/26.
|
||||||
|
//
|
||||||
|
|
||||||
|
#ifndef JOSEPHUS_DEFINE_H
|
||||||
|
#define JOSEPHUS_DEFINE_H
|
||||||
|
// 男性
|
||||||
|
#define MALE 0
|
||||||
|
// 女性
|
||||||
|
#define FEMALE 1
|
||||||
|
|
||||||
|
// 姓名字符串的最大长度
|
||||||
|
#define MAX_NAME_LENGTH 20
|
||||||
|
#define MAX_GENDER_LENGTH 10
|
||||||
|
|
||||||
|
#endif //JOSEPHUS_DEFINE_H
|
8
josephus/input.txt
Normal file
8
josephus/input.txt
Normal file
|
@ -0,0 +1,8 @@
|
||||||
|
6
|
||||||
|
1 zyl male 1
|
||||||
|
2 zzyl male 2
|
||||||
|
3 zzzyl female 3
|
||||||
|
4 zyyl female 4
|
||||||
|
5 zyyyl female 40
|
||||||
|
6 zyll female 45
|
||||||
|
0 4 1
|
135
josephus/main.cpp
Normal file
135
josephus/main.cpp
Normal file
|
@ -0,0 +1,135 @@
|
||||||
|
//
|
||||||
|
// Created by ricardo on 9/26/22.
|
||||||
|
//
|
||||||
|
#include "LinkedList.h"
|
||||||
|
#include "define.h"
|
||||||
|
|
||||||
|
node_p read_input()
|
||||||
|
{
|
||||||
|
int age, id, gender;
|
||||||
|
char name[MAX_NAME_LENGTH];
|
||||||
|
char gender_string[MAX_GENDER_LENGTH];
|
||||||
|
|
||||||
|
// 性别字符串
|
||||||
|
const char* male_string = "male";
|
||||||
|
const char* female_string = "female";
|
||||||
|
|
||||||
|
scanf("%d %s %s %d", &id, name, gender_string, &age);
|
||||||
|
|
||||||
|
// 匹配输入的性别字符串
|
||||||
|
if (strcmp(gender_string, male_string) == 0)
|
||||||
|
{
|
||||||
|
gender = MALE;
|
||||||
|
}
|
||||||
|
else if (strcmp(gender_string, female_string) == 0)
|
||||||
|
{
|
||||||
|
gender = FEMALE;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// 如果匹配失败说明输入非法
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
node_p node;
|
||||||
|
if (create_node(node, id, age, gender, name))
|
||||||
|
{
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
// 存储总共的人数
|
||||||
|
int number;
|
||||||
|
// 链表的头节点
|
||||||
|
node_p head;
|
||||||
|
|
||||||
|
if (!init_linked_list(head))
|
||||||
|
{
|
||||||
|
// 创建链表的头节点
|
||||||
|
// 如果创建失败输出错误信息
|
||||||
|
printf("E: Init linked list failed.\n");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 输入人员列表
|
||||||
|
printf("Hint: Enter number of people join this game:");
|
||||||
|
scanf("%d", &number);
|
||||||
|
printf("Hint: Enter the people information list as id name gender(male|female) age.\n");
|
||||||
|
for (int i = 0; i < number; ++i) {
|
||||||
|
node_p node = read_input();
|
||||||
|
if (node == nullptr)
|
||||||
|
{
|
||||||
|
printf("E: Create Node failed.\n");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
append_node(head, node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 打印人员列表
|
||||||
|
print_linked_list(head);
|
||||||
|
|
||||||
|
// 分别记录游戏开始的位置 中间的间隔 最后剩余的人数
|
||||||
|
int begin, middle, left;
|
||||||
|
printf("Hint: Enter the begin(begin from 0), middle and left people number.\n");
|
||||||
|
scanf("%d %d %d", &begin, &middle, &left);
|
||||||
|
|
||||||
|
node_p node = head->next;
|
||||||
|
// 循环到达游戏开始的位置
|
||||||
|
for (int i = 0; i < begin; ++i) {
|
||||||
|
node = node->next;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 这里有点屎
|
||||||
|
// 由于给定的数据是"间隔"
|
||||||
|
// 在遍历时的次数需要+1
|
||||||
|
// 但是当前被选中的节点会被删除 在删除之间需要将指针下移一位
|
||||||
|
// 遍历的次序又需要-1
|
||||||
|
// 故需要在开始前在指针前移一位
|
||||||
|
node = node->next;
|
||||||
|
while (number > left)
|
||||||
|
{
|
||||||
|
// 游戏开始
|
||||||
|
// 由于middle是间隔
|
||||||
|
for (int i = 0; i < middle; ++i) {
|
||||||
|
if (node == head)
|
||||||
|
{
|
||||||
|
// 由于头节点不存储数据
|
||||||
|
// 遍历到头节点需要多遍历一次
|
||||||
|
i--;
|
||||||
|
}
|
||||||
|
|
||||||
|
node = node->next;
|
||||||
|
}
|
||||||
|
if (node == head)
|
||||||
|
{
|
||||||
|
// 如果恰好在末尾遇到head
|
||||||
|
// 无法在循环中处理
|
||||||
|
node = node->next;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("ID:%d was killed\n", node->ID);
|
||||||
|
node_p target = node;
|
||||||
|
node = node->next;
|
||||||
|
if (!delete_node(head, target))
|
||||||
|
{
|
||||||
|
printf("E: delete node failed.\n");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
number--;
|
||||||
|
}
|
||||||
|
|
||||||
|
print_linked_list(head);
|
||||||
|
|
||||||
|
// 在退出程序之前 释放链表占用的空间
|
||||||
|
destroy_linked_list(head);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
132
josephus/src/LinkedList.cpp
Normal file
132
josephus/src/LinkedList.cpp
Normal file
|
@ -0,0 +1,132 @@
|
||||||
|
//
|
||||||
|
// Created by ricardo on 9/26/22.
|
||||||
|
//
|
||||||
|
#include "LinkedList.h"
|
||||||
|
|
||||||
|
bool init_linked_list(node_p& head)
|
||||||
|
{
|
||||||
|
head = (node_p) malloc(sizeof (node_t));
|
||||||
|
|
||||||
|
if (head == nullptr)
|
||||||
|
{
|
||||||
|
// 空间分配失败
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// 由于是创建循环链表 头节点的下一个节点就是头节点
|
||||||
|
head->next = head;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void destroy_linked_list(node_p& head)
|
||||||
|
{
|
||||||
|
node_p node = head->next;
|
||||||
|
|
||||||
|
// 先循环处理所有不是头节点的节点
|
||||||
|
while (node != head)
|
||||||
|
{
|
||||||
|
node_p temp = node;
|
||||||
|
node = node->next;
|
||||||
|
free(temp);
|
||||||
|
}
|
||||||
|
|
||||||
|
free(head);
|
||||||
|
head = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool create_node(node_p& node, int id, int age, int gender, char* name)
|
||||||
|
{
|
||||||
|
node = (node_p) malloc(sizeof(node_t));
|
||||||
|
|
||||||
|
if (node == nullptr)
|
||||||
|
{
|
||||||
|
// 分配空间失败
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
node->ID = id;
|
||||||
|
node->Age = age;
|
||||||
|
node->Gender = gender;
|
||||||
|
strcpy(node->Name, name);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void append_node(const node_p& head, node_p new_node)
|
||||||
|
{
|
||||||
|
node_p node = head->next;
|
||||||
|
|
||||||
|
// 找到头节点前的一个节点
|
||||||
|
while (node->next != head)
|
||||||
|
{
|
||||||
|
node = node->next;
|
||||||
|
}
|
||||||
|
|
||||||
|
node->next = new_node;
|
||||||
|
new_node->next = head;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool delete_node(const node_p& head, node_p target_node)
|
||||||
|
{
|
||||||
|
if (head == target_node)
|
||||||
|
{
|
||||||
|
// 删除头节点时不可行的
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
node_p node = head;
|
||||||
|
|
||||||
|
while (node->next != target_node)
|
||||||
|
{
|
||||||
|
if (node->next == head)
|
||||||
|
{
|
||||||
|
// 循环完了都没找见
|
||||||
|
// 说明查无此节点
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
node = node->next;
|
||||||
|
}
|
||||||
|
|
||||||
|
node->next = target_node->next;
|
||||||
|
free(target_node);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void print_node(const node_p& node)
|
||||||
|
{
|
||||||
|
if (node == nullptr)
|
||||||
|
{
|
||||||
|
// 指定节点为空
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("ID:%d|", node->ID);
|
||||||
|
printf("Name:%s|", node->Name);
|
||||||
|
printf("Age:%d|", node->Age);
|
||||||
|
if (node->Gender == MALE)
|
||||||
|
{
|
||||||
|
printf("Gender:Male\n");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
printf("Gender:Female\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void print_linked_list(const node_p& head)
|
||||||
|
{
|
||||||
|
if (head == nullptr)
|
||||||
|
{
|
||||||
|
// 头节点为空
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
node_p node = head->next;
|
||||||
|
|
||||||
|
while (node != head)
|
||||||
|
{
|
||||||
|
print_node(node);
|
||||||
|
node = node->next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
3
maze/.gitignore
vendored
Normal file
3
maze/.gitignore
vendored
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
cmake-build-*/
|
||||||
|
build/
|
||||||
|
.idea/
|
10
maze/CMakeLists.txt
Normal file
10
maze/CMakeLists.txt
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
cmake_minimum_required(VERSION 3.16)
|
||||||
|
project(maze)
|
||||||
|
|
||||||
|
set(CMAKE_CXX_STANDARD 11)
|
||||||
|
|
||||||
|
include_directories(${PROJECT_SOURCE_DIR}/include)
|
||||||
|
|
||||||
|
aux_source_directory(${PROJECT_SOURCE_DIR}/src SRCS)
|
||||||
|
|
||||||
|
add_executable(maze main.cpp ${SRCS})
|
71
maze/include/maze_node.h
Normal file
71
maze/include/maze_node.h
Normal file
|
@ -0,0 +1,71 @@
|
||||||
|
//
|
||||||
|
// Created by ricardo on 2022/10/25.
|
||||||
|
//
|
||||||
|
|
||||||
|
#ifndef MAZE_MAZE_NODE_H
|
||||||
|
#define MAZE_MAZE_NODE_H
|
||||||
|
|
||||||
|
// 全局的节点总数变量
|
||||||
|
// 虽然全局变量有点不好
|
||||||
|
extern int node_number;
|
||||||
|
|
||||||
|
struct maze_connect_node
|
||||||
|
{
|
||||||
|
// 连接的节点数组索引
|
||||||
|
int index;
|
||||||
|
struct maze_connect_node* next;
|
||||||
|
};
|
||||||
|
|
||||||
|
typedef struct maze_connect_node maze_connect_node_t;
|
||||||
|
typedef struct maze_connect_node* maze_connect_node_p;
|
||||||
|
|
||||||
|
struct maze_node
|
||||||
|
{
|
||||||
|
// 迷宫中结点的编号
|
||||||
|
int id;
|
||||||
|
// 与这个节点相连的节点链表
|
||||||
|
maze_connect_node_p connect_maze_nodes;
|
||||||
|
// 当前正在遍历的节点
|
||||||
|
maze_connect_node_p now_node;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 迷宫节点结构体
|
||||||
|
typedef struct maze_node maze_node_t;
|
||||||
|
// 迷宫节点结构体指针
|
||||||
|
typedef struct maze_node* maze_node_p;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建迷宫节点数组
|
||||||
|
* @param num 迷宫中节点的数量
|
||||||
|
* @return 数组地址
|
||||||
|
*/
|
||||||
|
maze_node_p create_maze_node_array(int num);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在指定的节点中添加与之相连的节点
|
||||||
|
* @param node 指定的节点引用
|
||||||
|
* @param target 与之相连的节点
|
||||||
|
* @return 是否添加成功
|
||||||
|
*/
|
||||||
|
bool maze_node_add_connect_node(maze_node_t& node, int target);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读取迷宫配置文件
|
||||||
|
* @param filename 配置文件文件名
|
||||||
|
* @return 迷宫节点数组地址
|
||||||
|
*/
|
||||||
|
maze_node_p read_maze_file(char* filename);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打印整个迷宫
|
||||||
|
* @param node_array 迷宫数组
|
||||||
|
*/
|
||||||
|
void print_maze(maze_node_p node_array);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 释放迷宫节点数组占据的空间
|
||||||
|
* @param node_array 迷宫节点数组引用
|
||||||
|
*/
|
||||||
|
void maze_node_free(maze_node_p& node_array);
|
||||||
|
|
||||||
|
#endif //MAZE_MAZE_NODE_H
|
83
maze/include/stack.h
Normal file
83
maze/include/stack.h
Normal file
|
@ -0,0 +1,83 @@
|
||||||
|
//
|
||||||
|
// Created by ricardo on 2022/10/25.
|
||||||
|
//
|
||||||
|
|
||||||
|
#ifndef MAZE_STACK_H
|
||||||
|
#define MAZE_STACK_H
|
||||||
|
|
||||||
|
#include "cstdlib"
|
||||||
|
#include "maze_node.h"
|
||||||
|
|
||||||
|
// 默认的栈大小
|
||||||
|
#define DEFAULT_STACK_LENGTH 200
|
||||||
|
|
||||||
|
// 由于将迷宫中的所有节点都储存在数组中
|
||||||
|
// 存储路径的栈就不用存储节点的指针
|
||||||
|
// 而是直接存储节点在数组中的索引
|
||||||
|
struct stack {
|
||||||
|
int* top;
|
||||||
|
int* base;
|
||||||
|
int stack_size;
|
||||||
|
};
|
||||||
|
|
||||||
|
typedef struct stack stack_t;
|
||||||
|
typedef struct stack* stack_p;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化栈空间
|
||||||
|
* @param s 栈结构体的引用
|
||||||
|
* @return 栈是否创建成功
|
||||||
|
*/
|
||||||
|
bool init_stack(stack_t& s);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断栈是否为空
|
||||||
|
* @param s 对于栈结构体的引用
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
bool stack_is_empty(const stack_t& s);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断栈是否已满
|
||||||
|
* @param s 对于结构体的引用
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
bool stack_is_full(const stack_t& s);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在栈中压入元素
|
||||||
|
* @param s 栈引用
|
||||||
|
* @param value 被压入栈的值
|
||||||
|
* @return 压入栈是否成功
|
||||||
|
*/
|
||||||
|
bool stack_push(stack_t& s, int index);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在栈中弹出元素
|
||||||
|
* @param s 栈引用
|
||||||
|
* @param value 被弹出栈的值
|
||||||
|
* @return 弹出栈是否成功
|
||||||
|
*/
|
||||||
|
bool stack_pop(stack_t& s, int* index);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获得栈底的元素
|
||||||
|
* @param s 栈引用
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
int stack_get_bottom(const stack_t& s);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获得栈顶的元素
|
||||||
|
* @param s 栈引用
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
int stack_get_top(const stack_t& s);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 释放栈所占用的空间
|
||||||
|
* @param s 栈引用
|
||||||
|
*/
|
||||||
|
void stack_free(stack_t& s);
|
||||||
|
|
||||||
|
#endif //MAZE_STACK_H
|
76
maze/main.cpp
Normal file
76
maze/main.cpp
Normal file
|
@ -0,0 +1,76 @@
|
||||||
|
#include "maze_node.h"
|
||||||
|
#include "stack.h"
|
||||||
|
#include "cstdio"
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
char config_file[10] = "maze.txt";
|
||||||
|
maze_node_p node_array = read_maze_file(config_file);
|
||||||
|
print_maze(node_array);
|
||||||
|
|
||||||
|
// 输入迷宫的开始和结束节点
|
||||||
|
int begin_node, end_node;
|
||||||
|
printf("Please enter the start node:\n");
|
||||||
|
scanf("%d", &begin_node);
|
||||||
|
printf("Please enter the end node:\n");
|
||||||
|
scanf("%d", &end_node);
|
||||||
|
|
||||||
|
// 初始化储存路径的栈
|
||||||
|
stack_t path_stack;
|
||||||
|
// 显然栈的最大大小就是迷宫中节点的数量
|
||||||
|
// 但是由于栈判满的原因需要多一个位置
|
||||||
|
path_stack.stack_size = node_number + 1;
|
||||||
|
init_stack(path_stack);
|
||||||
|
|
||||||
|
// 初始化将起点填入栈中
|
||||||
|
stack_push(path_stack, begin_node - 1);
|
||||||
|
|
||||||
|
while (stack_get_top(path_stack) + 1 != end_node)
|
||||||
|
{
|
||||||
|
maze_connect_node_p& node = node_array[stack_get_top(path_stack)].now_node;
|
||||||
|
if (node == nullptr)
|
||||||
|
{
|
||||||
|
// 节点已经遍历完不抱希望了
|
||||||
|
// 这个值仅占位
|
||||||
|
int temp;
|
||||||
|
stack_pop(path_stack, &temp);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// 遍历栈确定目标节点不在栈中
|
||||||
|
bool flag = false;
|
||||||
|
int* p = path_stack.base;
|
||||||
|
while (p != path_stack.top)
|
||||||
|
{
|
||||||
|
if (node->index == *p)
|
||||||
|
{
|
||||||
|
flag = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
p++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!flag)
|
||||||
|
{
|
||||||
|
// 如果在栈中没发现这个节点
|
||||||
|
stack_push(path_stack, node->index);
|
||||||
|
}
|
||||||
|
// 将未探索的节点置为下一个
|
||||||
|
node = node->next;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 打印路径栈
|
||||||
|
int* p = path_stack.base;
|
||||||
|
printf("%d", *p + 1);
|
||||||
|
p++;
|
||||||
|
while (p != path_stack.top)
|
||||||
|
{
|
||||||
|
printf("->%d", *p + 1);
|
||||||
|
p++;
|
||||||
|
}
|
||||||
|
printf("\n");
|
||||||
|
|
||||||
|
stack_free(path_stack);
|
||||||
|
maze_node_free(node_array);
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
20
maze/maze.txt
Normal file
20
maze/maze.txt
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
17
|
||||||
|
1-3
|
||||||
|
2-3
|
||||||
|
3-5
|
||||||
|
3-4
|
||||||
|
3-7
|
||||||
|
3-8
|
||||||
|
4-6
|
||||||
|
7-8
|
||||||
|
7-11
|
||||||
|
8-9
|
||||||
|
8-12
|
||||||
|
9-13
|
||||||
|
11-12
|
||||||
|
12-13
|
||||||
|
13-14
|
||||||
|
14-10
|
||||||
|
13-16
|
||||||
|
16-15
|
||||||
|
16-17
|
110
maze/src/maze_node.cpp
Normal file
110
maze/src/maze_node.cpp
Normal file
|
@ -0,0 +1,110 @@
|
||||||
|
#include "maze_node.h"
|
||||||
|
#include "cstdlib"
|
||||||
|
#include "cstdio"
|
||||||
|
|
||||||
|
int node_number;
|
||||||
|
|
||||||
|
maze_node_p create_maze_node_array(int num)
|
||||||
|
{
|
||||||
|
auto node = (maze_node_p) malloc(num * sizeof(maze_node_t));
|
||||||
|
maze_node_p p = node;
|
||||||
|
for (int i = 1; i <= num; ++i) {
|
||||||
|
p->id = i;
|
||||||
|
p->connect_maze_nodes = nullptr;
|
||||||
|
p++;
|
||||||
|
}
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool maze_node_add_connect_node(maze_node_t& node, int target)
|
||||||
|
{
|
||||||
|
auto new_node = (maze_connect_node_p) malloc(sizeof(maze_connect_node_t));
|
||||||
|
if (new_node == nullptr)
|
||||||
|
{
|
||||||
|
// 分配空间失败
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
new_node->next = nullptr;
|
||||||
|
new_node->index = target;
|
||||||
|
|
||||||
|
if (node.connect_maze_nodes == nullptr)
|
||||||
|
{
|
||||||
|
node.connect_maze_nodes = new_node;
|
||||||
|
// 遍历链表总是从头开始
|
||||||
|
node.now_node = new_node;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
maze_connect_node_p connect_node = node.connect_maze_nodes;
|
||||||
|
|
||||||
|
while (connect_node->next != nullptr)
|
||||||
|
{
|
||||||
|
// 找到链表末节点
|
||||||
|
connect_node = connect_node->next;
|
||||||
|
}
|
||||||
|
|
||||||
|
connect_node->next = new_node;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
maze_node_p read_maze_file(char* filename)
|
||||||
|
{
|
||||||
|
FILE* config_file;
|
||||||
|
char buffer[10];
|
||||||
|
|
||||||
|
config_file = fopen(filename, "r");
|
||||||
|
|
||||||
|
// 配置文件的第一行要求是迷宫中节点的总数
|
||||||
|
fgets(buffer, sizeof buffer, config_file);
|
||||||
|
char* point;
|
||||||
|
node_number = (int )strtol(buffer, &point, 10);
|
||||||
|
|
||||||
|
maze_node_p node_array = create_maze_node_array(node_number);
|
||||||
|
|
||||||
|
while (fgets(buffer, sizeof buffer, config_file) != nullptr)
|
||||||
|
{
|
||||||
|
int node1, node2;
|
||||||
|
sscanf(buffer, "%d-%d", &node1, &node2);
|
||||||
|
|
||||||
|
// 数组中的索引总是比编号小1
|
||||||
|
maze_node_add_connect_node(node_array[node1 - 1], node2 - 1);
|
||||||
|
maze_node_add_connect_node(node_array[node2 - 1], node1 - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
fclose(config_file);
|
||||||
|
|
||||||
|
return node_array;
|
||||||
|
}
|
||||||
|
|
||||||
|
void print_maze(maze_node_p node_array)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < node_number; ++i) {
|
||||||
|
maze_node_t node = node_array[i];
|
||||||
|
maze_connect_node_p p = node.connect_maze_nodes;
|
||||||
|
while (p != nullptr)
|
||||||
|
{
|
||||||
|
printf("%d->%d\n", node.id, node_array[p->index].id);
|
||||||
|
p = p->next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void maze_node_free(maze_node_p& node_array)
|
||||||
|
{
|
||||||
|
for(int i = 0; i < node_number; i++)
|
||||||
|
{
|
||||||
|
maze_connect_node_p node = node_array[i].connect_maze_nodes;
|
||||||
|
while (node != nullptr)
|
||||||
|
{
|
||||||
|
maze_connect_node_p temp = node;
|
||||||
|
node = node->next;
|
||||||
|
free(temp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
free(node_array);
|
||||||
|
node_array = nullptr;
|
||||||
|
}
|
81
maze/src/stack.cpp
Normal file
81
maze/src/stack.cpp
Normal file
|
@ -0,0 +1,81 @@
|
||||||
|
//
|
||||||
|
// Created by ricardo on 2022/10/25.
|
||||||
|
//
|
||||||
|
#include "stack.h"
|
||||||
|
|
||||||
|
bool init_stack(stack_t& s)
|
||||||
|
{
|
||||||
|
if (s.stack_size == 0)
|
||||||
|
{
|
||||||
|
// 如果没有设置栈的大小
|
||||||
|
// 就设置为默认大小
|
||||||
|
s.stack_size = DEFAULT_STACK_LENGTH;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto p = (int* ) malloc(sizeof(int));
|
||||||
|
if (p == nullptr)
|
||||||
|
{
|
||||||
|
// 空间分配失败
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
s.base = p;
|
||||||
|
s.top = p;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool stack_is_empty(const stack& s)
|
||||||
|
{
|
||||||
|
return s.base == s.top;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool stack_is_full(const stack& s)
|
||||||
|
{
|
||||||
|
return s.base + s.stack_size == s.top;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool stack_push(stack& s,int index)
|
||||||
|
{
|
||||||
|
if (stack_is_full(s))
|
||||||
|
{
|
||||||
|
// 栈已满
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
*s.top = index;
|
||||||
|
s.top++;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool stack_pop(stack& s, int* index)
|
||||||
|
{
|
||||||
|
if (stack_is_empty(s))
|
||||||
|
{
|
||||||
|
// 栈为空
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
*index = *s.top;
|
||||||
|
s.top--;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
int stack_get_bottom(const stack_t& s)
|
||||||
|
{
|
||||||
|
return *s.base;
|
||||||
|
}
|
||||||
|
|
||||||
|
int stack_get_top(const stack_t& s)
|
||||||
|
{
|
||||||
|
return *(s.top-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
void stack_free(stack_t& s)
|
||||||
|
{
|
||||||
|
free(s.base);
|
||||||
|
s.base = nullptr;
|
||||||
|
s.top = nullptr;
|
||||||
|
s.stack_size = 0;
|
||||||
|
}
|
3
zip-unzip-search/.gitignore
vendored
Normal file
3
zip-unzip-search/.gitignore
vendored
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
.idea/
|
||||||
|
cmake-*/
|
||||||
|
build/
|
10
zip-unzip-search/CMakeLists.txt
Normal file
10
zip-unzip-search/CMakeLists.txt
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
cmake_minimum_required(VERSION 3.22)
|
||||||
|
project(zip_unzip_search)
|
||||||
|
|
||||||
|
set(CMAKE_CXX_STANDARD 11)
|
||||||
|
|
||||||
|
include_directories(${PROJECT_SOURCE_DIR}/include)
|
||||||
|
|
||||||
|
aux_source_directory(${PROJECT_SOURCE_DIR}/src SRCS)
|
||||||
|
|
||||||
|
add_executable(zip_unzip_search main.cpp ${SRCS})
|
11
zip-unzip-search/include/const.h
Normal file
11
zip-unzip-search/include/const.h
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
//
|
||||||
|
// Created by ricardo on 22-12-11.
|
||||||
|
//
|
||||||
|
|
||||||
|
#ifndef ZIP_UNZIP_SEARCH_CONST_H
|
||||||
|
#define ZIP_UNZIP_SEARCH_CONST_H
|
||||||
|
|
||||||
|
// ASCII码的长度
|
||||||
|
#define ASCII_LENGTH 128
|
||||||
|
|
||||||
|
#endif //ZIP_UNZIP_SEARCH_CONST_H
|
82
zip-unzip-search/include/file_io.h
Normal file
82
zip-unzip-search/include/file_io.h
Normal file
|
@ -0,0 +1,82 @@
|
||||||
|
//
|
||||||
|
// Created by ricardo on 22-12-11.
|
||||||
|
//
|
||||||
|
|
||||||
|
#ifndef ZIP_UNZIP_SEARCH_FILE_IO_H
|
||||||
|
#define ZIP_UNZIP_SEARCH_FILE_IO_H
|
||||||
|
#include "string"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件元信息
|
||||||
|
*/
|
||||||
|
struct MetaData
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* 哈夫曼树节点数组长度
|
||||||
|
*/
|
||||||
|
int HuffmanNodeLength;
|
||||||
|
/**
|
||||||
|
* 哈夫曼树根节点长度
|
||||||
|
*/
|
||||||
|
int HuffmanRoot;
|
||||||
|
/**
|
||||||
|
* 文件中最后一个缓冲区被使用的位数
|
||||||
|
*/
|
||||||
|
int LastBufferUsedLength;
|
||||||
|
};
|
||||||
|
|
||||||
|
class FileIO
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
/**
|
||||||
|
* 统计文件的字符的出现频率
|
||||||
|
* @param fileName 文件名称
|
||||||
|
* @return 字符频率数组 需要delete
|
||||||
|
*/
|
||||||
|
static int* ReadCharFrequency(const std::string& fileName);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 写入压缩文件
|
||||||
|
* @param inputFile 被压缩文件名称
|
||||||
|
* @param outputFile 输出压缩文件名称
|
||||||
|
*/
|
||||||
|
static void WriteZipFile(const std::string& inputFile, const std::string& outputFile);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 写入解压缩文件
|
||||||
|
* @param inputFile 压缩文件名称
|
||||||
|
* @param outputFile 解压文件名称
|
||||||
|
*/
|
||||||
|
static void WriteUnzipFile(const std::string& inputFile, const std::string& outputFile);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算文件的压缩率
|
||||||
|
* @param inputFileName
|
||||||
|
* @param outputFileName
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
static double CalculateZipRate(const std::string& inputFileName, const std::string& outputFileName);
|
||||||
|
};
|
||||||
|
|
||||||
|
class BinaryBuffer
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
explicit BinaryBuffer(std::string& inputFileName);
|
||||||
|
|
||||||
|
~BinaryBuffer();
|
||||||
|
|
||||||
|
char read();
|
||||||
|
|
||||||
|
int position = 0;
|
||||||
|
|
||||||
|
private:
|
||||||
|
FILE* file = nullptr;
|
||||||
|
|
||||||
|
int buffer;
|
||||||
|
int bufferPos;
|
||||||
|
bool readFinishedFlag;
|
||||||
|
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif //ZIP_UNZIP_SEARCH_FILE_IO_H
|
103
zip-unzip-search/include/huffman.h
Normal file
103
zip-unzip-search/include/huffman.h
Normal file
|
@ -0,0 +1,103 @@
|
||||||
|
//
|
||||||
|
// Created by ricardo on 22-12-11.
|
||||||
|
//
|
||||||
|
|
||||||
|
#ifndef ZIP_UNZIP_SEARCH_HUFFMAN_H
|
||||||
|
#define ZIP_UNZIP_SEARCH_HUFFMAN_H
|
||||||
|
#include "vector"
|
||||||
|
#include "array"
|
||||||
|
#include "const.h"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 哈夫曼树中的节点结构体
|
||||||
|
*/
|
||||||
|
struct HuffmanNode
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* 节点的编号
|
||||||
|
*/
|
||||||
|
int id;
|
||||||
|
/**
|
||||||
|
* 节点表示的字符
|
||||||
|
* 如果不是叶子节点
|
||||||
|
* 值为-1
|
||||||
|
*/
|
||||||
|
char data;
|
||||||
|
/**
|
||||||
|
* 字符在文件中出现的频率
|
||||||
|
* 也就是哈夫曼树中节点的权值
|
||||||
|
*/
|
||||||
|
int frequency;
|
||||||
|
/**
|
||||||
|
* 左子结点在节点数组中的索引
|
||||||
|
*/
|
||||||
|
int lIndex;
|
||||||
|
/**
|
||||||
|
* 右子结点在节点中的索引
|
||||||
|
*/
|
||||||
|
int rIndex;
|
||||||
|
};
|
||||||
|
|
||||||
|
class HuffmanCode
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
/**
|
||||||
|
* 树中节点列表
|
||||||
|
*/
|
||||||
|
std::vector<HuffmanNode>* nodes = new std::vector<HuffmanNode>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 哈夫曼树根节点索引
|
||||||
|
*/
|
||||||
|
int root = -1;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从字符的频率数组出发创建
|
||||||
|
* @param frequencyArray
|
||||||
|
*/
|
||||||
|
explicit HuffmanCode(const int * frequencyArray);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从哈夫曼数组节点出发创建
|
||||||
|
* @param nodeArray 哈夫曼节点数组
|
||||||
|
* @param length 节点数组的长度
|
||||||
|
*/
|
||||||
|
HuffmanCode(HuffmanNode *nodeArray, int length);
|
||||||
|
|
||||||
|
~HuffmanCode();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建哈夫曼树
|
||||||
|
*/
|
||||||
|
void createHuffmanTree();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打印哈夫曼树
|
||||||
|
*/
|
||||||
|
void printHuffmanTree();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 得到哈夫曼编码
|
||||||
|
* @return 哈夫曼编码字典
|
||||||
|
*/
|
||||||
|
std::array<std::vector<char>, ASCII_LENGTH> * getHuffmanCode();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打印哈夫曼编码字典
|
||||||
|
* @param dictionary 字典
|
||||||
|
*/
|
||||||
|
static void printHuffmanCode(const std::array<std::vector<char>, ASCII_LENGTH>& dictionary);
|
||||||
|
|
||||||
|
private:
|
||||||
|
/**
|
||||||
|
* 对森林列表按权值排序
|
||||||
|
* @param forests
|
||||||
|
*/
|
||||||
|
static void sortForests(std::vector<HuffmanNode>& forests);
|
||||||
|
|
||||||
|
void printHuffmanTreeR(int nodeId);
|
||||||
|
|
||||||
|
void getHuffmanCodeR(std::array<std::vector<char>, ASCII_LENGTH> &dictionary, int nodeId, std::vector<char> &code);
|
||||||
|
|
||||||
|
};
|
||||||
|
#endif //ZIP_UNZIP_SEARCH_HUFFMAN_H
|
31
zip-unzip-search/include/logging.h
Normal file
31
zip-unzip-search/include/logging.h
Normal file
|
@ -0,0 +1,31 @@
|
||||||
|
//
|
||||||
|
// Created by ricardo on 22-12-11.
|
||||||
|
//
|
||||||
|
|
||||||
|
#ifndef ZIP_UNZIP_SEARCH_LOGGING_H
|
||||||
|
#define ZIP_UNZIP_SEARCH_LOGGING_H
|
||||||
|
#include "string"
|
||||||
|
|
||||||
|
class Logging
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
/**
|
||||||
|
* 输出信息
|
||||||
|
* @param info
|
||||||
|
*/
|
||||||
|
static void LoggingInfo(const std::string& info);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 输出警告
|
||||||
|
* @param warning
|
||||||
|
*/
|
||||||
|
static void LoggingWarning(const std::string& warning);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 输出错误
|
||||||
|
* @param error
|
||||||
|
*/
|
||||||
|
static void LoggingError(const std::string& error);
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif //ZIP_UNZIP_SEARCH_LOGGING_H
|
55
zip-unzip-search/include/search.h
Normal file
55
zip-unzip-search/include/search.h
Normal file
|
@ -0,0 +1,55 @@
|
||||||
|
//
|
||||||
|
// Created by ricardo on 22-12-16.
|
||||||
|
//
|
||||||
|
|
||||||
|
#ifndef ZIP_UNZIP_SEARCH_SEARCH_H
|
||||||
|
#define ZIP_UNZIP_SEARCH_SEARCH_H
|
||||||
|
#include "vector"
|
||||||
|
#include "array"
|
||||||
|
#include "string"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* BM算法搜索实现类
|
||||||
|
*/
|
||||||
|
class BMSearch
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
explicit BMSearch(std::vector<char>& sample);
|
||||||
|
|
||||||
|
~BMSearch();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 匹配二进制文件
|
||||||
|
* @param fileName 指向需要进行匹配的二进制文件 需要读取元信息和哈夫曼数组
|
||||||
|
*/
|
||||||
|
void matchFile(std::string &fileName);
|
||||||
|
|
||||||
|
private:
|
||||||
|
// 坏字符规则数组
|
||||||
|
// 字符串为01串
|
||||||
|
int* badCharArray;
|
||||||
|
|
||||||
|
// 好后缀规则数组
|
||||||
|
int* goodSuffixArray;
|
||||||
|
|
||||||
|
std::vector<char>* sample;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成坏字符数组
|
||||||
|
* @param s 模板字符串
|
||||||
|
*/
|
||||||
|
void generateBrokenCharArray(std::vector<char>& s);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成好后缀数组
|
||||||
|
* @param s 模板字符串
|
||||||
|
*/
|
||||||
|
void generateGoodSuffixArray(std::vector<char>& s);
|
||||||
|
|
||||||
|
static int max(int a, int b);
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
void SearchInFile(char* fileName, char* sample);
|
||||||
|
|
||||||
|
#endif //ZIP_UNZIP_SEARCH_SEARCH_H
|
67
zip-unzip-search/main.cpp
Normal file
67
zip-unzip-search/main.cpp
Normal file
|
@ -0,0 +1,67 @@
|
||||||
|
#include "file_io.h"
|
||||||
|
#include "logging.h"
|
||||||
|
#include "cstring"
|
||||||
|
#include "search.h"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 输出帮助信息
|
||||||
|
*/
|
||||||
|
void PrintHelpMessage()
|
||||||
|
{
|
||||||
|
printf("Usage: \n");
|
||||||
|
printf("Zip File: -z [In-File-Name] [Out-File-Name]\n");
|
||||||
|
printf("Unzip File: -u [In-File-Name] [Out-File-Name]\n");
|
||||||
|
printf("Search In Zip File: -s [Zip-File-Name] [Sample-String]\n");
|
||||||
|
printf("Print Help Message: -h\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
int main(int argc, char *argv[])
|
||||||
|
{
|
||||||
|
if (argc == 4)
|
||||||
|
{
|
||||||
|
std::string inputFileName = std::string(argv[2]);
|
||||||
|
std::string outputFileName = std::string(argv[3]);
|
||||||
|
|
||||||
|
if (strcmp(argv[1], "-z") == 0)
|
||||||
|
{
|
||||||
|
Logging::LoggingInfo("Start Zip File: " + inputFileName + " to zip file: " + outputFileName);
|
||||||
|
|
||||||
|
FileIO::WriteZipFile(inputFileName, outputFileName);
|
||||||
|
|
||||||
|
double zipRate = FileIO::CalculateZipRate(inputFileName, outputFileName) * 100.0;
|
||||||
|
Logging::LoggingInfo("The Zip Rate is: " + std::to_string(zipRate) + "%");
|
||||||
|
Logging::LoggingInfo("Zip Success!");
|
||||||
|
}
|
||||||
|
else if(strcmp(argv[1], "-u") == 0)
|
||||||
|
{
|
||||||
|
Logging::LoggingInfo("Start Unzip File: " + inputFileName + " to text file: " + outputFileName);
|
||||||
|
|
||||||
|
FileIO::WriteUnzipFile(inputFileName, outputFileName);
|
||||||
|
|
||||||
|
Logging::LoggingInfo("Unzip Success!");
|
||||||
|
}
|
||||||
|
else if(strcmp(argv[1], "-s") == 0)
|
||||||
|
{
|
||||||
|
Logging::LoggingInfo("Start to search in file " + inputFileName);
|
||||||
|
SearchInFile(argv[2], argv[3]);
|
||||||
|
Logging::LoggingInfo("Search finished");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
printf("Unknown Usage!\n");
|
||||||
|
PrintHelpMessage();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (argc == 2 && strcmp(argv[1], "-h") == 0)
|
||||||
|
{
|
||||||
|
PrintHelpMessage();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
printf("Unknown Usage!\n");
|
||||||
|
PrintHelpMessage();
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
307
zip-unzip-search/src/file_io.cpp
Normal file
307
zip-unzip-search/src/file_io.cpp
Normal file
|
@ -0,0 +1,307 @@
|
||||||
|
//
|
||||||
|
// Created by ricardo on 22-12-11.
|
||||||
|
//
|
||||||
|
#include "file_io.h"
|
||||||
|
#include "logging.h"
|
||||||
|
#include "cstdio"
|
||||||
|
#include "cstdlib"
|
||||||
|
#include "const.h"
|
||||||
|
#include "huffman.h"
|
||||||
|
#include "unistd.h"
|
||||||
|
#include "sys/stat.h"
|
||||||
|
|
||||||
|
int *FileIO::ReadCharFrequency(const std::string &fileName)
|
||||||
|
{
|
||||||
|
FILE *file = fopen(fileName.c_str(), "r");
|
||||||
|
|
||||||
|
if (file == nullptr)
|
||||||
|
{
|
||||||
|
// 文件打开失败
|
||||||
|
Logging::LoggingInfo(fileName + "is not a valid filename");
|
||||||
|
exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
int* frequencyArray = new int[ASCII_LENGTH];
|
||||||
|
|
||||||
|
for (int i = 0; i < ASCII_LENGTH; i++)
|
||||||
|
{
|
||||||
|
// 将所有频率初始化为0
|
||||||
|
frequencyArray[i] = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
int temp = fgetc(file);
|
||||||
|
|
||||||
|
if (temp == EOF)
|
||||||
|
{
|
||||||
|
// 文件结束
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (temp >= ASCII_LENGTH || temp < 0)
|
||||||
|
{
|
||||||
|
// 读取到非法字符
|
||||||
|
Logging::LoggingWarning(
|
||||||
|
"Read illegal char " + std::to_string(temp) + " in file. Ignore it");
|
||||||
|
}
|
||||||
|
|
||||||
|
frequencyArray[temp]++;
|
||||||
|
}
|
||||||
|
|
||||||
|
fclose(file);
|
||||||
|
return frequencyArray;
|
||||||
|
}
|
||||||
|
|
||||||
|
void FileIO::WriteZipFile(const std::string &inputFile, const std::string &outputFile)
|
||||||
|
{
|
||||||
|
int* frequencyArray = FileIO::ReadCharFrequency(inputFile);
|
||||||
|
|
||||||
|
auto huffmanCode = new HuffmanCode(frequencyArray);
|
||||||
|
// 创建哈夫曼树
|
||||||
|
huffmanCode->createHuffmanTree();
|
||||||
|
auto dictionary = huffmanCode->getHuffmanCode();
|
||||||
|
|
||||||
|
FILE* input = fopen(inputFile.c_str(), "r");
|
||||||
|
FILE* output = fopen(outputFile.c_str(), "wb");
|
||||||
|
|
||||||
|
// 判断文件打开ia是否成功
|
||||||
|
if (input == nullptr)
|
||||||
|
{
|
||||||
|
Logging::LoggingError(inputFile + " is not an valid file name.");
|
||||||
|
exit(0);
|
||||||
|
}
|
||||||
|
if (output == nullptr)
|
||||||
|
{
|
||||||
|
Logging::LoggingError(outputFile + " is not an valid file name.");
|
||||||
|
exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 首先写入文件的元信息
|
||||||
|
// 虽然目前元信息中部分信息还没有拿到
|
||||||
|
// 但是先把文件中的空间占据了再说
|
||||||
|
MetaData metaDataT{};
|
||||||
|
fwrite(&metaDataT, sizeof(MetaData), 1, output);
|
||||||
|
|
||||||
|
// 写入哈夫曼数组
|
||||||
|
fwrite(huffmanCode->nodes->data(), sizeof(HuffmanNode), huffmanCode->nodes->size(), output);
|
||||||
|
|
||||||
|
// 写入文件时的缓冲区
|
||||||
|
int buffer = 0;
|
||||||
|
int bufferPos = 0;
|
||||||
|
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
int temp = fgetc(input);
|
||||||
|
|
||||||
|
// 读取到文件末尾
|
||||||
|
if (temp == EOF)
|
||||||
|
{
|
||||||
|
|
||||||
|
buffer = buffer << (32 - bufferPos);
|
||||||
|
fwrite(&buffer, sizeof(int), 1, output);
|
||||||
|
|
||||||
|
metaDataT.LastBufferUsedLength = bufferPos;
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (temp >= ASCII_LENGTH || temp < 0)
|
||||||
|
{
|
||||||
|
// 读取到非法字符
|
||||||
|
Logging::LoggingWarning(
|
||||||
|
"Read illegal char " + std::to_string(temp) + " in file. Ignore it");
|
||||||
|
}
|
||||||
|
|
||||||
|
auto code = (*dictionary)[temp];
|
||||||
|
|
||||||
|
for (auto iter = code.begin(); iter < code.end(); iter++)
|
||||||
|
{
|
||||||
|
// 缓冲区已经满了
|
||||||
|
if (bufferPos == 32)
|
||||||
|
{
|
||||||
|
fwrite(&buffer, sizeof(int), 1, output);
|
||||||
|
bufferPos = 0;
|
||||||
|
buffer = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
buffer = (buffer << 1) + *iter;
|
||||||
|
bufferPos++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
metaDataT.HuffmanRoot = huffmanCode->root;
|
||||||
|
metaDataT.HuffmanNodeLength = (int )huffmanCode->nodes->size();
|
||||||
|
// 写入元信息
|
||||||
|
fseek(output, 0, SEEK_SET);
|
||||||
|
fwrite(&metaDataT, sizeof(MetaData), 1, output);
|
||||||
|
|
||||||
|
delete frequencyArray;
|
||||||
|
delete huffmanCode;
|
||||||
|
delete dictionary;
|
||||||
|
}
|
||||||
|
|
||||||
|
void FileIO::WriteUnzipFile(const std::string &inputFile, const std::string &outputFile)
|
||||||
|
{
|
||||||
|
FILE* input = fopen(inputFile.c_str(), "rb");
|
||||||
|
FILE* output = fopen(outputFile.c_str(), "w");
|
||||||
|
|
||||||
|
// 检查文件是否正常打开
|
||||||
|
if (input == nullptr)
|
||||||
|
{
|
||||||
|
Logging::LoggingError(inputFile + " is not a valid file name.");
|
||||||
|
exit(0);
|
||||||
|
}
|
||||||
|
if (output == nullptr)
|
||||||
|
{
|
||||||
|
Logging::LoggingError(outputFile + " is not a valid file name.");
|
||||||
|
exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 读取元信息
|
||||||
|
MetaData metaData{};
|
||||||
|
fread(&metaData, sizeof(MetaData), 1, input);
|
||||||
|
|
||||||
|
// 读取哈夫曼节点数组
|
||||||
|
auto nodes = new HuffmanNode[metaData.HuffmanNodeLength];
|
||||||
|
fread(nodes, sizeof(HuffmanNode), metaData.HuffmanNodeLength, input);
|
||||||
|
|
||||||
|
// 读取文件的缓冲区
|
||||||
|
int buffer;
|
||||||
|
fread(&buffer, sizeof(int), 1, input);
|
||||||
|
int bufferPos;
|
||||||
|
int nextBuffer;
|
||||||
|
|
||||||
|
HuffmanNode node = nodes[metaData.HuffmanRoot];
|
||||||
|
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
if (buffer == EOF)
|
||||||
|
{
|
||||||
|
// 读取结束
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 这里为了处理最后一个缓冲区的问题
|
||||||
|
// 设置了双缓冲
|
||||||
|
size_t readResult = fread(&nextBuffer, sizeof(int), 1, input);
|
||||||
|
|
||||||
|
if (readResult != 1)
|
||||||
|
{
|
||||||
|
// 读取到文件末尾
|
||||||
|
nextBuffer = EOF;
|
||||||
|
bufferPos = metaData.LastBufferUsedLength;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
bufferPos = 32;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (bufferPos > 0)
|
||||||
|
{
|
||||||
|
if (node.data == -1)
|
||||||
|
{
|
||||||
|
// 非叶子节点
|
||||||
|
int value = (buffer >> 31) & 1;
|
||||||
|
buffer = buffer << 1;
|
||||||
|
bufferPos--;
|
||||||
|
|
||||||
|
if (value == 0)
|
||||||
|
{
|
||||||
|
node = nodes[node.lIndex];
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
node = nodes[node.rIndex];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// 叶子节点
|
||||||
|
fputc(node.data, output);
|
||||||
|
node = nodes[metaData.HuffmanRoot];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
buffer = nextBuffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
delete[] nodes;
|
||||||
|
fclose(input);
|
||||||
|
fclose(output);
|
||||||
|
}
|
||||||
|
|
||||||
|
double FileIO::CalculateZipRate(const std::string &inputFileName, const std::string &outputFileName)
|
||||||
|
{
|
||||||
|
struct stat originFileStat{};
|
||||||
|
struct stat zipFileStat{};
|
||||||
|
|
||||||
|
stat(inputFileName.c_str(), &originFileStat);
|
||||||
|
stat(outputFileName.c_str(), &zipFileStat);
|
||||||
|
|
||||||
|
auto originFileSize = (double )originFileStat.st_size;
|
||||||
|
auto zipFileSize = (double )zipFileStat.st_size;
|
||||||
|
|
||||||
|
return zipFileSize / originFileSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
BinaryBuffer::BinaryBuffer(std::string &inputFileName)
|
||||||
|
{
|
||||||
|
file = fopen(inputFileName.c_str(), "rb");
|
||||||
|
|
||||||
|
if (file == nullptr)
|
||||||
|
{
|
||||||
|
// 读取文件失败
|
||||||
|
Logging::LoggingError(inputFileName + " is not a valid file name.");
|
||||||
|
exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
buffer = 0;
|
||||||
|
bufferPos = 0;
|
||||||
|
readFinishedFlag = false;
|
||||||
|
|
||||||
|
// 读取文件开头的元信息和哈夫曼数组
|
||||||
|
MetaData metaData{};
|
||||||
|
fread(&metaData, sizeof(MetaData), 1, file);
|
||||||
|
position = position + (int )sizeof(MetaData) * 8;
|
||||||
|
|
||||||
|
// 读取哈夫曼节点数组
|
||||||
|
HuffmanNode nodes[metaData.HuffmanNodeLength];
|
||||||
|
fread(nodes, sizeof(HuffmanNode), metaData.HuffmanNodeLength, file);
|
||||||
|
position = position + (int )sizeof(HuffmanNode) * metaData.HuffmanNodeLength * 8;
|
||||||
|
}
|
||||||
|
|
||||||
|
BinaryBuffer::~BinaryBuffer()
|
||||||
|
{
|
||||||
|
fclose(file);
|
||||||
|
file = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
char BinaryBuffer::read()
|
||||||
|
{
|
||||||
|
if (readFinishedFlag)
|
||||||
|
{
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bufferPos == 0)
|
||||||
|
{
|
||||||
|
// 当前缓冲区读取结束
|
||||||
|
int result = (int )fread(&buffer, sizeof(int), 1, file);
|
||||||
|
|
||||||
|
if (result == 0)
|
||||||
|
{
|
||||||
|
readFinishedFlag = true;
|
||||||
|
// 文件读取结束
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
bufferPos = 32;
|
||||||
|
}
|
||||||
|
|
||||||
|
int result = (buffer >> 31) & 1;
|
||||||
|
buffer = buffer << 1;
|
||||||
|
bufferPos--;
|
||||||
|
position++;
|
||||||
|
return (char )result;
|
||||||
|
}
|
176
zip-unzip-search/src/huffman.cpp
Normal file
176
zip-unzip-search/src/huffman.cpp
Normal file
|
@ -0,0 +1,176 @@
|
||||||
|
//
|
||||||
|
// Created by ricardo on 22-12-11.
|
||||||
|
//
|
||||||
|
#include "huffman.h"
|
||||||
|
#include "const.h"
|
||||||
|
#include "cstdio"
|
||||||
|
|
||||||
|
HuffmanCode::HuffmanCode(const int *frequencyArray)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < ASCII_LENGTH; i++)
|
||||||
|
{
|
||||||
|
HuffmanNode node{};
|
||||||
|
node.data = (char )i;
|
||||||
|
node.frequency = frequencyArray[i];
|
||||||
|
node.id = i;
|
||||||
|
node.lIndex = -1;
|
||||||
|
node.rIndex = -1;
|
||||||
|
|
||||||
|
nodes->push_back(node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
HuffmanCode::HuffmanCode(HuffmanNode *nodeArray, int length)
|
||||||
|
{
|
||||||
|
delete nodes;
|
||||||
|
|
||||||
|
nodes = new std::vector<HuffmanNode>(nodeArray, nodeArray + length);
|
||||||
|
}
|
||||||
|
|
||||||
|
HuffmanCode::~HuffmanCode()
|
||||||
|
{
|
||||||
|
delete nodes;
|
||||||
|
}
|
||||||
|
|
||||||
|
void HuffmanCode::sortForests(std::vector<HuffmanNode> &forests)
|
||||||
|
{
|
||||||
|
std::size_t length = forests.size();
|
||||||
|
bool sorted = false;
|
||||||
|
|
||||||
|
for (std::size_t i = 1; i < length and !sorted; i++)
|
||||||
|
{
|
||||||
|
sorted = true;
|
||||||
|
|
||||||
|
for (std::size_t j = 0; j < length - i; j++)
|
||||||
|
{
|
||||||
|
if (forests[j].frequency > forests[j + 1].frequency)
|
||||||
|
{
|
||||||
|
HuffmanNode node = forests[j];
|
||||||
|
forests[j] = forests[j + 1];
|
||||||
|
forests[j + 1] = node;
|
||||||
|
sorted = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void HuffmanCode::createHuffmanTree()
|
||||||
|
{
|
||||||
|
auto forests = new std::vector<HuffmanNode>(*nodes);
|
||||||
|
// 节点数组里的编号
|
||||||
|
int pos = (*nodes).rbegin()->id + 1;
|
||||||
|
|
||||||
|
while (forests->size() != 1)
|
||||||
|
{
|
||||||
|
// 反复执行建树的过程
|
||||||
|
sortForests(*forests);
|
||||||
|
|
||||||
|
HuffmanNode node{};
|
||||||
|
node.frequency = (*forests)[0].frequency + (*forests)[1].frequency;
|
||||||
|
node.data = -1;
|
||||||
|
// 权值大的节点为左子结点
|
||||||
|
// 权值小的节点为右子结点
|
||||||
|
node.rIndex = (*forests)[0].id;
|
||||||
|
node.lIndex = (*forests)[1].id;
|
||||||
|
node.id = pos;
|
||||||
|
pos++;
|
||||||
|
nodes->push_back(node);
|
||||||
|
|
||||||
|
// 在森里中删除已经合并的两棵树
|
||||||
|
// 新建一颗树
|
||||||
|
forests->erase(forests->begin(), forests->begin() + 2);
|
||||||
|
forests->push_back(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
root = forests->begin()->id;
|
||||||
|
delete forests;
|
||||||
|
}
|
||||||
|
|
||||||
|
void HuffmanCode::printHuffmanTree()
|
||||||
|
{
|
||||||
|
if (root == -1)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
printHuffmanTreeR(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
void HuffmanCode::printHuffmanTreeR(int nodeId)
|
||||||
|
{
|
||||||
|
HuffmanNode node = (*nodes)[nodeId];
|
||||||
|
|
||||||
|
// 不打印权值为0的节点
|
||||||
|
if (node.lIndex != -1 and node.frequency != 0)
|
||||||
|
{
|
||||||
|
printf("%d %d\n", node.id, node.lIndex);
|
||||||
|
printHuffmanTreeR(node.lIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (node.rIndex != -1 and node.frequency != 0)
|
||||||
|
{
|
||||||
|
printf("%d %d\n", node.id, node.rIndex);
|
||||||
|
printHuffmanTreeR(node.rIndex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::array<std::vector<char>, 128> * HuffmanCode::getHuffmanCode()
|
||||||
|
{
|
||||||
|
if (root == -1)
|
||||||
|
{
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto dictionary = new std::array<std::vector<char>, ASCII_LENGTH>();
|
||||||
|
|
||||||
|
std::vector<char> code;
|
||||||
|
|
||||||
|
getHuffmanCodeR(*dictionary, root, code);
|
||||||
|
|
||||||
|
return dictionary;
|
||||||
|
}
|
||||||
|
|
||||||
|
void HuffmanCode::getHuffmanCodeR(std::array<std::vector<char>, ASCII_LENGTH> &dictionary, int nodeId,
|
||||||
|
std::vector<char> &code)
|
||||||
|
{
|
||||||
|
HuffmanNode node = (*nodes)[nodeId];
|
||||||
|
|
||||||
|
if (node.data != -1)
|
||||||
|
{
|
||||||
|
for (auto iterator = code.begin(); iterator < code.end(); iterator++)
|
||||||
|
{
|
||||||
|
dictionary[node.data].push_back(*iterator);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (node.lIndex != -1)
|
||||||
|
{
|
||||||
|
// 遍历左子树
|
||||||
|
code.push_back(0);
|
||||||
|
getHuffmanCodeR(dictionary, node.lIndex, code);
|
||||||
|
code.pop_back();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (node.rIndex != -1)
|
||||||
|
{
|
||||||
|
// 遍历右子树
|
||||||
|
code.push_back(1);
|
||||||
|
getHuffmanCodeR(dictionary, node.rIndex, code);
|
||||||
|
code.pop_back();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void HuffmanCode::printHuffmanCode(const std::array<std::vector<char>, ASCII_LENGTH>& dictionary)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < ASCII_LENGTH; i++)
|
||||||
|
{
|
||||||
|
auto code = dictionary[i];
|
||||||
|
|
||||||
|
printf("%d: ", i);
|
||||||
|
for (auto iter = code.begin(); iter < code.end(); iter++)
|
||||||
|
{
|
||||||
|
putc(*iter + 48, stdout);
|
||||||
|
}
|
||||||
|
putc('\n', stdout);
|
||||||
|
}
|
||||||
|
}
|
20
zip-unzip-search/src/logging.cpp
Normal file
20
zip-unzip-search/src/logging.cpp
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
//
|
||||||
|
// Created by ricardo on 22-12-11.
|
||||||
|
//
|
||||||
|
#include "logging.h"
|
||||||
|
#include "cstdio"
|
||||||
|
|
||||||
|
void Logging::LoggingInfo(const std::string &info)
|
||||||
|
{
|
||||||
|
printf("[Info] %s\n", info.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void Logging::LoggingWarning(const std::string &warning)
|
||||||
|
{
|
||||||
|
printf("[warning] %s\n", warning.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void Logging::LoggingError(const std::string &error)
|
||||||
|
{
|
||||||
|
printf("[error] %s\n", error.c_str());
|
||||||
|
}
|
194
zip-unzip-search/src/search.cpp
Normal file
194
zip-unzip-search/src/search.cpp
Normal file
|
@ -0,0 +1,194 @@
|
||||||
|
//
|
||||||
|
// Created by ricardo on 22-12-16.
|
||||||
|
//
|
||||||
|
#include "search.h"
|
||||||
|
#include "cstdio"
|
||||||
|
#include "cstring"
|
||||||
|
#include "logging.h"
|
||||||
|
#include "file_io.h"
|
||||||
|
#include "huffman.h"
|
||||||
|
|
||||||
|
BMSearch::BMSearch(std::vector<char> &sample)
|
||||||
|
{
|
||||||
|
int length = (int )sample.size();
|
||||||
|
|
||||||
|
badCharArray = new int[2];
|
||||||
|
goodSuffixArray = new int[length];
|
||||||
|
this->sample = new std::vector<char>(sample);
|
||||||
|
|
||||||
|
generateBrokenCharArray(sample);
|
||||||
|
generateGoodSuffixArray(sample);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
BMSearch::~BMSearch()
|
||||||
|
{
|
||||||
|
delete badCharArray;
|
||||||
|
delete goodSuffixArray;
|
||||||
|
}
|
||||||
|
|
||||||
|
void BMSearch::generateBrokenCharArray(std::vector<char> &s)
|
||||||
|
{
|
||||||
|
int length = (int )s.size();
|
||||||
|
|
||||||
|
// 输入字符串为01串
|
||||||
|
for (int i = 0; i < 2; i++)
|
||||||
|
{
|
||||||
|
badCharArray[i] = length;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < length - 1; i++)
|
||||||
|
{
|
||||||
|
badCharArray[s[i]] = length - i - 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void BMSearch::generateGoodSuffixArray(std::vector<char> &s)
|
||||||
|
{
|
||||||
|
int length = (int )s.size();
|
||||||
|
|
||||||
|
int suffix[length];
|
||||||
|
|
||||||
|
suffix[length - 1] = length;
|
||||||
|
|
||||||
|
for (int i = length - 2; i >= 0; i--)
|
||||||
|
{
|
||||||
|
int pos = i;
|
||||||
|
while (pos >= 0 and s[pos] == s[length - 1 - i + pos])
|
||||||
|
{
|
||||||
|
pos--;
|
||||||
|
}
|
||||||
|
suffix[i] = i - pos;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < length; i++)
|
||||||
|
{
|
||||||
|
goodSuffixArray[i] = length;
|
||||||
|
}
|
||||||
|
|
||||||
|
int j = 0;
|
||||||
|
for (int i = length - 1; i >= 0 ; i--)
|
||||||
|
{
|
||||||
|
if (suffix[i] == i + 1)
|
||||||
|
{
|
||||||
|
for (; j < length - 1 - i; j++)
|
||||||
|
{
|
||||||
|
if (goodSuffixArray[j] == length)
|
||||||
|
{
|
||||||
|
goodSuffixArray[j] = length - 1 - i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < length - 1; i++)
|
||||||
|
{
|
||||||
|
goodSuffixArray[length - 1 - suffix[i]] = length - 1 - i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void BMSearch::matchFile(std::string &fileName)
|
||||||
|
{
|
||||||
|
auto buffer = new BinaryBuffer(fileName);
|
||||||
|
|
||||||
|
std::vector<char> inputArray;
|
||||||
|
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
if (inputArray.size() != sample->size())
|
||||||
|
{
|
||||||
|
// bm算法要求后缀匹配
|
||||||
|
// 所以开始之间需要读取一个长度和模式字符串长度相同的缓冲区
|
||||||
|
char temp = buffer->read();
|
||||||
|
if (temp == -1)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
inputArray.push_back(temp);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// 正式开始匹配
|
||||||
|
int pos = (int )sample->size() - 1;
|
||||||
|
for(; pos >= 0 and (*sample)[pos] == inputArray[pos]; pos--);
|
||||||
|
if (pos < 0)
|
||||||
|
{
|
||||||
|
// 完成一次匹配
|
||||||
|
Logging::LoggingInfo("Found at " + std::to_string(buffer->position));
|
||||||
|
auto begin = inputArray.begin();
|
||||||
|
auto end = begin + goodSuffixArray[0];
|
||||||
|
inputArray.erase(begin, end);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// 匹配失败
|
||||||
|
auto begin = inputArray.begin();
|
||||||
|
int teleport = max(goodSuffixArray[pos],
|
||||||
|
badCharArray[inputArray[pos]] - (int )sample->size() + 1 + pos);
|
||||||
|
auto end = begin + teleport;
|
||||||
|
inputArray.erase(begin, end);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
delete buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
int BMSearch::max(int a, int b)
|
||||||
|
{
|
||||||
|
return a >= b ? a : b;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SearchInFile(char* fileName, char* sample)
|
||||||
|
{
|
||||||
|
FILE* file = fopen(fileName, "rb");
|
||||||
|
|
||||||
|
if (file == nullptr)
|
||||||
|
{
|
||||||
|
Logging::LoggingError(std::string(fileName) + " is not a valid file name.");
|
||||||
|
exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 读取元信息
|
||||||
|
MetaData metaData{};
|
||||||
|
fread(&metaData, sizeof(MetaData), 1, file);
|
||||||
|
|
||||||
|
// 读取哈夫曼节点数组
|
||||||
|
auto nodes = new HuffmanNode[metaData.HuffmanNodeLength];
|
||||||
|
fread(nodes, sizeof(HuffmanNode), metaData.HuffmanNodeLength, file);
|
||||||
|
fclose(file);
|
||||||
|
// 从哈夫曼节点数组创建哈夫曼编码
|
||||||
|
auto huffmanCode = new HuffmanCode(nodes, metaData.HuffmanNodeLength);
|
||||||
|
huffmanCode->root = metaData.HuffmanRoot;
|
||||||
|
auto dictionary = huffmanCode->getHuffmanCode();
|
||||||
|
|
||||||
|
// 获得模板字符串的哈夫曼编码
|
||||||
|
std::vector<char> sampleCode;
|
||||||
|
int sampleLength = (int )strlen(sample);
|
||||||
|
|
||||||
|
Logging::LoggingInfo("The binary representation of " + std::string(sample) + " is ");
|
||||||
|
for (int i = 0; i < sampleLength; i++)
|
||||||
|
{
|
||||||
|
auto code = (*dictionary)[sample[i]];
|
||||||
|
for (auto iter = code.begin(); iter < code.end(); iter++)
|
||||||
|
{
|
||||||
|
sampleCode.push_back(*iter);
|
||||||
|
putc(*iter + 48, stdout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
putc('\n', stdout);
|
||||||
|
|
||||||
|
// 开始查找
|
||||||
|
auto bm = new BMSearch(sampleCode);
|
||||||
|
|
||||||
|
std::string str = std::string(fileName);
|
||||||
|
bm->matchFile(str);
|
||||||
|
|
||||||
|
delete bm;
|
||||||
|
delete[] nodes;
|
||||||
|
delete huffmanCode;
|
||||||
|
delete dictionary;
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user