Documentation for classes.

--HG--
branch : feature
This commit is contained in:
dismine 2013-10-07 18:34:14 +03:00
parent 8a7ace463c
commit 2b1da2ac32
4 changed files with 270 additions and 265 deletions

View file

@ -40,12 +40,12 @@ qreal Calculator::eval(QString prog, QString *errorMsg){
this->errorMsg->clear(); this->errorMsg->clear();
debugFormula.clear(); debugFormula.clear();
this->prog = prog; this->prog = prog;
//qDebug()<<"Формула: "<<prog; //qDebug()<<"Formula: "<<prog;
index = 0; index = 0;
qreal result = get_exp(); qreal result = get_exp();
QString str = QString(" = %1").arg(result, 0, 'f', 3); QString str = QString(" = %1").arg(result, 0, 'f', 3);
debugFormula.append(str); debugFormula.append(str);
//qDebug()<<"Результат:"<<debugFormula; //qDebug()<<"Result:"<<debugFormula;
return result; return result;
} }
@ -57,12 +57,10 @@ qreal Calculator::get_exp(){
return 0; return 0;
} }
level2(&result); level2(&result);
putback(); /* возвращает последнюю считаную putback();
лексему обратно во входной поток */
return result; return result;
} }
/* Сложение или вычитание двух термов */
void Calculator::level2(qreal *result){ void Calculator::level2(qreal *result){
QChar op; QChar op;
qreal hold; qreal hold;
@ -75,7 +73,6 @@ void Calculator::level2(qreal *result){
} }
} }
/* Вычисление произведения или частного двух фвкторов */
void Calculator::level3(qreal *result){ void Calculator::level3(qreal *result){
QChar op; QChar op;
qreal hold; qreal hold;
@ -89,7 +86,6 @@ void Calculator::level3(qreal *result){
} }
} }
/* Обработка степени числа (целочисленной) */
void Calculator::level4(qreal *result){ void Calculator::level4(qreal *result){
qreal hold; qreal hold;
@ -101,7 +97,6 @@ void Calculator::level4(qreal *result){
} }
} }
/* Унарный + или - */
void Calculator::level5(qreal *result){ void Calculator::level5(qreal *result){
QChar op; QChar op;
@ -115,7 +110,6 @@ void Calculator::level5(qreal *result){
unary(op, result); unary(op, result);
} }
/* Обработка выражения в круглых скобках */
void Calculator::level6(qreal *result){ void Calculator::level6(qreal *result){
if((token[0] == '(') && (token_type == DELIMITER)) { if((token[0] == '(') && (token_type == DELIMITER)) {
get_token(); get_token();
@ -127,7 +121,6 @@ void Calculator::level6(qreal *result){
primitive(result); primitive(result);
} }
/* Определение значения переменной по ее имени */
void Calculator::primitive(qreal *result){ void Calculator::primitive(qreal *result){
QString str; QString str;
switch(token_type) { switch(token_type) {
@ -148,9 +141,8 @@ void Calculator::primitive(qreal *result){
} }
} }
/* Выполнение специфицированной арифметики */
void Calculator::arith(QChar o, qreal *r, qreal *h){ void Calculator::arith(QChar o, qreal *r, qreal *h){
qreal t;//, ex; qreal t;
switch(o.toLatin1()) { switch(o.toLatin1()) {
case '-': case '-':
@ -171,78 +163,54 @@ void Calculator::arith(QChar o, qreal *r, qreal *h){
break; break;
case '^': case '^':
*r = pow(*r, *h); *r = pow(*r, *h);
// ex =*r;
// if(*h==0) {
// *r = 1;
// break;
// }
// for(t=*h-1; t>0; --t)
// *r = (*r) * ex;
break; break;
} }
} }
/* Изменение знака */
void Calculator::unary(QChar o, qreal *r){ void Calculator::unary(QChar o, qreal *r){
if(o=='-') if(o=='-')
*r = -(*r); *r = -(*r);
} }
/* Поиск значения переменной */
qreal Calculator::find_var(QString s){ qreal Calculator::find_var(QString s){
bool ok = false; bool ok = false;
qreal value = data->FindVar(s, &ok); qreal value = data->FindVar(s, &ok);
if(!ok){ if(!ok){
qDebug()<<s; qDebug()<<s;
serror(4); /* не переменная */ serror(4); /* don't variable */
return 0; return 0;
} }
return value; return value;
} }
/* выдать сообщение об ошибке */
void Calculator::serror(qint32 error){ void Calculator::serror(qint32 error){
QString e[]= { QString e[]= {
"Синтаксическая ошибка", tr("Syntax error"),
"Непарные круглые скобки", tr("Parentheses do not match"),
"Это не выражение", tr("This is not an expression"),
"Предполагается символ равенства", tr("It is assumed the equality symbol"),
"Не переменная" tr("Do not variable")
}; };
errorMsg->clear(); errorMsg->clear();
*errorMsg = e[error]; *errorMsg = e[error];
qDebug()<<e[error]; qDebug()<<e[error];
} }
/* Поиск соответствия внутреннего формата для
текущей лексемы в таблице лексем.
*/
char Calculator::look_up(QString s){ char Calculator::look_up(QString s){
QString p; QString p;
/* преобразование к нижнему регистру */
p = s; p = s;
p = p.toLower(); p = p.toLower();
/* просматривается, если лексема обнаружена в return 0;
таблице */
/*
*у нас більше немає команд що потрібно опрацьовувати
*/
// if(commands.contains(p)){
// return commands[p];
// }
return 0; /* нераспознанная команда */
} }
/* Возвращает "истину", если "c" разделитель */
bool Calculator::isdelim(QChar c){ bool Calculator::isdelim(QChar c){
if(StrChr(" ;,+-<>/*%^=()",c) || c=='\n' || c=='\r' || c=='\0') if(StrChr(" ;,+-<>/*%^=()",c) || c=='\n' || c=='\r' || c=='\0')
return true; return true;
return false; return false;
} }
/* Возвращает 1, если "с" пробел или табуляция */
bool Calculator::iswhite(QChar c){ bool Calculator::iswhite(QChar c){
if(c==' ' || c=='\t') if(c==' ' || c=='\t')
return true; return true;
@ -257,14 +225,14 @@ void Calculator::get_token(){
token.clear(); token.clear();
temp=&token; temp=&token;
if(prog[index]=='\0') { /* Конец файла */ if(prog[index]=='\0') { /* end of file */
token="\0"; token="\0";
tok=FINISHED; tok=FINISHED;
token_type=DELIMITER; token_type=DELIMITER;
return; return;
} }
while(iswhite(prog[index])) ++index; /* пропуск пробелов */ while(iswhite(prog[index])) ++index; /* skip spaces */
if(prog[index]=='\r') { /* crtl */ if(prog[index]=='\r') { /* crtl */
++index; ++index; ++index; ++index;
@ -274,15 +242,15 @@ void Calculator::get_token(){
return; return;
} }
if(StrChr("+-*^/%=;(),><", prog[index])) { /* разделитель */ if(StrChr("+-*^/%=;(),><", prog[index])) { /* delimiter */
*temp=prog[index]; *temp=prog[index];
index++; /* переход на следующую позицию */ index++; /* jump to the next position */
temp->append("\0"); temp->append("\0");
token_type=DELIMITER; token_type=DELIMITER;
debugFormula.append(token); debugFormula.append(token);
return; return;
} }
if(prog[index]=='"') { /* строка в кавычках */ if(prog[index]=='"') { /* quoted string */
index++; index++;
while(prog[index] != '"' && prog[index] != '\r'){ while(prog[index] != '"' && prog[index] != '\r'){
temp->append(prog[index]); temp->append(prog[index]);
@ -294,7 +262,7 @@ void Calculator::get_token(){
token_type=QUOTE; token_type=QUOTE;
return; return;
} }
if(prog[index].isDigit()) { /* число */ if(prog[index].isDigit()) { /* number */
while(!isdelim(prog[index])){ while(!isdelim(prog[index])){
temp->append(prog[index]); temp->append(prog[index]);
index++; index++;
@ -304,7 +272,7 @@ void Calculator::get_token(){
return; return;
} }
if(prog[index].isPrint()) { /* переменная или команда */ if(prog[index].isPrint()) { /* variable or command */
while(!isdelim(prog[index])){ while(!isdelim(prog[index])){
temp->append(prog[index]); temp->append(prog[index]);
index++; index++;
@ -313,13 +281,12 @@ void Calculator::get_token(){
} }
temp->append("\0"); temp->append("\0");
/* Просматривается, если строка есть команда или переменная */ /* Seen if there is a command line or a variable */
if(token_type==STRING) { if(token_type==STRING) {
tok=look_up(token); /* преобразование во внутренний tok=look_up(token);
формат */
if(!tok) if(!tok)
token_type = VARIABLE; token_type = VARIABLE;
else token_type = COMMAND; /* это команда */ else token_type = COMMAND; /* It is command */
} }
return; return;
} }
@ -328,7 +295,6 @@ bool Calculator::StrChr(QString string, QChar c){
return string.contains(c, Qt::CaseInsensitive); return string.contains(c, Qt::CaseInsensitive);
} }
/* Возвращает лексему обратно во входной поток */
void Calculator::putback(){ void Calculator::putback(){
QString t; QString t;
t = token; t = token;

View file

@ -26,140 +26,146 @@
#include "vcontainer.h" #include "vcontainer.h"
/** /**
* @brief The Calculator клас калькулятора формул лекал. Виконує розрахунок формул з підставлянням * @brief The Calculator class calculate formulas of pattern. Support operation +,-,/,* and braces.
* значеннь зміних. * Can replace name of variables her value.
*/ */
class Calculator class Calculator{
{
public: public:
/** /**
* @brief Calculator конструктор класу. Використовується при розрахунку лекала. * @brief Calculator class constructor.
* @param data покажчик на контейнер змінних * @param data pointer to a variable container.
*/ */
explicit Calculator(const VContainer *data); explicit Calculator(const VContainer *data);
/** /**
* @brief eval виконує розрахунок формули. * @brief eval calculate formula.
* @param prog рядко в якому зберігається формула. * @param prog string of formula.
* @return значення формули. * @return value of formula.
*/ */
qreal eval(QString prog, QString *errorMsg); qreal eval(QString prog, QString *errorMsg);
private: private:
Q_DISABLE_COPY(Calculator) Q_DISABLE_COPY(Calculator)
/**
* @brief errorMsg keeps error message of calculation.
*/
QString *errorMsg; QString *errorMsg;
/** /**
* @brief token теперішня лексема. * @brief token current token.
*/ */
QString token; QString token;
/** /**
* @brief tok внутрішне представлення лексеми. * @brief tok internal representation of token.
*/ */
qint32 tok; qint32 tok;
/** /**
* @brief token_type тип лексеми. * @brief token_type type of token.
*/ */
qint32 token_type; qint32 token_type;
/** /**
* @brief prog рядок в якому зберігається формула. * @brief prog string where keeps formula.
*/ */
QString prog; /* Содержит анализируемое выражение */ QString prog;
/** /**
* @brief index номер символу в рядку формули. * @brief index number character in string of formula.
*/ */
qint32 index; /* Индекс символа в строке*/ qint32 index;
/** /**
* @brief data контейнер усіх змінних. * @brief data container of all variables.
*/ */
const VContainer *data; const VContainer *data;
/** /**
* @brief debugFormula рядок розшифрованої формули. * @brief debugFormula decoded string of formula.
*/ */
QString debugFormula; QString debugFormula;
/** /**
* @brief get_exp виконує розрахунок формули. * @brief get_exp calculate formula.
* @return значення формули. * @return value of formula.
*/ */
qreal get_exp(); qreal get_exp();
/** /**
* @brief get_token повертає наступну лексему. * @brief get_token return next token.
*/ */
void get_token();/* Получить лексему */ void get_token();
/** /**
* @brief StrChr перевіряє чи символ належить рядку. * @brief StrChr checks whether the character belongs to the line.
* @param string рядок * @param string string with formula
* @param c символ. * @param c character.
* @return true - належить рядку, false - не належить рядку. * @return true - belongs to the line, false - don't belongs to the line.
*/ */
static bool StrChr(QString string, QChar c); static bool StrChr(QString string, QChar c);
/** /**
* @brief putback повертає зчитану лексему назад у потік. * @brief putback returns the readout token back into the flow.
*/ */
void putback(); void putback();
/** /**
* @brief level2 метод додавання і віднімання двух термів. * @brief level2 method of addition and subtraction of two terms.
* @param result результат операції. * @param result result of operation.
*/ */
void level2(qreal *result); void level2(qreal *result);
/** /**
* @brief level3 метод множення, ділення, знаходження процентів. * @brief level3 method of multiplication, division, finding percent.
* @param result результат операції. * @param result result of operation.
*/ */
void level3(qreal *result); void level3(qreal *result);
/** /**
* @brief level4 метод знаходження степені двох чисел. * @brief level4 method of degree two numbers.
* @param result результат операції. * @param result result of operation.
*/ */
void level4(qreal *result); void level4(qreal *result);
/** /**
* @brief level5 метод знаходження унарного плюса чи мінуса. * @brief level5 method for finding unary plus or minus.
* @param result результат операції. * @param result result of operation.
*/ */
void level5(qreal *result); void level5(qreal *result);
/** /**
* @brief level6 метод обробки виразу в круглих лапках. * @brief level6 processing method of the expression in brackets.
* @param result результат операції. * @param result result of operation.
*/ */
void level6(qreal *result); void level6(qreal *result);
/** /**
* @brief primitive метод визначення значення зміної по її імені. * @brief primitive method of determining the value of a variable by its name.
* @param result результат операції. * @param result result of operation.
*/ */
void primitive(qreal *result); void primitive(qreal *result);
/** /**
* @brief arith виконання специфікованої арифметики. Результат записується в перший елемент. * @brief arith perform the specified arithmetic. The result is written to the first element.
* @param o знак операції. * @param o sign operation.
* @param r перший елемент. * @param r first element.
* @param h другий елемент. * @param h second element.
*/ */
static void arith(QChar o, qreal *r, qreal *h); static void arith(QChar o, qreal *r, qreal *h);
/** /**
* @brief unary метод зміни знаку. * @brief unary method changes the sign.
* @param o символ знаку. * @param o sign of symbol.
* @param r елемент. * @param r element.
*/ */
static void unary(QChar o, qreal *r); static void unary(QChar o, qreal *r);
/** /**
* @brief find_var метод знаходить змінну за іменем. * @brief find_var method is finding variable by name.
* @param s ім'я змінної. * @param s name of variable.
* @return значення зміної. * @return value of variable.
*/ */
qreal find_var(QString s); qreal find_var(QString s);
/**
* @brief serror report an error
* @param error error code
*/
void serror(qint32 error); void serror(qint32 error);
/** /**
* @brief look_up пошук відповідного внутрішнього формату для теперішньої лексеми в таблиці лексем. текущей лексемы в таблице лексем * @brief look_up Finding the internal format for the current token in the token table.
* @param s ім'я лексеми. * @param s name of token.
* @return внутрішній номер лексеми. * @return internal number of token.
*/ */
static char look_up(QString s); static char look_up(QString s);
/** /**
* @brief isdelim повертає "істино", якщо с розділювач. * @brief isdelim return true if c delimiter.
* @param c символ. * @param c character.
* @return розділювач, або ні. * @return true - delimiter, false - do not delimiter.
*/ */
static bool isdelim(QChar c); static bool isdelim(QChar c);
/** /**
* @brief iswhite перевіряє чи с пробіл чи табуляція. * @brief iswhite checks whether c space or tab.
* @param c символ. * @param c character.
* @return так або ні. * @return true - space or tab, false - don't space and don't tab.
*/ */
static bool iswhite(QChar c); static bool iswhite(QChar c);
}; };

View file

@ -32,26 +32,48 @@
#include <QCoreApplication> #include <QCoreApplication>
/** /**
* @brief The VContainer class * @brief The VContainer class container of all variables.
*/ */
class VContainer class VContainer{
{
Q_DECLARE_TR_FUNCTIONS(VContainer) Q_DECLARE_TR_FUNCTIONS(VContainer)
public: public:
/** /**
* @brief VContainer * @brief VContainer create empty container
*/ */
VContainer(); VContainer();
/**
* @brief operator = copy constructor
* @param data container
* @return copy container
*/
VContainer &operator=(const VContainer &data); VContainer &operator=(const VContainer &data);
/**
* @brief VContainer create container from another container
* @param data container
*/
VContainer(const VContainer &data); VContainer(const VContainer &data);
/**
* @brief setData copy data from container
* @param data container
*/
void setData(const VContainer &data); void setData(const VContainer &data);
/** /**
* @brief GetPoint * @brief GetPoint returns a point by id
* @param id * @param id id of point
* @return * @return point
*/ */
VPointF GetPoint(qint64 id) const; VPointF GetPoint(qint64 id) const;
/**
* @brief GetModelingPoint return a modeling point by id
* @param id id of modeling point
* @return modeling point
*/
VPointF GetModelingPoint(qint64 id) const; VPointF GetModelingPoint(qint64 id) const;
/**
* @brief GetStandartTableCell
* @param name
* @return
*/
VStandartTableCell GetStandartTableCell(const QString& name) const; VStandartTableCell GetStandartTableCell(const QString& name) const;
VIncrementTableRow GetIncrementTableRow(const QString& name) const; VIncrementTableRow GetIncrementTableRow(const QString& name) const;
qreal GetLine(const QString &name) const; qreal GetLine(const QString &name) const;
@ -67,10 +89,13 @@ public:
qint64 AddPoint(const VPointF& point); qint64 AddPoint(const VPointF& point);
qint64 AddModelingPoint(const VPointF& point); qint64 AddModelingPoint(const VPointF& point);
qint64 AddDetail(const VDetail& detail); qint64 AddDetail(const VDetail& detail);
void AddStandartTableCell(const QString& name, const VStandartTableCell& cell); void AddStandartTableCell(const QString& name,
void AddIncrementTableRow(const QString& name, const VIncrementTableRow &cell); const VStandartTableCell& cell);
void AddIncrementTableRow(const QString& name,
const VIncrementTableRow &cell);
void AddLengthLine(const QString &name, const qreal &value); void AddLengthLine(const QString &name, const qreal &value);
void AddLengthSpline(const qint64 &firstPointId, const qint64 &secondPointId, void AddLengthSpline(const qint64 &firstPointId,
const qint64 &secondPointId,
Draw::Draws mode = Draw::Calculation); Draw::Draws mode = Draw::Calculation);
void AddLengthSpline(const QString &name, const qreal &value); void AddLengthSpline(const QString &name, const qreal &value);
void AddLengthArc(const qint64 &center, const qint64 &id); void AddLengthArc(const qint64 &center, const qint64 &id);
@ -86,7 +111,8 @@ public:
qint64 AddModelingArc(const VArc& arc); qint64 AddModelingArc(const VArc& arc);
QString GetNameLine(const qint64 &firstPoint, const qint64 &secondPoint, QString GetNameLine(const qint64 &firstPoint, const qint64 &secondPoint,
Draw::Draws mode = Draw::Calculation) const; Draw::Draws mode = Draw::Calculation) const;
QString GetNameLineAngle(const qint64 &firstPoint, const qint64 &secondPoint, QString GetNameLineAngle(const qint64 &firstPoint,
const qint64 &secondPoint,
Draw::Draws mode = Draw::Calculation) const; Draw::Draws mode = Draw::Calculation) const;
QString GetNameSpline(const qint64 &firstPoint, const qint64 &secondPoint, QString GetNameSpline(const qint64 &firstPoint, const qint64 &secondPoint,
Draw::Draws mode = Draw::Calculation) const; Draw::Draws mode = Draw::Calculation) const;
@ -103,8 +129,10 @@ public:
void UpdateModelingSplinePath(qint64 id, const VSplinePath& splPath); void UpdateModelingSplinePath(qint64 id, const VSplinePath& splPath);
void UpdateArc(qint64 id, const VArc& arc); void UpdateArc(qint64 id, const VArc& arc);
void UpdateModelingArc(qint64 id, const VArc& arc); void UpdateModelingArc(qint64 id, const VArc& arc);
void UpdateStandartTableCell(const QString& name, const VStandartTableCell& cell); void UpdateStandartTableCell(const QString& name,
void UpdateIncrementTableRow(const QString& name, const VIncrementTableRow& cell); const VStandartTableCell& cell);
void UpdateIncrementTableRow(const QString& name,
const VIncrementTableRow& cell);
qreal GetValueStandartTableCell(const QString& name) const; qreal GetValueStandartTableCell(const QString& name) const;
qreal GetValueIncrementTableRow(const QString& name) const; qreal GetValueIncrementTableRow(const QString& name) const;
void Clear(); void Clear();
@ -140,11 +168,14 @@ public:
const QHash<qint64, VDetail> *DataDetails() const; const QHash<qint64, VDetail> *DataDetails() const;
static void UpdateId(qint64 newId); static void UpdateId(qint64 newId);
QPainterPath ContourPath(qint64 idDetail) const; QPainterPath ContourPath(qint64 idDetail) const;
QPainterPath Equidistant(QVector<QPointF> points, const Detail::Equidistant &eqv, QPainterPath Equidistant(QVector<QPointF> points,
const Detail::Equidistant &eqv,
const qreal &width)const; const qreal &width)const;
static QLineF ParallelLine(const QLineF &line, qreal width ); static QLineF ParallelLine(const QLineF &line, qreal width );
static QPointF SingleParallelPoint(const QLineF &line, const qreal &angle, const qreal &width); static QPointF SingleParallelPoint(const QLineF &line, const qreal &angle,
QVector<QPointF> EkvPoint(const QLineF &line1, const QLineF &line2, const qreal &width)const; const qreal &width);
QVector<QPointF> EkvPoint(const QLineF &line1, const QLineF &line2,
const qreal &width)const;
QVector<QPointF> CheckLoops(const QVector<QPointF> &points) const; QVector<QPointF> CheckLoops(const QVector<QPointF> &points) const;
void PrepareDetails(QVector<VItem*> & list)const; void PrepareDetails(QVector<VItem*> & list)const;
private: private:
@ -168,10 +199,12 @@ private:
template <typename key, typename val> static val GetObject(const QHash<key,val> &obj, key id); template <typename key, typename val> static val GetObject(const QHash<key,val> &obj, key id);
template <typename val> static void UpdateObject(QHash<qint64, val> &obj, const qint64 &id, template <typename val> static void UpdateObject(QHash<qint64, val> &obj, const qint64 &id,
const val& point); const val& point);
template <typename key, typename val> static qint64 AddObject(QHash<key, val> &obj, const val& value); template <typename key, typename val> static qint64 AddObject(QHash<key, val> &obj,
const val& value);
void CreateManTableIGroup (); void CreateManTableIGroup ();
QVector<QPointF> GetReversePoint(const QVector<QPointF> &points)const; QVector<QPointF> GetReversePoint(const QVector<QPointF> &points)const;
qreal GetLengthContour(const QVector<QPointF> &contour, const QVector<QPointF> &newPoints)const; qreal GetLengthContour(const QVector<QPointF> &contour,
const QVector<QPointF> &newPoints)const;
}; };
#endif // VCONTAINER_H #endif // VCONTAINER_H

View file

@ -74,7 +74,7 @@ CREATE_SUBDIRS = NO
# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, # Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak,
# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. # Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
OUTPUT_LANGUAGE = Ukrainian OUTPUT_LANGUAGE = English
# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
# include brief member descriptions after the members that are listed in # include brief member descriptions after the members that are listed in
@ -369,7 +369,7 @@ EXTRACT_PACKAGE = NO
# If the EXTRACT_STATIC tag is set to YES all static members of a file # If the EXTRACT_STATIC tag is set to YES all static members of a file
# will be included in the documentation. # will be included in the documentation.
EXTRACT_STATIC = NO EXTRACT_STATIC = YES
# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
# defined locally in source files will be included in the documentation. # defined locally in source files will be included in the documentation.