From f8147f5bb5c15263bce6c267785d504d673f4b42 Mon Sep 17 00:00:00 2001 From: Mark Olesen Date: Sat, 2 Jan 2010 13:01:37 +0100 Subject: [PATCH 01/42] Add basic scalar functions to calcEntry. --- applications/test/dictionary/Make/files | 1 + .../addToStaticMemberFunctionSelectionTable.H | 53 +++++ .../test/dictionary/calcEntry/calcEntry.C | 2 +- .../test/dictionary/calcEntry/calcEntry.H | 2 +- .../test/dictionary/calcEntry/calcEntry.atg | 205 +++++++++--------- .../dictionary/calcEntry/calcEntryInternal.C | 182 ++++++++++++++++ .../dictionary/calcEntry/calcEntryInternal.H | 101 +++++++++ .../dictionary/calcEntry/calcEntryParser.cpp | 111 +++++----- .../dictionary/calcEntry/calcEntryParser.h | 69 ++---- .../dictionary/calcEntry/calcEntryScanner.cpp | 52 ++--- .../dictionary/calcEntry/calcEntryScanner.h | 12 +- .../staticMemberFunctionSelectionTables.H | 147 +++++++++++++ applications/test/dictionary/testDictCalc | 8 +- 13 files changed, 704 insertions(+), 241 deletions(-) create mode 100644 applications/test/dictionary/calcEntry/addToStaticMemberFunctionSelectionTable.H create mode 100644 applications/test/dictionary/calcEntry/calcEntryInternal.C create mode 100644 applications/test/dictionary/calcEntry/calcEntryInternal.H create mode 100644 applications/test/dictionary/calcEntry/staticMemberFunctionSelectionTables.H diff --git a/applications/test/dictionary/Make/files b/applications/test/dictionary/Make/files index 148f5fb1c9..ff7a3caad4 100644 --- a/applications/test/dictionary/Make/files +++ b/applications/test/dictionary/Make/files @@ -1,6 +1,7 @@ dictionaryTest.C calcEntry/calcEntry.C +calcEntry/calcEntryInternal.C calcEntry/calcEntryParser.cpp calcEntry/calcEntryScanner.cpp diff --git a/applications/test/dictionary/calcEntry/addToStaticMemberFunctionSelectionTable.H b/applications/test/dictionary/calcEntry/addToStaticMemberFunctionSelectionTable.H new file mode 100644 index 0000000000..572f93ae23 --- /dev/null +++ b/applications/test/dictionary/calcEntry/addToStaticMemberFunctionSelectionTable.H @@ -0,0 +1,53 @@ +/*---------------------------------------------------------------------------*\ + ========= | + \\ / F ield | OpenFOAM: The Open Source CFD Toolbox + \\ / O peration | + \\ / A nd | Copyright (C) 2010-2010 OpenCFD Ltd. + \\/ M anipulation | +------------------------------------------------------------------------------- +License + This file is part of OpenFOAM. + + OpenFOAM 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 2 of the License, or (at your + option) any later version. + + OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation, + Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +@file Foam::addToStaticMemberFunctionSelectionTable + +Description + Macros for easy insertion into member function selection tables + +\*---------------------------------------------------------------------------*/ + +#ifndef addToStaticMemberFunctionSelectionTable_H +#define addToStaticMemberFunctionSelectionTable_H + +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + + +// add to hash-table of functions with 'lookup' as the key +#define addNamedToStaticMemberFunctionSelectionTable\ +(baseType,thisType,memberFunction,argNames,lookup,functionPtr) \ + \ + /* Add the thisType memberFunction to the table, find by lookup name */ \ + baseType::add##memberFunction##argNames##StaticMemberFunctionToTable \ + add_##lookup##_##thisType##memberFunction##argNames##StaticMemberFunctionTo##baseType##Table_\ + (#lookup, functionPtr) + + +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + + +#endif + +// ************************************************************************* // diff --git a/applications/test/dictionary/calcEntry/calcEntry.C b/applications/test/dictionary/calcEntry/calcEntry.C index 9810812308..7e634bc8b4 100644 --- a/applications/test/dictionary/calcEntry/calcEntry.C +++ b/applications/test/dictionary/calcEntry/calcEntry.C @@ -2,7 +2,7 @@ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | - \\ / A nd | Copyright (C) 2009-2009 OpenCFD Ltd. + \\ / A nd | Copyright (C) 2009-2010 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License diff --git a/applications/test/dictionary/calcEntry/calcEntry.H b/applications/test/dictionary/calcEntry/calcEntry.H index 027c4b510b..3db7562161 100644 --- a/applications/test/dictionary/calcEntry/calcEntry.H +++ b/applications/test/dictionary/calcEntry/calcEntry.H @@ -2,7 +2,7 @@ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | - \\ / A nd | Copyright (C) 2009-2009 OpenCFD Ltd. + \\ / A nd | Copyright (C) 2009-2010 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License diff --git a/applications/test/dictionary/calcEntry/calcEntry.atg b/applications/test/dictionary/calcEntry/calcEntry.atg index 90c0861143..57646c3cad 100644 --- a/applications/test/dictionary/calcEntry/calcEntry.atg +++ b/applications/test/dictionary/calcEntry/calcEntry.atg @@ -1,65 +1,72 @@ -/*------------------------------------------------------------------------- +/*---------------------------------*- C++ -*---------------------------------*\ + ========= | + \\ / F ield | OpenFOAM: The Open Source CFD Toolbox + \\ / O peration | + \\ / A nd | Copyright (C) 2009-2010 OpenCFD Ltd. + \\/ M anipulation | +------------------------------------------------------------------------------- +License + This file is part of OpenFOAM. + + OpenFOAM 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 2 of the License, or (at your + option) any later version. + + OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation, + Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +@file calcEntry.atg + +Description + An attributed Coco/R grammar to parse simple arithmetic expressions + +SourceFiles + generated + +\*---------------------------------------------------------------------------*/ +/*---------------------------------------------------------------------------*\ compile with: Coco \ -frames $WM_THIRD_PARTY_DIR/coco-r \ calcEntry.atg --------------------------------------------------------------------------*/ +\*---------------------------------------------------------------------------*/ #include "dictionary.H" #include "scalar.H" #include "error.H" #include "wchar.H" +#include "DynamicList.H" +#include "calcEntryInternal.H" COMPILER calcEntry -$prefix=calcEntry -$namespace=Foam::functionEntries::calcEntryInternal -$eof=true // grammar handles eof itself + // grammar pragmas: + $prefix=calcEntry + $namespace=Foam::functionEntries::calcEntryInternal + $eof=true // grammar handles eof itself // Simple four function calculator for OpenFOAM dictionaries - //! with debug - static const int debug = 0; - - //! The parent dictionary +private: + //- The parent dictionary mutable dictionary* dict_; - //! Track that parent dictionary was set - bool hasDict_; - - //! The calculation result + //- The calculation result scalar val; - - //! token -> scalar - scalar getScalar() const - { - return coco_string_toDouble(t->val); - } - - //! token -> string - std::string getString() const - { - char* str = coco_string_create_char(t->val); - std::string s(str); - coco_string_delete(str); - return s; - } - - //! attach a dictionary - void dict(const dictionary& dict) - { - dict_ = const_cast(&dict); - hasDict_ = true; - } - - - //! lookup dictionary entry + //- lookup dictionary entry scalar getDictLookup() const { scalar dictValue = 0; - if (!hasDict_) + if (!dict_) { FatalErrorIn ( @@ -70,19 +77,14 @@ $eof=true // grammar handles eof itself return 0; } - char* chars = coco_string_create_char + char* str = coco_string_create_char ( t->val, 1, (coco_string_length(t->val) - 1) ); - word keyword(chars); - coco_string_delete(chars); - - if (debug) - { - Info<<"lookup: " << keyword << nl; - } + word keyword(str); + coco_string_delete(str); entry* entryPtr = dict_->lookupEntryPtr(keyword, true, false); if (entryPtr && !entryPtr->isDict()) @@ -107,23 +109,35 @@ $eof=true // grammar handles eof itself << exit(FatalError); } - return dictValue; } + +public: + + //- attach a dictionary + void dict(const dictionary& dict) + { + dict_ = const_cast(&dict); + } + + //- Return the calculated result scalar Result() const { return val; } +INITIALIZE + dict_ = 0; + val = 0; + /*---------------------------------------------------------------------------*/ CHARACTERS - letter = 'A'..'Z' + 'a'..'z'. - qualifier = '_' + ':'. - dollar = '$'. + letter = 'A'..'Z' + 'a'..'z' + '_'. digit = "0123456789". + alphanum = letter + digit. sign = '+' + '-'. cr = '\r'. lf = '\n'. @@ -138,16 +152,16 @@ TOKENS // identifier ident = - letter { letter | digit | qualifier }. + letter { alphanum }. // string string = '"' { stringCh | '\\' printable } '"'. // dictionary lookup identifier -// starts with '$' and otherwise limited to a normal indentifier +// starts with '$' and otherwise limited to a normal identifier variable = - dollar letter { letter | digit | qualifier }. + '$' letter { alphanum }. // floating point and integer numbers number = @@ -167,63 +181,35 @@ IGNORE cr + lf + tab PRODUCTIONS -calcEntry (. val = 0; - if (debug){Info<<"start val pos:"<< t->pos << nl;} - .) +calcEntry (. val = 0; .) = - '{' Expr '}' (. - if (debug){ - Info<<"end {} at pos:"<< t->pos - <<" val:"<< t->val - <<" len:"<< coco_string_length(t->val) - <<" la pos:"<< la->pos << nl; - } - // reposition to immediately after the closing '}' - scanner->buffer->SetPos - ( - t->pos + coco_string_length(t->val) - ); + '{' Expr '}' (. // reposition to immediately after the closing '}' + scanner->buffer->SetPos(t->pos + 1); .) - | ( Expr EOF ) + | ( Expr EOF ) . /*---------------------------------------------------------------------------*/ -Expr (. scalar val2 = 0; - if (debug) {Info<<"Expr:"<< val<< " pos:"<< t->pos << nl;} - .) +Expr (. scalar val2 = 0; .) = Term { - "+" Term (. if (debug) {Info<<"+Term:"<pos << nl;} - val += val2; - if (debug) {Info<<"="<< val<< " pos:"<< t->pos << nl;} - .) - | "-" Term (. if (debug) {Info<<"-Term:"<pos << nl;} - val -= val2; - if (debug) {Info<<"="<< val<< " pos:"<< t->pos << nl;} - .) + "+" Term (. val += val2; .) + | "-" Term (. val -= val2; .) } . /*---------------------------------------------------------------------------*/ -Term (. scalar val2 = 0; - if (debug) {Info<<"Term:"<< val<< " pos:"<< t->pos << nl;} - .) +Term (. scalar val2 = 0; .) = Factor { - "*" Factor (. if (debug) {Info<<"*Factor:"<pos << nl;} - val *= val2; - if (debug) {Info<<"="<< val<< " pos:"<< t->pos << nl;} - .) - | "/" Factor (. if (debug) {Info<<"/Factor:"<pos << nl;} - val /= val2; - if (debug) {Info<<"="<< val<< " pos:"<< t->pos << nl;} - .) + "*" Factor (. val *= val2; .) + | "/" Factor (. val /= val2; .) } . @@ -231,17 +217,32 @@ Term (. scalar val2 = 0; /*---------------------------------------------------------------------------*/ Factor = - variable (. val = getDictLookup(); - if (debug) {Info<<"lookup:"<pos << nl;} - .) - | number (. val = getScalar(); - if (debug) {Info<<"got num:"<pos << nl;} - .) - | '-' '(' Expr ')' (. val = -val; - if (debug) {Info<<"inv:"<pos << nl;} - .) - | '(' Expr ')' (. if (debug){Info<<"got Expr:"<pos << nl;} + Func + | variable (. val = getDictLookup(); .) + | number (. val = coco_string_toDouble(t->val); .) + | '-' '(' Expr ')' (. val = -val; .) + | '(' Expr ')' +. + + +/*---------------------------------------------------------------------------*/ + +// functions like sin(x) or pow(x, y) etc. +Func += + ident (. + char* str = coco_string_create_char(t->val); + word funcName(str); + coco_string_delete(str); + DynamicList param(4); // hold parameter values .) + '(' + [ (. scalar x; .) + Expr (. param.append(x); .) + { ',' Expr (. param.append(x); .) + } + ] + ')' (. val = scalarFunctions::dispatch(funcName, param); .) . diff --git a/applications/test/dictionary/calcEntry/calcEntryInternal.C b/applications/test/dictionary/calcEntry/calcEntryInternal.C new file mode 100644 index 0000000000..888475cee6 --- /dev/null +++ b/applications/test/dictionary/calcEntry/calcEntryInternal.C @@ -0,0 +1,182 @@ +/*---------------------------------------------------------------------------*\ + ========= | + \\ / F ield | OpenFOAM: The Open Source CFD Toolbox + \\ / O peration | + \\ / A nd | Copyright (C) 2010-2010 OpenCFD Ltd. + \\/ M anipulation | +------------------------------------------------------------------------------- +License + This file is part of OpenFOAM. + + OpenFOAM 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 2 of the License, or (at your + option) any later version. + + OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation, + Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +\*---------------------------------------------------------------------------*/ + +#include "calcEntryInternal.H" +#include "addToMemberFunctionSelectionTable.H" +#include "addToStaticMemberFunctionSelectionTable.H" +#include "unitConversion.H" + +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + +namespace Foam +{ +namespace functionEntries +{ +namespace calcEntryInternal +{ + +defineStaticMemberFunctionSelectionTable(scalarFunctions,dispatch,ParamList); + + +scalar scalarFunctions::dispatch +( + const word& name, + const UList& param +) +{ + // create lookup name with parameter count + const word lookupName = name + '_' + Foam::name(param.size()); + + dispatchParamListMemberFunctionTable::iterator mfIter = + dispatchParamListMemberFunctionTablePtr_->find(lookupName); + + if (mfIter == dispatchParamListMemberFunctionTablePtr_->end()) + { + FatalErrorIn + ( + "calcEntryInternal::scalarFunctions::dispatch" + "(const word&, const UList&) : " + ) << "Unknown function " << name << nl << nl + << "Valid types are :" << endl + << dispatchParamListMemberFunctionTablePtr_->sortedToc() + << exit(FatalError); + } + + return mfIter()(param); +} + + +scalar scalarFunctions::pi_0(const UList& param) +{ + return constant::mathematical::pi; +} + +scalar scalarFunctions::degToRad_1(const UList& param) +{ + return degToRad(param[0]); +} + +scalar scalarFunctions::radToDeg_1(const UList& param) +{ + return radToDeg(param[0]); +} + +scalar scalarFunctions::sin_1(const UList& param) +{ + return Foam::sin(param[0]); +} + +scalar scalarFunctions::cos_1(const UList& param) +{ + return Foam::cos(param[0]); +} + +scalar scalarFunctions::pow_2(const UList& param) +{ + return Foam::pow(param[0], param[1]); +} + +scalar scalarFunctions::log_1(const UList& param) +{ + return Foam::log(param[0]); +} + +scalar scalarFunctions::log10_1(const UList& param) +{ + return Foam::log10(param[0]); +} + + + +addNamedToStaticMemberFunctionSelectionTable +( + scalarFunctions,scalarFunctions,dispatch,ParamList, + pi_0, + &scalarFunctions::pi_0 +); + +addNamedToStaticMemberFunctionSelectionTable +( + scalarFunctions,scalarFunctions,dispatch,ParamList, + degToRad_1, + &scalarFunctions::degToRad_1 +); + +addNamedToStaticMemberFunctionSelectionTable +( + scalarFunctions,scalarFunctions,dispatch,ParamList, + radToDeg_1, + &scalarFunctions::radToDeg_1 +); + +addNamedToStaticMemberFunctionSelectionTable +( + scalarFunctions,scalarFunctions,dispatch,ParamList, + sin_1, + &scalarFunctions::sin_1 +); + +addNamedToStaticMemberFunctionSelectionTable +( + scalarFunctions,scalarFunctions,dispatch,ParamList, + cos_1, + &scalarFunctions::cos_1 +); + +addNamedToStaticMemberFunctionSelectionTable +( + scalarFunctions,scalarFunctions,dispatch,ParamList, + pow_2, + &scalarFunctions::pow_2 +); + +addNamedToStaticMemberFunctionSelectionTable +( + scalarFunctions,scalarFunctions,dispatch,ParamList, + log_1, + &scalarFunctions::log_1 +); + + + +addNamedToStaticMemberFunctionSelectionTable +( + scalarFunctions,scalarFunctions,dispatch,ParamList, + log10_1, + &scalarFunctions::log10_1 +); + + +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + +} // End namespace calcEntryInternal +} // End namespace functionEntries +} // End namespace Foam + +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + + +// ************************************************************************* // diff --git a/applications/test/dictionary/calcEntry/calcEntryInternal.H b/applications/test/dictionary/calcEntry/calcEntryInternal.H new file mode 100644 index 0000000000..73ff08c7e4 --- /dev/null +++ b/applications/test/dictionary/calcEntry/calcEntryInternal.H @@ -0,0 +1,101 @@ +/*---------------------------------------------------------------------------*\ + ========= | + \\ / F ield | OpenFOAM: The Open Source CFD Toolbox + \\ / O peration | + \\ / A nd | Copyright (C) 2010-2010 OpenCFD Ltd. + \\/ M anipulation | +------------------------------------------------------------------------------- +License + This file is part of OpenFOAM. + + OpenFOAM 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 2 of the License, or (at your + option) any later version. + + OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation, + Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +Namespace + Foam::functionEntries::calcEntryInternal + +Description + This dictionary function entry may or may not do anything particularly + useful - depending upon what is currently being used to test. + +SourceFiles + calcEntryInternal.C + +\*---------------------------------------------------------------------------*/ + +#ifndef calcEntryInternal_H +#define calcEntryInternal_H + +#include "functionEntry.H" +#include "memberFunctionSelectionTables.H" +#include "staticMemberFunctionSelectionTables.H" + +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + +namespace Foam +{ +namespace functionEntries +{ +namespace calcEntryInternal +{ + +/*---------------------------------------------------------------------------*\ + Class calcEntryFunctions Declaration +\*---------------------------------------------------------------------------*/ + +class scalarFunctions +{ +public: + + // Member Function Selectors + + declareStaticMemberFunctionSelectionTable + ( + scalar, + scalarFunctions, + dispatch, + ParamList, + ( + const UList& param + ), + (param) + ); + + //- Calculate + static scalar dispatch(const word&, const UList&); + + + static scalar pi_0(const UList&); + static scalar degToRad_1(const UList&); + static scalar radToDeg_1(const UList&); + static scalar cos_1(const UList&); + static scalar sin_1(const UList&); + static scalar pow_2(const UList&); + static scalar log_1(const UList&); + static scalar log10_1(const UList&); + +}; + + +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + +} // End namespace calcEntryInternal +} // End namespace functionEntries +} // End namespace Foam + +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + +#endif + +// ************************************************************************* // diff --git a/applications/test/dictionary/calcEntry/calcEntryParser.cpp b/applications/test/dictionary/calcEntry/calcEntryParser.cpp index 1ff95b8ac9..4fc4016207 100644 --- a/applications/test/dictionary/calcEntry/calcEntryParser.cpp +++ b/applications/test/dictionary/calcEntry/calcEntryParser.cpp @@ -91,105 +91,93 @@ bool Parser::WeakSeparator(int n, int syFol, int repFol) { void Parser::calcEntry() { - val = 0; - if (debug){Info<<"start val pos:"<< t->pos << nl;} - + val = 0; if (la->kind == 5) { Get(); Expr(val); Expect(6); - if (debug){ - Info<<"end {} at pos:"<< t->pos - <<" val:"<< t->val - <<" len:"<< coco_string_length(t->val) - <<" la pos:"<< la->pos << nl; - } - // reposition to immediately after the closing '}' - scanner->buffer->SetPos - ( - t->pos + coco_string_length(t->val) - ); + scanner->buffer->SetPos(t->pos + 1); } else if (StartOf(1)) { Expr(val); Expect(0); - } else SynErr(14); + } else SynErr(15); } void Parser::Expr(scalar& val) { - scalar val2 = 0; - if (debug) {Info<<"Expr:"<< val<< " pos:"<< t->pos << nl;} - + scalar val2 = 0; Term(val); while (la->kind == 7 || la->kind == 8) { if (la->kind == 7) { Get(); Term(val2); - if (debug) {Info<<"+Term:"<pos << nl;} - val += val2; - if (debug) {Info<<"="<< val<< " pos:"<< t->pos << nl;} - + val += val2; } else { Get(); Term(val2); - if (debug) {Info<<"-Term:"<pos << nl;} - val -= val2; - if (debug) {Info<<"="<< val<< " pos:"<< t->pos << nl;} - + val -= val2; } } } void Parser::Term(scalar& val) { - scalar val2 = 0; - if (debug) {Info<<"Term:"<< val<< " pos:"<< t->pos << nl;} - + scalar val2 = 0; Factor(val); while (la->kind == 9 || la->kind == 10) { if (la->kind == 9) { Get(); Factor(val2); - if (debug) {Info<<"*Factor:"<pos << nl;} - val *= val2; - if (debug) {Info<<"="<< val<< " pos:"<< t->pos << nl;} - + val *= val2; } else { Get(); Factor(val2); - if (debug) {Info<<"/Factor:"<pos << nl;} - val /= val2; - if (debug) {Info<<"="<< val<< " pos:"<< t->pos << nl;} - + val /= val2; } } } void Parser::Factor(scalar& val) { - if (la->kind == 3) { + if (la->kind == 1) { + Func(val); + } else if (la->kind == 3) { Get(); - val = getDictLookup(); - if (debug) {Info<<"lookup:"<pos << nl;} - + val = getDictLookup(); } else if (la->kind == 4) { Get(); - val = getScalar(); - if (debug) {Info<<"got num:"<pos << nl;} - + val = coco_string_toDouble(t->val); } else if (la->kind == 8) { Get(); Expect(11); Expr(val); Expect(12); - val = -val; - if (debug) {Info<<"inv:"<pos << nl;} - + val = -val; } else if (la->kind == 11) { Get(); Expr(val); Expect(12); - if (debug){Info<<"got Expr:"<pos << nl;} - - } else SynErr(15); + } else SynErr(16); +} + +void Parser::Func(scalar& val) { + Expect(1); + char* str = coco_string_create_char(t->val); + word funcName(str); + coco_string_delete(str); + DynamicList param(4); // hold parameter values + + Expect(11); + if (StartOf(1)) { + scalar x; + Expr(x); + param.append(x); + while (la->kind == 13) { + Get(); + Expr(x); + param.append(x); + } + } + Expect(12); + val = scalarFunctions::dispatch(funcName, param); } @@ -218,10 +206,16 @@ Parser::Parser(Scanner* scan, Errors* err) t(NULL), la(NULL) { - if (!errors) { // add in default error handling errors = new Errors(); } + // user-defined initialization: +dict_ = 0; + val = 0; + +/*---------------------------------------------------------------------------*/ + + } @@ -229,9 +223,9 @@ bool Parser::StartOf(int s) { const bool T = true; const bool x = false; - static bool set[2][15] = { - {T,x,x,x, x,x,x,x, x,x,x,x, x,x,x}, - {x,x,x,T, T,x,x,x, T,x,x,T, x,x,x} + static const bool set[2][16] = { + {T,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x}, + {x,T,x,T, T,x,x,x, T,x,x,T, x,x,x,x} }; @@ -245,6 +239,8 @@ Parser::~Parser() { delete errors; } delete dummyToken; + // user-defined destruction: + } @@ -284,9 +280,10 @@ wchar_t* Errors::strerror(int n) case 10: s = coco_string_create(L"\"/\" expected"); break; case 11: s = coco_string_create(L"\"(\" expected"); break; case 12: s = coco_string_create(L"\")\" expected"); break; - case 13: s = coco_string_create(L"??? expected"); break; - case 14: s = coco_string_create(L"invalid calcEntry"); break; - case 15: s = coco_string_create(L"invalid Factor"); break; + case 13: s = coco_string_create(L"\",\" expected"); break; + case 14: s = coco_string_create(L"??? expected"); break; + case 15: s = coco_string_create(L"invalid calcEntry"); break; + case 16: s = coco_string_create(L"invalid Factor"); break; default: { diff --git a/applications/test/dictionary/calcEntry/calcEntryParser.h b/applications/test/dictionary/calcEntry/calcEntryParser.h index de12a3961e..afa25782a7 100644 --- a/applications/test/dictionary/calcEntry/calcEntryParser.h +++ b/applications/test/dictionary/calcEntry/calcEntryParser.h @@ -7,6 +7,8 @@ #include "scalar.H" #include "error.H" #include "wchar.H" +#include "DynamicList.H" +#include "calcEntryInternal.H" #include "calcEntryScanner.h" @@ -55,7 +57,7 @@ private: _variable=3, _number=4, }; - static const int maxT = 13; + static const int maxT = 14; static const int minErrDist = 2; //!< min. distance before reporting errors @@ -77,47 +79,19 @@ public: Token *t; //!< last recognized token Token *la; //!< lookahead token -static const int debug = 0; - - //! The parent dictionary +private: + //- The parent dictionary mutable dictionary* dict_; - //! Track that parent dictionary was set - bool hasDict_; - - //! The calculation result + //- The calculation result scalar val; - - //! token -> scalar - scalar getScalar() const - { - return coco_string_toDouble(t->val); - } - - //! token -> string - std::string getString() const - { - char* str = coco_string_create_char(t->val); - std::string s(str); - coco_string_delete(str); - return s; - } - - //! attach a dictionary - void dict(const dictionary& dict) - { - dict_ = const_cast(&dict); - hasDict_ = true; - } - - - //! lookup dictionary entry + //- lookup dictionary entry scalar getDictLookup() const { scalar dictValue = 0; - if (!hasDict_) + if (!dict_) { FatalErrorIn ( @@ -128,19 +102,14 @@ static const int debug = 0; return 0; } - char* chars = coco_string_create_char + char* str = coco_string_create_char ( t->val, 1, (coco_string_length(t->val) - 1) ); - word keyword(chars); - coco_string_delete(chars); - - if (debug) - { - Info<<"lookup: " << keyword << nl; - } + word keyword(str); + coco_string_delete(str); entry* entryPtr = dict_->lookupEntryPtr(keyword, true, false); if (entryPtr && !entryPtr->isDict()) @@ -165,18 +134,25 @@ static const int debug = 0; << exit(FatalError); } - return dictValue; } + +public: + + //- attach a dictionary + void dict(const dictionary& dict) + { + dict_ = const_cast(&dict); + } + + //- Return the calculated result scalar Result() const { return val; } -/*---------------------------------------------------------------------------*/ - //! Construct for the specified scanner @@ -185,13 +161,14 @@ static const int debug = 0; * handler, which will not be deleted upon destruction. */ Parser(Scanner* scan, Errors* err = 0); - ~Parser(); //!< Destructor - cleanup errors and dummyToken + ~Parser(); void SemErr(const wchar_t* msg); //!< Handle semantic error void calcEntry(); void Expr(scalar& val); void Term(scalar& val); void Factor(scalar& val); + void Func(scalar& val); void Parse(); //!< Execute the parse operation diff --git a/applications/test/dictionary/calcEntry/calcEntryScanner.cpp b/applications/test/dictionary/calcEntry/calcEntryScanner.cpp index b070bcf3f3..f475323086 100644 --- a/applications/test/dictionary/calcEntry/calcEntryScanner.cpp +++ b/applications/test/dictionary/calcEntry/calcEntryScanner.cpp @@ -21,7 +21,7 @@ namespace calcEntryInternal { // string handling, wide character wchar_t* coco_string_create(const wchar_t* str) { - int len = coco_string_length(str); + const int len = coco_string_length(str); wchar_t* dest = new wchar_t[len + 1]; if (len) { wcsncpy(dest, str, len); @@ -31,10 +31,7 @@ wchar_t* coco_string_create(const wchar_t* str) { } wchar_t* coco_string_create(const wchar_t* str, int index, int length) { - int len = coco_string_length(str); - if (len) { - len = length; - } + const int len = (str && *str) ? length : 0; wchar_t* dest = new wchar_t[len + 1]; if (len) { wcsncpy(dest, &(str[index]), len); @@ -69,8 +66,8 @@ wchar_t* coco_string_create_lower(const wchar_t* str, int index, int len) { wchar_t* coco_string_create_append(const wchar_t* str1, const wchar_t* str2) { - int str1Len = coco_string_length(str1); - int str2Len = coco_string_length(str2); + const int str1Len = coco_string_length(str1); + const int str2Len = coco_string_length(str2); wchar_t* dest = new wchar_t[str1Len + str2Len + 1]; @@ -82,7 +79,7 @@ wchar_t* coco_string_create_append(const wchar_t* str1, const wchar_t* str2) { } wchar_t* coco_string_create_append(const wchar_t* str1, const wchar_t ch) { - int len = coco_string_length(str1); + const int len = coco_string_length(str1); wchar_t* dest = new wchar_t[len + 2]; wcsncpy(dest, str1, len); // or use if (len) { wcscpy(dest, str1); } dest[len] = ch; @@ -100,8 +97,8 @@ int coco_string_length(const wchar_t* str) { } bool coco_string_endswith(const wchar_t* str, const wchar_t* endstr) { - int strLen = wcslen(str); - int endLen = wcslen(endstr); + const int strLen = wcslen(str); + const int endLen = wcslen(endstr); return (endLen <= strLen) && (wcscmp(str + strLen - endLen, endstr) == 0); } @@ -159,7 +156,7 @@ float coco_string_toFloat(const wchar_t* str) // wchar_t* coco_string_create(const char* str) { - int len = str ? strlen(str) : 0; + const int len = str ? strlen(str) : 0; wchar_t* dest = new wchar_t[len + 1]; for (int i = 0; i < len; ++i) { dest[i] = wchar_t(str[i]); @@ -169,7 +166,7 @@ wchar_t* coco_string_create(const char* str) { } wchar_t* coco_string_create(const char* str, int index, int length) { - int len = str ? length : 0; + const int len = str ? length : 0; wchar_t* dest = new wchar_t[len + 1]; for (int i = 0; i < len; ++i) { dest[i] = wchar_t(str[index + i]); @@ -180,8 +177,8 @@ wchar_t* coco_string_create(const char* str, int index, int length) { char* coco_string_create_char(const wchar_t* str) { - int len = coco_string_length(str); - char *dest = new char[len + 1]; + const int len = coco_string_length(str); + char* dest = new char[len + 1]; for (int i = 0; i < len; ++i) { dest[i] = char(str[i]); @@ -191,11 +188,8 @@ char* coco_string_create_char(const wchar_t* str) { } char* coco_string_create_char(const wchar_t* str, int index, int length) { - int len = coco_string_length(str); - if (len) { - len = length; - } - char *dest = new char[len + 1]; + const int len = (str && *str) ? length : 0; + char* dest = new char[len + 1]; for (int i = 0; i < len; ++i) { dest[i] = char(str[index + i]); } @@ -589,25 +583,29 @@ Scanner::~Scanner() { void Scanner::Init() { for (int i = 65; i <= 90; ++i) start.set(i, 1); + for (int i = 95; i <= 95; ++i) start.set(i, 1); for (int i = 97; i <= 122; ++i) start.set(i, 1); - for (int i = 36; i <= 36; ++i) start.set(i, 5); - start.set(45, 20); + start.set(45, 21); for (int i = 48; i <= 57; ++i) start.set(i, 9); start.set(34, 2); + start.set(36, 5); start.set(46, 7); start.set(123, 14); start.set(125, 15); - start.set(43, 21); + start.set(43, 22); start.set(42, 16); start.set(47, 17); start.set(40, 18); start.set(41, 19); + start.set(44, 20); start.set(Buffer::EoF, -1); tvalLength = 128; tval = new wchar_t[tvalLength]; // text of current token + tlen = 0; + tval[tlen] = 0; // HEAP_BLOCK_SIZE byte heap + pointer to next heap block heap = malloc(HEAP_BLOCK_SIZE + sizeof(void*)); @@ -813,7 +811,7 @@ Token* Scanner::NextToken() { case 0: { t->kind = noSym; break; } // NextCh already done case 1: case_1: - if ((ch >= L'0' && ch <= L':') || (ch >= L'A' && ch <= L'Z') || ch == L'_' || (ch >= L'a' && ch <= L'z')) {AddCh(); goto case_1;} + if ((ch >= L'0' && ch <= L'9') || (ch >= L'A' && ch <= L'Z') || ch == L'_' || (ch >= L'a' && ch <= L'z')) {AddCh(); goto case_1;} else {t->kind = 1; break;} case 2: case_2: @@ -829,11 +827,11 @@ Token* Scanner::NextToken() { case_4: {t->kind = 2; break;} case 5: - if ((ch >= L'A' && ch <= L'Z') || (ch >= L'a' && ch <= L'z')) {AddCh(); goto case_6;} + if ((ch >= L'A' && ch <= L'Z') || ch == L'_' || (ch >= L'a' && ch <= L'z')) {AddCh(); goto case_6;} else {t->kind = noSym; break;} case 6: case_6: - if ((ch >= L'0' && ch <= L':') || (ch >= L'A' && ch <= L'Z') || ch == L'_' || (ch >= L'a' && ch <= L'z')) {AddCh(); goto case_6;} + if ((ch >= L'0' && ch <= L'9') || (ch >= L'A' && ch <= L'Z') || ch == L'_' || (ch >= L'a' && ch <= L'z')) {AddCh(); goto case_6;} else {t->kind = 3; break;} case 7: case_7: @@ -880,9 +878,11 @@ Token* Scanner::NextToken() { case 19: {t->kind = 12; break;} case 20: + {t->kind = 13; break;} + case 21: if (ch == L'.') {AddCh(); goto case_7;} else {t->kind = 8; break;} - case 21: + case 22: if (ch == L'.') {AddCh(); goto case_7;} else {t->kind = 7; break;} diff --git a/applications/test/dictionary/calcEntry/calcEntryScanner.h b/applications/test/dictionary/calcEntry/calcEntryScanner.h index fdebddeebe..9ea17302c6 100644 --- a/applications/test/dictionary/calcEntry/calcEntryScanner.h +++ b/applications/test/dictionary/calcEntry/calcEntryScanner.h @@ -219,7 +219,6 @@ public: //------------------------------------------------------------------------------ //! maps characters (integers) to start states of tokens class StartStates { -private: class Elem { public: int key, val; @@ -235,7 +234,7 @@ public: StartStates() : tab(new Elem*[128]) { - memset(tab, 0, 128 * sizeof(Elem*)); + memset(tab, 0, 128*sizeof(Elem*)); } virtual ~StartStates() { @@ -252,7 +251,7 @@ public: void set(int key, int val) { Elem *e = new Elem(key, val); - int k = unsigned(key) % 128; + const int k = unsigned(key) % 128; e->next = tab[k]; tab[k] = e; } @@ -270,7 +269,6 @@ public: //------------------------------------------------------------------------------ //! maps strings to integers (identifiers to keyword kinds) class KeywordMap { -private: class Elem { public: wchar_t *key; @@ -290,7 +288,7 @@ public: KeywordMap() : tab(new Elem*[128]) { - memset(tab, 0, 128 * sizeof(Elem*)); + memset(tab, 0, 128*sizeof(Elem*)); } virtual ~KeywordMap() { @@ -323,8 +321,8 @@ public: //! A Coco/R Scanner class Scanner { private: - static const int maxT = 13; - static const int noSym = 13; + static const int maxT = 14; + static const int noSym = 14; static const int eofSym = 0; //!< end-of-file token id static const char EOL = '\n'; //!< end-of-line character diff --git a/applications/test/dictionary/calcEntry/staticMemberFunctionSelectionTables.H b/applications/test/dictionary/calcEntry/staticMemberFunctionSelectionTables.H new file mode 100644 index 0000000000..3febd71e8a --- /dev/null +++ b/applications/test/dictionary/calcEntry/staticMemberFunctionSelectionTables.H @@ -0,0 +1,147 @@ +/*---------------------------------------------------------------------------*\ + ========= | + \\ / F ield | OpenFOAM: The Open Source CFD Toolbox + \\ / O peration | + \\ / A nd | Copyright (C) 2010-2010 OpenCFD Ltd. + \\/ M anipulation | +------------------------------------------------------------------------------- +License + This file is part of OpenFOAM. + + OpenFOAM 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 2 of the License, or (at your + option) any later version. + + OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation, + Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +@file Foam::staticMemberFunctionSelectionTables + +Description + Macros to enable the easy declaration of member function selection tables. + +\*---------------------------------------------------------------------------*/ + +#ifndef staticMemberFunctionSelectionTables_H +#define staticMemberFunctionSelectionTables_H + +#include "memberFunctionSelectionTables.H" + +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + + +// external use: +// ~~~~~~~~~~~~~ +// declare a run-time selection: +#define declareStaticMemberFunctionSelectionTable\ +(returnType,baseType,memberFunction,argNames,argList,parList) \ + \ + /* Construct from argList function pointer type */ \ + typedef returnType (*memberFunction##argNames##MemberFunctionPtr)argList; \ + \ + /* Construct from argList function table type */ \ + typedef HashTable \ + \ + memberFunction##argNames##MemberFunctionTable; \ + \ + /* Construct from argList function pointer table pointer */ \ + static memberFunction##argNames##MemberFunctionTable* \ + memberFunction##argNames##MemberFunctionTablePtr_; \ + \ + /* Table memberFunction called from the table add function */ \ + static void construct##memberFunction##argNames##MemberFunctionTables(); \ + \ + /* Table destructor called from the table add function destructor */ \ + static void destroy##memberFunction##argNames##MemberFunctionTables(); \ + \ + /* Class to add constructor from argList to table */ \ + template \ + class add##memberFunction##argNames##StaticMemberFunctionToTable \ + { \ + public: \ + \ + add##memberFunction##argNames##StaticMemberFunctionToTable \ + ( \ + const word& lookup, \ + memberFunction##argNames##MemberFunctionPtr function \ + ) \ + { \ + construct##memberFunction##argNames##MemberFunctionTables(); \ + memberFunction##argNames##MemberFunctionTablePtr_->insert \ + ( \ + lookup, \ + function \ + ); \ + } \ + \ + ~add##memberFunction##argNames##StaticMemberFunctionToTable() \ + { \ + destroy##memberFunction##argNames##MemberFunctionTables(); \ + } \ + } + + +// internal use: +// constructor/destructor aid +#define defineStaticMemberFunctionSelectionTableConstructDestruct\ +(baseType,memberFunction,argNames) \ + \ + /* Table constructor called from the table add function constructor */ \ + void baseType::construct##memberFunction##argNames##MemberFunctionTables()\ + { \ + static bool constructed = false; \ + if (!constructed) \ + { \ + constructed = true; \ + baseType::memberFunction##argNames##MemberFunctionTablePtr_ \ + = new baseType::memberFunction##argNames##MemberFunctionTable;\ + } \ + }; \ + \ + /* Table destructor called from the table add function destructor */ \ + void baseType::destroy##memberFunction##argNames##MemberFunctionTables() \ + { \ + if (baseType::memberFunction##argNames##MemberFunctionTablePtr_) \ + { \ + delete baseType::memberFunction##argNames##MemberFunctionTablePtr_;\ + baseType::memberFunction##argNames##MemberFunctionTablePtr_ = NULL;\ + } \ + } + + +// internal use: +// create pointer to hash-table of functions +#define defineStaticMemberFunctionSelectionTablePtr\ +(baseType,memberFunction,argNames) \ + \ + /* Define the memberFunction table */ \ + baseType::memberFunction##argNames##MemberFunctionTable* \ + baseType::memberFunction##argNames##MemberFunctionTablePtr_ = NULL + + +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + +// external use: +// ~~~~~~~~~~~~~ +// define run-time selection table +#define defineStaticMemberFunctionSelectionTable\ +(baseType,memberFunction,argNames) \ + \ + defineStaticMemberFunctionSelectionTablePtr \ + (baseType,memberFunction,argNames); \ + defineStaticMemberFunctionSelectionTableConstructDestruct \ + (baseType,memberFunction,argNames) \ + +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + + +#endif + +// ************************************************************************* // diff --git a/applications/test/dictionary/testDictCalc b/applications/test/dictionary/testDictCalc index f1d67650e8..6f2c38a51c 100644 --- a/applications/test/dictionary/testDictCalc +++ b/applications/test/dictionary/testDictCalc @@ -37,7 +37,13 @@ p this calculation #calc{ is done inplace; -flowRate #calc{ $flowRatePerHour / 3600}; +flowRate #calc{ $flowRatePerHour / 3600 }; + +sin45 #calc{ sin( 45*pi() / 180 ) }; +cos45 #calc{ cos( degToRad(45) ) }; +pow #calc{ pow( $x, $y ) }; +log10 #calc{ log( 1e6 ) }; +// list #calc{ list() }; xxx yyy; foo 30; From cf91174880bb99ce96bdc1abdba5dcb22c6ad51b Mon Sep 17 00:00:00 2001 From: Mark Olesen Date: Sat, 2 Jan 2010 15:09:17 +0100 Subject: [PATCH 02/42] Use global lookup tables for the calcEntry scalar functions. Handle leading signs on functions etc. --- .../addToGlobalFunctionSelectionTable.H | 53 ++++++ .../test/dictionary/calcEntry/calcEntry.atg | 33 ++-- .../dictionary/calcEntry/calcEntryInternal.C | 171 ++++++------------ .../dictionary/calcEntry/calcEntryInternal.H | 54 ++---- .../dictionary/calcEntry/calcEntryParser.cpp | 28 +-- .../dictionary/calcEntry/calcEntryParser.h | 5 +- .../calcEntry/globalFunctionSelectionTables.H | 145 +++++++++++++++ applications/test/dictionary/testDictCalc | 7 +- 8 files changed, 314 insertions(+), 182 deletions(-) create mode 100644 applications/test/dictionary/calcEntry/addToGlobalFunctionSelectionTable.H create mode 100644 applications/test/dictionary/calcEntry/globalFunctionSelectionTables.H diff --git a/applications/test/dictionary/calcEntry/addToGlobalFunctionSelectionTable.H b/applications/test/dictionary/calcEntry/addToGlobalFunctionSelectionTable.H new file mode 100644 index 0000000000..d6eadfdd74 --- /dev/null +++ b/applications/test/dictionary/calcEntry/addToGlobalFunctionSelectionTable.H @@ -0,0 +1,53 @@ +/*---------------------------------------------------------------------------*\ + ========= | + \\ / F ield | OpenFOAM: The Open Source CFD Toolbox + \\ / O peration | + \\ / A nd | Copyright (C) 2010-2010 OpenCFD Ltd. + \\/ M anipulation | +------------------------------------------------------------------------------- +License + This file is part of OpenFOAM. + + OpenFOAM 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 2 of the License, or (at your + option) any later version. + + OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation, + Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +@file Foam::addToGlobalFunctionSelectionTable + +Description + Macros for easy insertion into global function selection tables + +\*---------------------------------------------------------------------------*/ + +#ifndef addToGlobalFunctionSelectionTable_H +#define addToGlobalFunctionSelectionTable_H + +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + + +// add to hash-table of functions with 'lookup' as the key +#define addNamedToGlobalFunctionSelectionTable\ +(memberFunction,argNames,lookup,functionPtr) \ + \ + /* Add to the table, find by lookup name */ \ + add##memberFunction##argNames##GlobalMemberFunctionToTable \ + add_##lookup##_##memberFunction##argNames##GlobalMemberFunctionTo##Table_\ + (#lookup, functionPtr) + + +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + + +#endif + +// ************************************************************************* // diff --git a/applications/test/dictionary/calcEntry/calcEntry.atg b/applications/test/dictionary/calcEntry/calcEntry.atg index 57646c3cad..ac6766aae4 100644 --- a/applications/test/dictionary/calcEntry/calcEntry.atg +++ b/applications/test/dictionary/calcEntry/calcEntry.atg @@ -39,10 +39,7 @@ SourceFiles \*---------------------------------------------------------------------------*/ #include "dictionary.H" -#include "scalar.H" -#include "error.H" #include "wchar.H" -#include "DynamicList.H" #include "calcEntryInternal.H" @@ -56,7 +53,7 @@ COMPILER calcEntry private: //- The parent dictionary - mutable dictionary* dict_; + dictionary* dict_; //- The calculation result scalar val; @@ -196,8 +193,8 @@ Expr (. scalar val2 = 0; .) = Term { - "+" Term (. val += val2; .) - | "-" Term (. val -= val2; .) + '+' Term (. val += val2; .) + | '-' Term (. val -= val2; .) } . @@ -208,20 +205,26 @@ Term (. scalar val2 = 0; .) = Factor { - "*" Factor (. val *= val2; .) - | "/" Factor (. val /= val2; .) + '*' Factor (. val *= val2; .) + | '/' Factor (. val /= val2; .) } . /*---------------------------------------------------------------------------*/ -Factor + +// Note the treatment of the leading signs is fairly generous +// eg, "10 + - 10" is treated like "10 + -10" +// +Factor (. bool negative = false; .) = - Func - | variable (. val = getDictLookup(); .) - | number (. val = coco_string_toDouble(t->val); .) - | '-' '(' Expr ')' (. val = -val; .) - | '(' Expr ')' + ['+' | '-' (. negative = true; .) + ] + ( + Func | '(' Expr ')' + | variable (. val = getDictLookup(); .) + | number (. val = coco_string_toDouble(t->val); .) + ) (. if (negative) { val = -val; } .) . @@ -242,7 +245,7 @@ Func { ',' Expr (. param.append(x); .) } ] - ')' (. val = scalarFunctions::dispatch(funcName, param); .) + ')' (. val = dispatch(funcName, param); .) . diff --git a/applications/test/dictionary/calcEntry/calcEntryInternal.C b/applications/test/dictionary/calcEntry/calcEntryInternal.C index 888475cee6..086238d9a3 100644 --- a/applications/test/dictionary/calcEntry/calcEntryInternal.C +++ b/applications/test/dictionary/calcEntry/calcEntryInternal.C @@ -25,8 +25,7 @@ License \*---------------------------------------------------------------------------*/ #include "calcEntryInternal.H" -#include "addToMemberFunctionSelectionTable.H" -#include "addToStaticMemberFunctionSelectionTable.H" +#include "addToGlobalFunctionSelectionTable.H" #include "unitConversion.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // @@ -38,14 +37,66 @@ namespace functionEntries namespace calcEntryInternal { -defineStaticMemberFunctionSelectionTable(scalarFunctions,dispatch,ParamList); +defineGlobalFunctionSelectionTable(dispatch,ParamList); -scalar scalarFunctions::dispatch -( - const word& name, - const UList& param -) +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + +#define globalConstant0(Name, Constant)\ +scalar Name##_0(const UList& param) \ +{ \ + return Constant; \ +} \ +addNamedToGlobalFunctionSelectionTable(dispatch,ParamList,Name##_0,&Name##_0) + + +#define globalFunction0(Name, Function)\ +scalar Name##_0(const UList& param) \ +{ \ + return Function(); \ +} \ +addNamedToGlobalFunctionSelectionTable(dispatch,ParamList,Name##_0,&Name##_0) + + +#define globalFunction1(Name, Function)\ +scalar Name##_1(const UList& param) \ +{ \ + return Function(param[0]); \ +} \ +addNamedToGlobalFunctionSelectionTable(dispatch,ParamList,Name##_1,&Name##_1) + + +#define globalFunction2(Name, Function)\ +scalar Name##_2(const UList& param) \ +{ \ + return Function(param[0], param[1]); \ +} \ +addNamedToGlobalFunctionSelectionTable(dispatch,ParamList,Name##_2,&Name##_2) + + +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + +globalConstant0(pi, constant::mathematical::pi); + +globalFunction1(degToRad, degToRad); +globalFunction1(radToDeg, radToDeg); +globalFunction1(asin, Foam::asin); +globalFunction1(acos, Foam::acos); +globalFunction1(atan, Foam::atan); +globalFunction1(sin, Foam::sin); +globalFunction1(cos, Foam::cos); +globalFunction1(tan, Foam::tan); +globalFunction1(log, Foam::log); +globalFunction1(log10, Foam::log10); +globalFunction1(mag, Foam::mag); + +globalFunction2(atan2, Foam::atan2); +globalFunction2(pow, Foam::pow); + + +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + +scalar dispatch(const word& name, const UList& param) { // create lookup name with parameter count const word lookupName = name + '_' + Foam::name(param.size()); @@ -69,114 +120,10 @@ scalar scalarFunctions::dispatch } -scalar scalarFunctions::pi_0(const UList& param) -{ - return constant::mathematical::pi; -} - -scalar scalarFunctions::degToRad_1(const UList& param) -{ - return degToRad(param[0]); -} - -scalar scalarFunctions::radToDeg_1(const UList& param) -{ - return radToDeg(param[0]); -} - -scalar scalarFunctions::sin_1(const UList& param) -{ - return Foam::sin(param[0]); -} - -scalar scalarFunctions::cos_1(const UList& param) -{ - return Foam::cos(param[0]); -} - -scalar scalarFunctions::pow_2(const UList& param) -{ - return Foam::pow(param[0], param[1]); -} - -scalar scalarFunctions::log_1(const UList& param) -{ - return Foam::log(param[0]); -} - -scalar scalarFunctions::log10_1(const UList& param) -{ - return Foam::log10(param[0]); -} - - - -addNamedToStaticMemberFunctionSelectionTable -( - scalarFunctions,scalarFunctions,dispatch,ParamList, - pi_0, - &scalarFunctions::pi_0 -); - -addNamedToStaticMemberFunctionSelectionTable -( - scalarFunctions,scalarFunctions,dispatch,ParamList, - degToRad_1, - &scalarFunctions::degToRad_1 -); - -addNamedToStaticMemberFunctionSelectionTable -( - scalarFunctions,scalarFunctions,dispatch,ParamList, - radToDeg_1, - &scalarFunctions::radToDeg_1 -); - -addNamedToStaticMemberFunctionSelectionTable -( - scalarFunctions,scalarFunctions,dispatch,ParamList, - sin_1, - &scalarFunctions::sin_1 -); - -addNamedToStaticMemberFunctionSelectionTable -( - scalarFunctions,scalarFunctions,dispatch,ParamList, - cos_1, - &scalarFunctions::cos_1 -); - -addNamedToStaticMemberFunctionSelectionTable -( - scalarFunctions,scalarFunctions,dispatch,ParamList, - pow_2, - &scalarFunctions::pow_2 -); - -addNamedToStaticMemberFunctionSelectionTable -( - scalarFunctions,scalarFunctions,dispatch,ParamList, - log_1, - &scalarFunctions::log_1 -); - - - -addNamedToStaticMemberFunctionSelectionTable -( - scalarFunctions,scalarFunctions,dispatch,ParamList, - log10_1, - &scalarFunctions::log10_1 -); - - // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace calcEntryInternal } // End namespace functionEntries } // End namespace Foam -// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // - - // ************************************************************************* // diff --git a/applications/test/dictionary/calcEntry/calcEntryInternal.H b/applications/test/dictionary/calcEntry/calcEntryInternal.H index 73ff08c7e4..2dd3a03056 100644 --- a/applications/test/dictionary/calcEntry/calcEntryInternal.H +++ b/applications/test/dictionary/calcEntry/calcEntryInternal.H @@ -26,8 +26,7 @@ Namespace Foam::functionEntries::calcEntryInternal Description - This dictionary function entry may or may not do anything particularly - useful - depending upon what is currently being used to test. + Contains global functions and classes for the calcEntry. SourceFiles calcEntryInternal.C @@ -37,9 +36,10 @@ SourceFiles #ifndef calcEntryInternal_H #define calcEntryInternal_H -#include "functionEntry.H" -#include "memberFunctionSelectionTables.H" -#include "staticMemberFunctionSelectionTables.H" +#include "error.H" +#include "scalar.H" +#include "DynamicList.H" +#include "globalFunctionSelectionTables.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // @@ -50,42 +50,22 @@ namespace functionEntries namespace calcEntryInternal { -/*---------------------------------------------------------------------------*\ - Class calcEntryFunctions Declaration -\*---------------------------------------------------------------------------*/ + // Global Function Selectors -class scalarFunctions -{ -public: - - // Member Function Selectors - - declareStaticMemberFunctionSelectionTable + declareGlobalFunctionSelectionTable + ( + scalar, + dispatch, + ParamList, ( - scalar, - scalarFunctions, - dispatch, - ParamList, - ( - const UList& param - ), - (param) - ); - - //- Calculate - static scalar dispatch(const word&, const UList&); + const UList& param + ), + (param) + ); - static scalar pi_0(const UList&); - static scalar degToRad_1(const UList&); - static scalar radToDeg_1(const UList&); - static scalar cos_1(const UList&); - static scalar sin_1(const UList&); - static scalar pow_2(const UList&); - static scalar log_1(const UList&); - static scalar log10_1(const UList&); - -}; + //- Dispatch calculation to the named function + scalar dispatch(const word&, const UList&); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // diff --git a/applications/test/dictionary/calcEntry/calcEntryParser.cpp b/applications/test/dictionary/calcEntry/calcEntryParser.cpp index 4fc4016207..e1a3937823 100644 --- a/applications/test/dictionary/calcEntry/calcEntryParser.cpp +++ b/applications/test/dictionary/calcEntry/calcEntryParser.cpp @@ -137,25 +137,29 @@ void Parser::Term(scalar& val) { } void Parser::Factor(scalar& val) { + bool negative = false; + if (la->kind == 7 || la->kind == 8) { + if (la->kind == 7) { + Get(); + } else { + Get(); + negative = true; + } + } if (la->kind == 1) { Func(val); + } else if (la->kind == 11) { + Get(); + Expr(val); + Expect(12); } else if (la->kind == 3) { Get(); val = getDictLookup(); } else if (la->kind == 4) { Get(); val = coco_string_toDouble(t->val); - } else if (la->kind == 8) { - Get(); - Expect(11); - Expr(val); - Expect(12); - val = -val; - } else if (la->kind == 11) { - Get(); - Expr(val); - Expect(12); } else SynErr(16); + if (negative) { val = -val; } } void Parser::Func(scalar& val) { @@ -177,7 +181,7 @@ void Parser::Func(scalar& val) { } } Expect(12); - val = scalarFunctions::dispatch(funcName, param); + val = dispatch(funcName, param); } @@ -225,7 +229,7 @@ bool Parser::StartOf(int s) { static const bool set[2][16] = { {T,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x}, - {x,T,x,T, T,x,x,x, T,x,x,T, x,x,x,x} + {x,T,x,T, T,x,x,T, T,x,x,T, x,x,x,x} }; diff --git a/applications/test/dictionary/calcEntry/calcEntryParser.h b/applications/test/dictionary/calcEntry/calcEntryParser.h index afa25782a7..cfc036ccec 100644 --- a/applications/test/dictionary/calcEntry/calcEntryParser.h +++ b/applications/test/dictionary/calcEntry/calcEntryParser.h @@ -4,10 +4,7 @@ #define COCO_calcEntryPARSER_H__ #include "dictionary.H" -#include "scalar.H" -#include "error.H" #include "wchar.H" -#include "DynamicList.H" #include "calcEntryInternal.H" @@ -81,7 +78,7 @@ public: private: //- The parent dictionary - mutable dictionary* dict_; + dictionary* dict_; //- The calculation result scalar val; diff --git a/applications/test/dictionary/calcEntry/globalFunctionSelectionTables.H b/applications/test/dictionary/calcEntry/globalFunctionSelectionTables.H new file mode 100644 index 0000000000..4a7dfb4ac4 --- /dev/null +++ b/applications/test/dictionary/calcEntry/globalFunctionSelectionTables.H @@ -0,0 +1,145 @@ +/*---------------------------------------------------------------------------*\ + ========= | + \\ / F ield | OpenFOAM: The Open Source CFD Toolbox + \\ / O peration | + \\ / A nd | Copyright (C) 2010-2010 OpenCFD Ltd. + \\/ M anipulation | +------------------------------------------------------------------------------- +License + This file is part of OpenFOAM. + + OpenFOAM 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 2 of the License, or (at your + option) any later version. + + OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation, + Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +@file Foam::globalFunctionSelectionTables + +Description + Macros to enable the easy declaration of global function selection tables. + +\*---------------------------------------------------------------------------*/ + +#ifndef globalMemberFunctionSelectionTables_H +#define globalMemberFunctionSelectionTables_H + +#include "memberFunctionSelectionTables.H" + +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + + +// external use: +// ~~~~~~~~~~~~~ +// declare a run-time selection: +#define declareGlobalFunctionSelectionTable\ +(returnType,memberFunction,argNames,argList,parList) \ + \ + /* Construct from argList function pointer type */ \ + typedef returnType (*memberFunction##argNames##MemberFunctionPtr)argList; \ + \ + /* Construct from argList function table type */ \ + typedef HashTable \ + \ + memberFunction##argNames##MemberFunctionTable; \ + \ + /* Construct from argList function pointer table pointer */ \ + extern memberFunction##argNames##MemberFunctionTable* \ + memberFunction##argNames##MemberFunctionTablePtr_; \ + \ + /* Table memberFunction called from the table add function */ \ + void construct##memberFunction##argNames##MemberFunctionTables(); \ + \ + /* Table destructor called from the table add function destructor */ \ + void destroy##memberFunction##argNames##MemberFunctionTables(); \ + \ + /* Class to add constructor from argList to table */ \ + class add##memberFunction##argNames##GlobalMemberFunctionToTable \ + { \ + public: \ + \ + add##memberFunction##argNames##GlobalMemberFunctionToTable \ + ( \ + const word& lookup, \ + memberFunction##argNames##MemberFunctionPtr function \ + ) \ + { \ + construct##memberFunction##argNames##MemberFunctionTables(); \ + memberFunction##argNames##MemberFunctionTablePtr_->insert \ + ( \ + lookup, \ + function \ + ); \ + } \ + \ + ~add##memberFunction##argNames##GlobalMemberFunctionToTable() \ + { \ + destroy##memberFunction##argNames##MemberFunctionTables(); \ + } \ + } + +// internal use: +// constructor/destructor aid +#define defineGlobalFunctionSelectionTableConstructDestruct\ +(memberFunction,argNames) \ + \ + /* Table constructor called from the table add function */ \ + void construct##memberFunction##argNames##MemberFunctionTables()\ + { \ + static bool constructed = false; \ + if (!constructed) \ + { \ + constructed = true; \ + memberFunction##argNames##MemberFunctionTablePtr_ \ + = new memberFunction##argNames##MemberFunctionTable; \ + } \ + } \ + \ + /* Table destructor called from the table add function destructor */ \ + void destroy##memberFunction##argNames##MemberFunctionTables()\ + { \ + if (memberFunction##argNames##MemberFunctionTablePtr_) \ + { \ + delete memberFunction##argNames##MemberFunctionTablePtr_; \ + memberFunction##argNames##MemberFunctionTablePtr_ = NULL; \ + } \ + } + + +// internal use: +// create pointer to hash-table of functions +#define defineGlobalFunctionSelectionTablePtr\ +(memberFunction,argNames) \ + \ + /* Define the memberFunction table */ \ + memberFunction##argNames##MemberFunctionTable* \ + memberFunction##argNames##MemberFunctionTablePtr_ = NULL + + +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + +// external use: +// ~~~~~~~~~~~~~ +// define run-time selection table +#define defineGlobalFunctionSelectionTable\ +(memberFunction,argNames) \ + \ + defineGlobalFunctionSelectionTablePtr \ + (memberFunction,argNames); \ + defineGlobalFunctionSelectionTableConstructDestruct \ + (memberFunction,argNames) + +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + + +#endif + +// ************************************************************************* // diff --git a/applications/test/dictionary/testDictCalc b/applications/test/dictionary/testDictCalc index 6f2c38a51c..092a933a29 100644 --- a/applications/test/dictionary/testDictCalc +++ b/applications/test/dictionary/testDictCalc @@ -39,8 +39,11 @@ is done inplace; flowRate #calc{ $flowRatePerHour / 3600 }; -sin45 #calc{ sin( 45*pi() / 180 ) }; -cos45 #calc{ cos( degToRad(45) ) }; +// inplace redefine +flowRate #calc{ $flowRate * 0.1 }; + +sin45 #calc{ sin( 45.0 * pi() / 180 ) }; +cos45 #calc{ cos( degToRad(15- -15+ +15) ) }; pow #calc{ pow( $x, $y ) }; log10 #calc{ log( 1e6 ) }; // list #calc{ list() }; From d1a2be78724755441a53ef5b01cb71516acc44ce Mon Sep 17 00:00:00 2001 From: Mark Olesen Date: Sat, 2 Jan 2010 16:09:08 +0100 Subject: [PATCH 03/42] Reorganize runTimeSelection to include new macros from calcEntry. Added globalFunctionSelectionTables, staticMemberFunctionSelectionTables --- .../{ => construction}/addToRunTimeSelectionTable.H | 0 .../runTimeSelection/{ => construction}/runTimeSelectionTables.H | 0 .../globalFunctions}/addToGlobalFunctionSelectionTable.H | 0 .../globalFunctions}/globalFunctionSelectionTables.H | 0 .../memberFunctions}/addToMemberFunctionSelectionTable.H | 0 .../memberFunctions}/memberFunctionSelectionTables.H | 0 .../addToStaticMemberFunctionSelectionTable.H | 0 .../staticMemberFunctions}/staticMemberFunctionSelectionTables.H | 0 8 files changed, 0 insertions(+), 0 deletions(-) rename src/OpenFOAM/db/runTimeSelection/{ => construction}/addToRunTimeSelectionTable.H (100%) rename src/OpenFOAM/db/runTimeSelection/{ => construction}/runTimeSelectionTables.H (100%) rename {applications/test/dictionary/calcEntry => src/OpenFOAM/db/runTimeSelection/globalFunctions}/addToGlobalFunctionSelectionTable.H (100%) rename {applications/test/dictionary/calcEntry => src/OpenFOAM/db/runTimeSelection/globalFunctions}/globalFunctionSelectionTables.H (100%) rename src/OpenFOAM/db/{memberFunctionSelection => runTimeSelection/memberFunctions}/addToMemberFunctionSelectionTable.H (100%) rename src/OpenFOAM/db/{memberFunctionSelection => runTimeSelection/memberFunctions}/memberFunctionSelectionTables.H (100%) rename {applications/test/dictionary/calcEntry => src/OpenFOAM/db/runTimeSelection/staticMemberFunctions}/addToStaticMemberFunctionSelectionTable.H (100%) rename {applications/test/dictionary/calcEntry => src/OpenFOAM/db/runTimeSelection/staticMemberFunctions}/staticMemberFunctionSelectionTables.H (100%) diff --git a/src/OpenFOAM/db/runTimeSelection/addToRunTimeSelectionTable.H b/src/OpenFOAM/db/runTimeSelection/construction/addToRunTimeSelectionTable.H similarity index 100% rename from src/OpenFOAM/db/runTimeSelection/addToRunTimeSelectionTable.H rename to src/OpenFOAM/db/runTimeSelection/construction/addToRunTimeSelectionTable.H diff --git a/src/OpenFOAM/db/runTimeSelection/runTimeSelectionTables.H b/src/OpenFOAM/db/runTimeSelection/construction/runTimeSelectionTables.H similarity index 100% rename from src/OpenFOAM/db/runTimeSelection/runTimeSelectionTables.H rename to src/OpenFOAM/db/runTimeSelection/construction/runTimeSelectionTables.H diff --git a/applications/test/dictionary/calcEntry/addToGlobalFunctionSelectionTable.H b/src/OpenFOAM/db/runTimeSelection/globalFunctions/addToGlobalFunctionSelectionTable.H similarity index 100% rename from applications/test/dictionary/calcEntry/addToGlobalFunctionSelectionTable.H rename to src/OpenFOAM/db/runTimeSelection/globalFunctions/addToGlobalFunctionSelectionTable.H diff --git a/applications/test/dictionary/calcEntry/globalFunctionSelectionTables.H b/src/OpenFOAM/db/runTimeSelection/globalFunctions/globalFunctionSelectionTables.H similarity index 100% rename from applications/test/dictionary/calcEntry/globalFunctionSelectionTables.H rename to src/OpenFOAM/db/runTimeSelection/globalFunctions/globalFunctionSelectionTables.H diff --git a/src/OpenFOAM/db/memberFunctionSelection/addToMemberFunctionSelectionTable.H b/src/OpenFOAM/db/runTimeSelection/memberFunctions/addToMemberFunctionSelectionTable.H similarity index 100% rename from src/OpenFOAM/db/memberFunctionSelection/addToMemberFunctionSelectionTable.H rename to src/OpenFOAM/db/runTimeSelection/memberFunctions/addToMemberFunctionSelectionTable.H diff --git a/src/OpenFOAM/db/memberFunctionSelection/memberFunctionSelectionTables.H b/src/OpenFOAM/db/runTimeSelection/memberFunctions/memberFunctionSelectionTables.H similarity index 100% rename from src/OpenFOAM/db/memberFunctionSelection/memberFunctionSelectionTables.H rename to src/OpenFOAM/db/runTimeSelection/memberFunctions/memberFunctionSelectionTables.H diff --git a/applications/test/dictionary/calcEntry/addToStaticMemberFunctionSelectionTable.H b/src/OpenFOAM/db/runTimeSelection/staticMemberFunctions/addToStaticMemberFunctionSelectionTable.H similarity index 100% rename from applications/test/dictionary/calcEntry/addToStaticMemberFunctionSelectionTable.H rename to src/OpenFOAM/db/runTimeSelection/staticMemberFunctions/addToStaticMemberFunctionSelectionTable.H diff --git a/applications/test/dictionary/calcEntry/staticMemberFunctionSelectionTables.H b/src/OpenFOAM/db/runTimeSelection/staticMemberFunctions/staticMemberFunctionSelectionTables.H similarity index 100% rename from applications/test/dictionary/calcEntry/staticMemberFunctionSelectionTables.H rename to src/OpenFOAM/db/runTimeSelection/staticMemberFunctions/staticMemberFunctionSelectionTables.H From ebfdafad7f0ed90ee990602888a224507311fb02 Mon Sep 17 00:00:00 2001 From: Mark Olesen Date: Sun, 3 Jan 2010 00:39:28 +0100 Subject: [PATCH 04/42] Add preliminary wmake rule for using CoCo/R. --- applications/test/dictionary/Allwmake | 11 +- applications/test/dictionary/Make/files | 5 +- applications/test/dictionary/Make/options | 2 + .../{calcEntry.atg => calcEntryParser.ATG} | 18 +- .../dictionary/calcEntry/calcEntryParser.cpp | 340 ------- .../dictionary/calcEntry/calcEntryParser.h | 180 ---- .../dictionary/calcEntry/calcEntryScanner.cpp | 932 ------------------ .../dictionary/calcEntry/calcEntryScanner.h | 396 -------- wmake/rules/General/coco | 6 + wmake/rules/General/standard | 1 + 10 files changed, 23 insertions(+), 1868 deletions(-) rename applications/test/dictionary/calcEntry/{calcEntry.atg => calcEntryParser.ATG} (95%) delete mode 100644 applications/test/dictionary/calcEntry/calcEntryParser.cpp delete mode 100644 applications/test/dictionary/calcEntry/calcEntryParser.h delete mode 100644 applications/test/dictionary/calcEntry/calcEntryScanner.cpp delete mode 100644 applications/test/dictionary/calcEntry/calcEntryScanner.h create mode 100644 wmake/rules/General/coco diff --git a/applications/test/dictionary/Allwmake b/applications/test/dictionary/Allwmake index fcf297dc89..86ec8fd45d 100755 --- a/applications/test/dictionary/Allwmake +++ b/applications/test/dictionary/Allwmake @@ -3,13 +3,8 @@ cd ${0%/*} || exit 1 # run from this directory # this will have to do until we have a makefile rule -if type Coco > /dev/null 2>&1 -then - Coco \ - -frames $WM_THIRD_PARTY_DIR/coco-r \ - calcEntry/calcEntry.atg -else - echo "Coco not installed" -fi +type Coco > /dev/null 2>&1 || { + echo "Coco not installed -- cannot make this test" +} wmake diff --git a/applications/test/dictionary/Make/files b/applications/test/dictionary/Make/files index ff7a3caad4..89d95d0298 100644 --- a/applications/test/dictionary/Make/files +++ b/applications/test/dictionary/Make/files @@ -1,8 +1,7 @@ dictionaryTest.C -calcEntry/calcEntry.C +calcEntry/calcEntryParser.ATG calcEntry/calcEntryInternal.C -calcEntry/calcEntryParser.cpp -calcEntry/calcEntryScanner.cpp +calcEntry/calcEntry.C EXE = $(FOAM_USER_APPBIN)/dictionaryTest diff --git a/applications/test/dictionary/Make/options b/applications/test/dictionary/Make/options index e69de29bb2..3af3c946ac 100644 --- a/applications/test/dictionary/Make/options +++ b/applications/test/dictionary/Make/options @@ -0,0 +1,2 @@ +EXE_INC = -IcalcEntry -I$(OBJECTS_DIR) + diff --git a/applications/test/dictionary/calcEntry/calcEntry.atg b/applications/test/dictionary/calcEntry/calcEntryParser.ATG similarity index 95% rename from applications/test/dictionary/calcEntry/calcEntry.atg rename to applications/test/dictionary/calcEntry/calcEntryParser.ATG index ac6766aae4..e1a1567700 100644 --- a/applications/test/dictionary/calcEntry/calcEntry.atg +++ b/applications/test/dictionary/calcEntry/calcEntryParser.ATG @@ -22,7 +22,7 @@ License along with OpenFOAM; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -@file calcEntry.atg +@file calcEntryParser.ATG Description An attributed Coco/R grammar to parse simple arithmetic expressions @@ -34,8 +34,8 @@ SourceFiles /*---------------------------------------------------------------------------*\ compile with: Coco \ - -frames $WM_THIRD_PARTY_DIR/coco-r \ - calcEntry.atg + [-single] -frames $WM_THIRD_PARTY_DIR/coco-r \ + calcEntryParser.ATG \*---------------------------------------------------------------------------*/ #include "dictionary.H" @@ -61,8 +61,6 @@ private: //- lookup dictionary entry scalar getDictLookup() const { - scalar dictValue = 0; - if (!dict_) { FatalErrorIn @@ -83,6 +81,8 @@ private: word keyword(str); coco_string_delete(str); + scalar dictValue = 0; + entry* entryPtr = dict_->lookupEntryPtr(keyword, true, false); if (entryPtr && !entryPtr->isDict()) { @@ -237,15 +237,15 @@ Func char* str = coco_string_create_char(t->val); word funcName(str); coco_string_delete(str); - DynamicList param(4); // hold parameter values + DynamicList stack(4); .) '(' [ (. scalar x; .) - Expr (. param.append(x); .) - { ',' Expr (. param.append(x); .) + Expr (. stack.append(x); .) + { ',' Expr (. stack.append(x); .) } ] - ')' (. val = dispatch(funcName, param); .) + ')' (. val = dispatch(funcName, stack); .) . diff --git a/applications/test/dictionary/calcEntry/calcEntryParser.cpp b/applications/test/dictionary/calcEntry/calcEntryParser.cpp deleted file mode 100644 index e1a3937823..0000000000 --- a/applications/test/dictionary/calcEntry/calcEntryParser.cpp +++ /dev/null @@ -1,340 +0,0 @@ - - -#include -#include "calcEntryParser.h" - - -namespace Foam { -namespace functionEntries { -namespace calcEntryInternal { - - -// ---------------------------------------------------------------------------- -// Parser Implementation -// ---------------------------------------------------------------------------- - -void Parser::SynErr(int n) { - if (errDist >= minErrDist) errors->SynErr(la->line, la->col, n); - errDist = 0; -} - - -void Parser::SemErr(const wchar_t* msg) { - if (errDist >= minErrDist) errors->Error(t->line, t->col, msg); - errDist = 0; -} - - -void Parser::Get() { - for (;;) { - t = la; - la = scanner->Scan(); - if (la->kind <= maxT) { - ++errDist; - break; - } - - if (dummyToken != t) { - dummyToken->kind = t->kind; - dummyToken->pos = t->pos; - dummyToken->col = t->col; - dummyToken->line = t->line; - dummyToken->next = NULL; - coco_string_delete(dummyToken->val); - dummyToken->val = coco_string_create(t->val); - t = dummyToken; - } - la = t; - } -} - - -void Parser::Expect(int n) { - if (la->kind == n) { - Get(); - } - else { - SynErr(n); - } -} - - -void Parser::ExpectWeak(int n, int follow) { - if (la->kind == n) { - Get(); - } - else { - SynErr(n); - while (!StartOf(follow)) { - Get(); - } - } -} - - -bool Parser::WeakSeparator(int n, int syFol, int repFol) { - if (la->kind == n) { - Get(); - return true; - } - else if (StartOf(repFol)) { - return false; - } - else { - SynErr(n); - while (!(StartOf(syFol) || StartOf(repFol) || StartOf(0))) { - Get(); - } - return StartOf(syFol); - } -} - - -void Parser::calcEntry() { - val = 0; - if (la->kind == 5) { - Get(); - Expr(val); - Expect(6); - scanner->buffer->SetPos(t->pos + 1); - - } else if (StartOf(1)) { - Expr(val); - Expect(0); - } else SynErr(15); -} - -void Parser::Expr(scalar& val) { - scalar val2 = 0; - Term(val); - while (la->kind == 7 || la->kind == 8) { - if (la->kind == 7) { - Get(); - Term(val2); - val += val2; - } else { - Get(); - Term(val2); - val -= val2; - } - } -} - -void Parser::Term(scalar& val) { - scalar val2 = 0; - Factor(val); - while (la->kind == 9 || la->kind == 10) { - if (la->kind == 9) { - Get(); - Factor(val2); - val *= val2; - } else { - Get(); - Factor(val2); - val /= val2; - } - } -} - -void Parser::Factor(scalar& val) { - bool negative = false; - if (la->kind == 7 || la->kind == 8) { - if (la->kind == 7) { - Get(); - } else { - Get(); - negative = true; - } - } - if (la->kind == 1) { - Func(val); - } else if (la->kind == 11) { - Get(); - Expr(val); - Expect(12); - } else if (la->kind == 3) { - Get(); - val = getDictLookup(); - } else if (la->kind == 4) { - Get(); - val = coco_string_toDouble(t->val); - } else SynErr(16); - if (negative) { val = -val; } -} - -void Parser::Func(scalar& val) { - Expect(1); - char* str = coco_string_create_char(t->val); - word funcName(str); - coco_string_delete(str); - DynamicList param(4); // hold parameter values - - Expect(11); - if (StartOf(1)) { - scalar x; - Expr(x); - param.append(x); - while (la->kind == 13) { - Get(); - Expr(x); - param.append(x); - } - } - Expect(12); - val = dispatch(funcName, param); -} - - - -void Parser::Parse() { - t = NULL; - if (dummyToken) { // safety: someone might call Parse() twice - delete dummyToken; - } - la = dummyToken = new Token(); - la->val = coco_string_create(L"Dummy Token"); - Get(); - calcEntry(); - // let grammar deal with end-of-file expectations - -} - - -Parser::Parser(Scanner* scan, Errors* err) -: - dummyToken(NULL), - deleteErrorsDestruct_(!err), - errDist(minErrDist), - scanner(scan), - errors(err), - t(NULL), - la(NULL) -{ - if (!errors) { // add in default error handling - errors = new Errors(); - } - // user-defined initialization: -dict_ = 0; - val = 0; - -/*---------------------------------------------------------------------------*/ - - -} - - -bool Parser::StartOf(int s) { - const bool T = true; - const bool x = false; - - static const bool set[2][16] = { - {T,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x}, - {x,T,x,T, T,x,x,T, T,x,x,T, x,x,x,x} - }; - - - - return set[s][la->kind]; -} - - -Parser::~Parser() { - if (deleteErrorsDestruct_) { // delete default error handling - delete errors; - } - delete dummyToken; - // user-defined destruction: - -} - - -// ---------------------------------------------------------------------------- -// Errors Implementation -// ---------------------------------------------------------------------------- - -Errors::Errors() -: - count(0) -{} - - -Errors::~Errors() -{} - - -void Errors::clear() { - count = 0; -} - - -wchar_t* Errors::strerror(int n) -{ - wchar_t* s; - switch (n) { - case 0: s = coco_string_create(L"EOF expected"); break; - case 1: s = coco_string_create(L"ident expected"); break; - case 2: s = coco_string_create(L"string expected"); break; - case 3: s = coco_string_create(L"variable expected"); break; - case 4: s = coco_string_create(L"number expected"); break; - case 5: s = coco_string_create(L"\"{\" expected"); break; - case 6: s = coco_string_create(L"\"}\" expected"); break; - case 7: s = coco_string_create(L"\"+\" expected"); break; - case 8: s = coco_string_create(L"\"-\" expected"); break; - case 9: s = coco_string_create(L"\"*\" expected"); break; - case 10: s = coco_string_create(L"\"/\" expected"); break; - case 11: s = coco_string_create(L"\"(\" expected"); break; - case 12: s = coco_string_create(L"\")\" expected"); break; - case 13: s = coco_string_create(L"\",\" expected"); break; - case 14: s = coco_string_create(L"??? expected"); break; - case 15: s = coco_string_create(L"invalid calcEntry"); break; - case 16: s = coco_string_create(L"invalid Factor"); break; - - default: - { - wchar_t format[20]; - coco_swprintf(format, 20, L"error %d", n); - s = coco_string_create(format); - } - break; - } - return s; -} - - -void Errors::Warning(const wchar_t* msg) { - wprintf(L"%ls\n", msg); -} - - -void Errors::Warning(int line, int col, const wchar_t* msg) { - wprintf(L"-- line %d col %d: %ls\n", line, col, msg); -} - - -void Errors::Error(int line, int col, const wchar_t* msg) { - wprintf(L"-- line %d col %d: %ls\n", line, col, msg); - count++; -} - - -void Errors::SynErr(int line, int col, int n) { - wchar_t* msg = this->strerror(n); - this->Error(line, col, msg); - coco_string_delete(msg); -} - - -void Errors::Exception(const wchar_t* msg) { - wprintf(L"%ls", msg); - ::exit(1); -} - - -// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // - -} // namespace -} // namespace -} // namespace - - -// ************************************************************************* // diff --git a/applications/test/dictionary/calcEntry/calcEntryParser.h b/applications/test/dictionary/calcEntry/calcEntryParser.h deleted file mode 100644 index cfc036ccec..0000000000 --- a/applications/test/dictionary/calcEntry/calcEntryParser.h +++ /dev/null @@ -1,180 +0,0 @@ - - -#ifndef COCO_calcEntryPARSER_H__ -#define COCO_calcEntryPARSER_H__ - -#include "dictionary.H" -#include "wchar.H" -#include "calcEntryInternal.H" - - -#include "calcEntryScanner.h" - -namespace Foam { -namespace functionEntries { -namespace calcEntryInternal { - - -//! Parser error handing -class Errors { -public: - int count; //!< The number of errors detected - - //! Allocate and return a string describing the given error code. - /** It is the responsibility of the caller to free this string, - * eg, with coco_string_delete() - */ - static wchar_t* strerror(int n); - - Errors(); //!< Construct null - start with no errors - virtual ~Errors(); //!< Destructor - virtual void clear(); //!< Clear the error count - - //! Handle a general warning 'msg' - virtual void Warning(const wchar_t* msg); - //! Handle a general warning 'msg' - virtual void Warning(int line, int col, const wchar_t* msg); - //! Handle general error 'msg' (eg, a semantic error) - virtual void Error(int line, int col, const wchar_t* msg); - //! Handle syntax error 'n', uses strerror for the message, calls Error() - virtual void SynErr(int line, int col, int n); - //! Handle a general exception 'msg' - virtual void Exception(const wchar_t* msg); - -}; // Errors - - -//! A Coco/R Parser -class Parser { -private: - enum { - _EOF=0, - _ident=1, - _string=2, - _variable=3, - _number=4, - }; - static const int maxT = 14; - - static const int minErrDist = 2; //!< min. distance before reporting errors - - Token *dummyToken; - bool deleteErrorsDestruct_; //!< delete the 'errors' member in destructor - int errDist; - - void SynErr(int n); //!< Handle syntax error 'n' - void Get(); - void Expect(int n); - bool StartOf(int s); - void ExpectWeak(int n, int follow); - bool WeakSeparator(int n, int syFol, int repFol); - -public: - Scanner *scanner; - Errors *errors; - - Token *t; //!< last recognized token - Token *la; //!< lookahead token - -private: - //- The parent dictionary - dictionary* dict_; - - //- The calculation result - scalar val; - - //- lookup dictionary entry - scalar getDictLookup() const - { - scalar dictValue = 0; - - if (!dict_) - { - FatalErrorIn - ( - "calcEntry::getDictEntry() const" - ) << "No dictionary attached!" - << exit(FatalError); - - return 0; - } - - char* str = coco_string_create_char - ( - t->val, - 1, - (coco_string_length(t->val) - 1) - ); - word keyword(str); - coco_string_delete(str); - - entry* entryPtr = dict_->lookupEntryPtr(keyword, true, false); - if (entryPtr && !entryPtr->isDict()) - { - if (entryPtr->stream().size() != 1) - { - FatalErrorIn - ( - "calcEntry::getDictEntry() const" - ) << "keyword " << keyword << " has " - << entryPtr->stream().size() << " values in dictionary " - << exit(FatalError); - } - entryPtr->stream() >> dictValue; - } - else - { - FatalErrorIn - ( - "calcEntry::getDictEntry() const" - ) << "keyword " << keyword << " is undefined in dictionary " - << exit(FatalError); - } - - return dictValue; - } - - -public: - - //- attach a dictionary - void dict(const dictionary& dict) - { - dict_ = const_cast(&dict); - } - - //- Return the calculated result - scalar Result() const - { - return val; - } - - - - - //! Construct for the specified scanner - /** - * Use the default error handling, or optionally provide an error - * handler, which will not be deleted upon destruction. - */ - Parser(Scanner* scan, Errors* err = 0); - ~Parser(); - void SemErr(const wchar_t* msg); //!< Handle semantic error - - void calcEntry(); - void Expr(scalar& val); - void Term(scalar& val); - void Factor(scalar& val); - void Func(scalar& val); - - void Parse(); //!< Execute the parse operation - -}; // end Parser - -} // namespace -} // namespace -} // namespace - - -#endif // COCO_calcEntryPARSER_H__ - diff --git a/applications/test/dictionary/calcEntry/calcEntryScanner.cpp b/applications/test/dictionary/calcEntry/calcEntryScanner.cpp deleted file mode 100644 index f475323086..0000000000 --- a/applications/test/dictionary/calcEntry/calcEntryScanner.cpp +++ /dev/null @@ -1,932 +0,0 @@ - - -#include - -#include "calcEntryScanner.h" - -// values for the file stream buffering -#define MIN_BUFFER_LENGTH 1024 // 1KB -#define MAX_BUFFER_LENGTH (64*MIN_BUFFER_LENGTH) // 64KB -// value for the heap management -#define HEAP_BLOCK_SIZE (64*1024) // 64KB - - -namespace Foam { -namespace functionEntries { -namespace calcEntryInternal { - - -// * * * * * * * * * * Wide Character String Routines * * * * * * * * * * * // - -// string handling, wide character - -wchar_t* coco_string_create(const wchar_t* str) { - const int len = coco_string_length(str); - wchar_t* dest = new wchar_t[len + 1]; - if (len) { - wcsncpy(dest, str, len); - } - dest[len] = 0; - return dest; -} - -wchar_t* coco_string_create(const wchar_t* str, int index, int length) { - const int len = (str && *str) ? length : 0; - wchar_t* dest = new wchar_t[len + 1]; - if (len) { - wcsncpy(dest, &(str[index]), len); - } - dest[len] = 0; - return dest; -} - - -wchar_t* coco_string_create_lower(const wchar_t* str) { - if (!str) { return NULL; } - return coco_string_create_lower(str, 0, wcslen(str)); -} - - -wchar_t* coco_string_create_lower(const wchar_t* str, int index, int len) { - if (!str) { return NULL; } - wchar_t* dest = new wchar_t[len + 1]; - - for (int i = 0; i < len; i++) { - const wchar_t ch = str[index + i]; - if ((L'A' <= ch) && (ch <= L'Z')) { - dest[i] = ch - (L'A' - L'a'); - } - else { - dest[i] = ch; - } - } - dest[len] = L'\0'; - return dest; -} - - -wchar_t* coco_string_create_append(const wchar_t* str1, const wchar_t* str2) { - const int str1Len = coco_string_length(str1); - const int str2Len = coco_string_length(str2); - - wchar_t* dest = new wchar_t[str1Len + str2Len + 1]; - - if (str1Len) { wcscpy(dest, str1); } - if (str2Len) { wcscpy(dest + str1Len, str2); } - - dest[str1Len + str2Len] = 0; - return dest; -} - -wchar_t* coco_string_create_append(const wchar_t* str1, const wchar_t ch) { - const int len = coco_string_length(str1); - wchar_t* dest = new wchar_t[len + 2]; - wcsncpy(dest, str1, len); // or use if (len) { wcscpy(dest, str1); } - dest[len] = ch; - dest[len + 1] = 0; - return dest; -} - -void coco_string_delete(wchar_t* &str) { - delete [] str; - str = NULL; -} - -int coco_string_length(const wchar_t* str) { - return str ? wcslen(str) : 0; -} - -bool coco_string_endswith(const wchar_t* str, const wchar_t* endstr) { - const int strLen = wcslen(str); - const int endLen = wcslen(endstr); - return (endLen <= strLen) && (wcscmp(str + strLen - endLen, endstr) == 0); -} - -int coco_string_indexof(const wchar_t* str, const wchar_t ch) { - const wchar_t* fnd = wcschr(str, ch); - return fnd ? (fnd - str) : -1; -} - -int coco_string_lastindexof(const wchar_t* str, const wchar_t ch) { - const wchar_t* fnd = wcsrchr(str, ch); - return fnd ? (fnd - str) : -1; -} - -void coco_string_merge(wchar_t* &dest, const wchar_t* str) { - if (!str) { return; } - wchar_t* newstr = coco_string_create_append(dest, str); - delete [] dest; - dest = newstr; -} - -bool coco_string_equal(const wchar_t* str1, const wchar_t* str2) { - return wcscmp(str1, str2) == 0; -} - -int coco_string_compareto(const wchar_t* str1, const wchar_t* str2) { - return wcscmp(str1, str2); -} - -int coco_string_hash(const wchar_t* str) { - int h = 0; - if (!str) { return 0; } - while (*str != 0) { - h = (h * 7) ^ *str; - ++str; - } - if (h < 0) { h = -h; } - return h; -} - - -double coco_string_toDouble(const wchar_t* str) -{ - return str ? wcstod(str, NULL) : 0; -} - -float coco_string_toFloat(const wchar_t* str) -{ - return str ? wcstof(str, NULL) : 0; -} - - - -// -// string handling, byte character -// - -wchar_t* coco_string_create(const char* str) { - const int len = str ? strlen(str) : 0; - wchar_t* dest = new wchar_t[len + 1]; - for (int i = 0; i < len; ++i) { - dest[i] = wchar_t(str[i]); - } - dest[len] = 0; - return dest; -} - -wchar_t* coco_string_create(const char* str, int index, int length) { - const int len = str ? length : 0; - wchar_t* dest = new wchar_t[len + 1]; - for (int i = 0; i < len; ++i) { - dest[i] = wchar_t(str[index + i]); - } - dest[len] = 0; - return dest; -} - - -char* coco_string_create_char(const wchar_t* str) { - const int len = coco_string_length(str); - char* dest = new char[len + 1]; - for (int i = 0; i < len; ++i) - { - dest[i] = char(str[i]); - } - dest[len] = 0; - return dest; -} - -char* coco_string_create_char(const wchar_t* str, int index, int length) { - const int len = (str && *str) ? length : 0; - char* dest = new char[len + 1]; - for (int i = 0; i < len; ++i) { - dest[i] = char(str[index + i]); - } - dest[len] = 0; - return dest; -} - - -void coco_string_delete(char* &str) { - delete [] str; - str = NULL; -} - - -double coco_string_toDouble(const char* str) -{ - return str ? strtod(str, NULL) : 0; -} - -float coco_string_toFloat(const char* str) -{ - return str ? strtof(str, NULL) : 0; -} - - -// * * * * * * * * * End of Wide Character String Routines * * * * * * * * * // - - -Token::Token() -: - kind(0), - pos(0), - col(0), - line(0), - val(NULL), - next(NULL) -{} - - -// Note: this delete may not be correct if the token was actually -// allocated by the internal heap mechanism -Token::~Token() { - coco_string_delete(val); -} - - -// ---------------------------------------------------------------------------- -// Buffer Implementation -// ---------------------------------------------------------------------------- - -Buffer::Buffer(Buffer* b) -: - buf(b->buf), - bufCapacity(b->bufCapacity), - bufLen(b->bufLen), - bufPos(b->bufPos), - bufStart(b->bufStart), - fileLen(b->fileLen), - cStream(b->cStream), - stdStream(b->stdStream), - isUserStream_(b->isUserStream_) -{ - // avoid accidental deletion on any of these members - b->buf = NULL; - b->cStream = NULL; - b->stdStream = NULL; -} - - -Buffer::Buffer(FILE* istr, bool isUserStream) -: - buf(NULL), - bufCapacity(0), - bufLen(0), - bufPos(0), - bufStart(0), - fileLen(0), - cStream(istr), - stdStream(NULL), - isUserStream_(isUserStream) -{ -// ensure binary read on windows -#if _MSC_VER >= 1300 - _setmode(_fileno(cStream), _O_BINARY); -#endif - - if (CanSeek()) { - fseek(cStream, 0, SEEK_END); - fileLen = ftell(cStream); - fseek(cStream, 0, SEEK_SET); - bufLen = (fileLen < MAX_BUFFER_LENGTH) ? fileLen : MAX_BUFFER_LENGTH; - bufStart = INT_MAX; // nothing in the buffer so far - } - - bufCapacity = (bufLen > 0) ? bufLen : MIN_BUFFER_LENGTH; - buf = new unsigned char[bufCapacity]; - if (fileLen > 0) SetPos(0); // setup buffer to position 0 (start) - else bufPos = 0; // index 0 is already after the file, thus Pos = 0 is invalid - if (bufLen == fileLen && CanSeek()) Close(); -} - - -Buffer::Buffer(std::istream* istr, bool isUserStream) -: - buf(NULL), - bufCapacity(0), - bufLen(0), - bufPos(0), - bufStart(0), - fileLen(0), - cStream(NULL), - stdStream(istr), - isUserStream_(isUserStream) -{ - // ensure binary read on windows -#if _MSC_VER >= 1300 - // TODO -#endif -} - - -Buffer::Buffer(std::string& str) -: - buf(NULL), - bufCapacity(0), - bufLen(0), - bufPos(0), - bufStart(0), - fileLen(0), - cStream(NULL), - stdStream(new std::istringstream(str)), - isUserStream_(false) -{} - - -Buffer::Buffer(const unsigned char* chars, int len) -: - buf(new unsigned char[len]), - bufCapacity(len), - bufLen(len), - bufPos(0), - bufStart(0), - fileLen(len), - cStream(NULL), - stdStream(NULL), - isUserStream_(false) -{ - memcpy(this->buf, chars, len*sizeof(char)); -} - - -Buffer::Buffer(const char* chars, int len) -: - buf(new unsigned char[len]), - bufCapacity(len), - bufLen(len), - bufPos(0), - bufStart(0), - fileLen(len), - cStream(NULL), - stdStream(NULL), - isUserStream_(false) -{ - memcpy(this->buf, chars, len*sizeof(char)); -} - - -Buffer::~Buffer() { - Close(); - if (buf) { - delete [] buf; - buf = NULL; - } -} - - -void Buffer::Close() { - if (!isUserStream_) { - if (cStream) { - fclose(cStream); - cStream = NULL; - } - else if (stdStream) { - delete stdStream; - stdStream = 0; - } - } -} - - -int Buffer::Read() { - if (stdStream) - { - int ch = stdStream->get(); - if (stdStream->eof()) - { - return EoF; - } - return ch; - } - - if (bufPos < bufLen) { - return buf[bufPos++]; - } else if (GetPos() < fileLen) { - SetPos(GetPos()); // shift buffer start to Pos - return buf[bufPos++]; - } else if (cStream && !CanSeek() && (ReadNextStreamChunk() > 0)) { - return buf[bufPos++]; - } else { - return EoF; - } -} - - -int UTF8Buffer::Read() { - int ch; - do { - ch = Buffer::Read(); - // until we find a utf8 start (0xxxxxxx or 11xxxxxx) - } while ((ch >= 128) && ((ch & 0xC0) != 0xC0) && (ch != EoF)); - if (ch < 128 || ch == EoF) { - // nothing to do, first 127 chars are the same in ascii and utf8 - // 0xxxxxxx or end of file character - } else if ((ch & 0xF0) == 0xF0) { - // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - int c1 = ch & 0x07; ch = Buffer::Read(); - int c2 = ch & 0x3F; ch = Buffer::Read(); - int c3 = ch & 0x3F; ch = Buffer::Read(); - int c4 = ch & 0x3F; - ch = (((((c1 << 6) | c2) << 6) | c3) << 6) | c4; - } else if ((ch & 0xE0) == 0xE0) { - // 1110xxxx 10xxxxxx 10xxxxxx - int c1 = ch & 0x0F; ch = Buffer::Read(); - int c2 = ch & 0x3F; ch = Buffer::Read(); - int c3 = ch & 0x3F; - ch = (((c1 << 6) | c2) << 6) | c3; - } else if ((ch & 0xC0) == 0xC0) { - // 110xxxxx 10xxxxxx - int c1 = ch & 0x1F; ch = Buffer::Read(); - int c2 = ch & 0x3F; - ch = (c1 << 6) | c2; - } - return ch; -} - - -int Buffer::Peek() { - int curPos = GetPos(); - int ch = Read(); - SetPos(curPos); - return ch; -} - - -int Buffer::GetPos() const { - if (stdStream) - { - return stdStream->tellg(); - } - - return bufPos + bufStart; -} - - -void Buffer::SetPos(int value) { - if (stdStream) - { - stdStream->seekg(value, std::ios::beg); - return; - } - - if ((value >= fileLen) && cStream && !CanSeek()) { - // Wanted position is after buffer and the stream - // is not seek-able e.g. network or console, - // thus we have to read the stream manually till - // the wanted position is in sight. - while ((value >= fileLen) && (ReadNextStreamChunk() > 0)) - {} - } - - if ((value < 0) || (value > fileLen)) { - wprintf(L"--- buffer out of bounds access, position: %d\n", value); - ::exit(1); - } - - if ((value >= bufStart) && (value < (bufStart + bufLen))) { // already in buffer - bufPos = value - bufStart; - } else if (cStream) { // must be swapped in - fseek(cStream, value, SEEK_SET); - bufLen = fread(buf, sizeof(char), bufCapacity, cStream); - bufStart = value; bufPos = 0; - } else { - bufPos = fileLen - bufStart; // make Pos return fileLen - } -} - - -// Read the next chunk of bytes from the stream, increases the buffer -// if needed and updates the fields fileLen and bufLen. -// Returns the number of bytes read. -int Buffer::ReadNextStreamChunk() { - int freeLen = bufCapacity - bufLen; - if (freeLen == 0) { - // in the case of a growing input stream - // we can neither seek in the stream, nor can we - // foresee the maximum length, thus we must adapt - // the buffer size on demand. - bufCapacity = bufLen * 2; - unsigned char *newBuf = new unsigned char[bufCapacity]; - memcpy(newBuf, buf, bufLen*sizeof(char)); - delete [] buf; - buf = newBuf; - freeLen = bufLen; - } - int read = fread(buf + bufLen, sizeof(char), freeLen, cStream); - if (read > 0) { - fileLen = bufLen = (bufLen + read); - return read; - } - // end of stream reached - return 0; -} - - -bool Buffer::CanSeek() const { - return cStream && (ftell(cStream) != -1); -} - - -// ---------------------------------------------------------------------------- -// Scanner Implementation -// ---------------------------------------------------------------------------- - -Scanner::Scanner(FILE* istr) -: - buffer(new Buffer(istr, true)) -{ - Init(); -} - - -Scanner::Scanner(std::istream& istr) -: - buffer(new Buffer(&istr, true)) -{ - Init(); -} - - -Scanner::Scanner(const wchar_t* fileName) { - char *chFileName = coco_string_create_char(fileName); - FILE* istr; - if ((istr = fopen(chFileName, "rb")) == NULL) { - wprintf(L"--- Cannot open file %ls\n", fileName); - ::exit(1); - } - coco_string_delete(chFileName); - buffer = new Buffer(istr, false); - Init(); -} - - -Scanner::Scanner(const unsigned char* buf, int len) -: - buffer(new Buffer(buf, len)) -{ - Init(); -} - - -Scanner::Scanner(const char* buf, int len) -: - buffer(new Buffer(buf, len)) -{ - Init(); -} - - -Scanner::~Scanner() { - char* cur = reinterpret_cast(firstHeap); - - while (cur) { - cur = *(reinterpret_cast(cur + HEAP_BLOCK_SIZE)); - free(firstHeap); - firstHeap = cur; - } - delete [] tval; - delete buffer; -} - - -void Scanner::Init() { - for (int i = 65; i <= 90; ++i) start.set(i, 1); - for (int i = 95; i <= 95; ++i) start.set(i, 1); - for (int i = 97; i <= 122; ++i) start.set(i, 1); - start.set(45, 21); - for (int i = 48; i <= 57; ++i) start.set(i, 9); - start.set(34, 2); - start.set(36, 5); - start.set(46, 7); - start.set(123, 14); - start.set(125, 15); - start.set(43, 22); - start.set(42, 16); - start.set(47, 17); - start.set(40, 18); - start.set(41, 19); - start.set(44, 20); - start.set(Buffer::EoF, -1); - - - - tvalLength = 128; - tval = new wchar_t[tvalLength]; // text of current token - tlen = 0; - tval[tlen] = 0; - - // HEAP_BLOCK_SIZE byte heap + pointer to next heap block - heap = malloc(HEAP_BLOCK_SIZE + sizeof(void*)); - firstHeap = heap; - heapEnd = - reinterpret_cast - (reinterpret_cast(heap) + HEAP_BLOCK_SIZE); - *heapEnd = 0; - heapTop = heap; - if (sizeof(Token) > HEAP_BLOCK_SIZE) { - wprintf(L"--- Too small HEAP_BLOCK_SIZE\n"); - ::exit(1); - } - - pos = -1; line = 1; col = 0; - oldEols = 0; - NextCh(); - if (ch == 0xEF) { // check optional byte order mark for UTF-8 - NextCh(); int ch1 = ch; - NextCh(); int ch2 = ch; - if (ch1 != 0xBB || ch2 != 0xBF) { - wprintf(L"Illegal byte order mark at start of file"); - ::exit(1); - } - Buffer *oldBuf = buffer; - buffer = new UTF8Buffer(buffer); col = 0; - delete oldBuf; oldBuf = NULL; - NextCh(); - } - - - pt = tokens = CreateToken(); // first token is a dummy -} - - -void Scanner::NextCh() { - if (oldEols > 0) { - ch = EOL; - oldEols--; - } - else { - pos = buffer->GetPos(); - ch = buffer->Read(); col++; - // replace isolated '\r' by '\n' in order to make - // eol handling uniform across Windows, Unix and Mac - if (ch == L'\r' && buffer->Peek() != L'\n') ch = EOL; - if (ch == EOL) { line++; col = 0; } - } - -} - - -void Scanner::AddCh() { - if (tlen >= tvalLength) { - tvalLength *= 2; - wchar_t *newBuf = new wchar_t[tvalLength]; - memcpy(newBuf, tval, tlen*sizeof(wchar_t)); - delete [] tval; - tval = newBuf; - } - if (ch != Buffer::EoF) { - tval[tlen++] = ch; - NextCh(); - } -} - - - -bool Scanner::Comment0() { - int level = 1, pos0 = pos, line0 = line, col0 = col; - NextCh(); - if (ch == L'/') { - NextCh(); - for(;;) { - if (ch == 10) { - level--; - if (level == 0) { oldEols = line - line0; NextCh(); return true; } - NextCh(); - } else if (ch == buffer->EoF) return false; - else NextCh(); - } - } else { - buffer->SetPos(pos0); NextCh(); line = line0; col = col0; - } - return false; -} - -bool Scanner::Comment1() { - int level = 1, pos0 = pos, line0 = line, col0 = col; - NextCh(); - if (ch == L'*') { - NextCh(); - for(;;) { - if (ch == L'*') { - NextCh(); - if (ch == L'/') { - level--; - if (level == 0) { oldEols = line - line0; NextCh(); return true; } - NextCh(); - } - } else if (ch == L'/') { - NextCh(); - if (ch == L'*') { - level++; NextCh(); - } - } else if (ch == buffer->EoF) return false; - else NextCh(); - } - } else { - buffer->SetPos(pos0); NextCh(); line = line0; col = col0; - } - return false; -} - - -void Scanner::CreateHeapBlock() { - char* cur = reinterpret_cast(firstHeap); - - // release unused blocks - while - ( - (reinterpret_cast(tokens) < cur) - || (reinterpret_cast(tokens) > (cur + HEAP_BLOCK_SIZE)) - ) { - cur = *(reinterpret_cast(cur + HEAP_BLOCK_SIZE)); - free(firstHeap); - firstHeap = cur; - } - - // HEAP_BLOCK_SIZE byte heap + pointer to next heap block - void* newHeap = malloc(HEAP_BLOCK_SIZE + sizeof(void*)); - *heapEnd = newHeap; - heapEnd = - reinterpret_cast - (reinterpret_cast(newHeap) + HEAP_BLOCK_SIZE); - *heapEnd = 0; - heap = newHeap; - heapTop = heap; -} - - -Token* Scanner::CreateToken() { - const int reqMem = sizeof(Token); - if - ( - (reinterpret_cast(heapTop) + reqMem) - >= reinterpret_cast(heapEnd) - ) { - CreateHeapBlock(); - } - // token 'occupies' heap starting at heapTop - Token* tok = reinterpret_cast(heapTop); - // increment past this part of the heap, which is now used - heapTop = - reinterpret_cast - (reinterpret_cast(heapTop) + reqMem); - tok->val = NULL; - tok->next = NULL; - return tok; -} - - -void Scanner::AppendVal(Token* tok) { - const int reqMem = (tlen + 1) * sizeof(wchar_t); - if - ( - (reinterpret_cast(heapTop) + reqMem) - >= reinterpret_cast(heapEnd) - ) { - if (reqMem > HEAP_BLOCK_SIZE) { - wprintf(L"--- Too long token value\n"); - ::exit(1); - } - CreateHeapBlock(); - } - - // add text value from heap - tok->val = reinterpret_cast(heapTop); - - // increment past this part of the heap, which is now used - heapTop = - reinterpret_cast - (reinterpret_cast(heapTop) + reqMem); - - // copy the currently parsed tval into the token - wcsncpy(tok->val, tval, tlen); - tok->val[tlen] = L'\0'; -} - - -Token* Scanner::NextToken() { - while (ch == ' ' || - (ch >= 9 && ch <= 10) || ch == 13 - ) NextCh(); - if ((ch == L'/' && Comment0()) || (ch == L'/' && Comment1())) return NextToken(); - t = CreateToken(); - t->pos = pos; t->col = col; t->line = line; - int state = start.state(ch); - tlen = 0; AddCh(); - - switch (state) { - case -1: { t->kind = eofSym; break; } // NextCh already done - case 0: { t->kind = noSym; break; } // NextCh already done - case 1: - case_1: - if ((ch >= L'0' && ch <= L'9') || (ch >= L'A' && ch <= L'Z') || ch == L'_' || (ch >= L'a' && ch <= L'z')) {AddCh(); goto case_1;} - else {t->kind = 1; break;} - case 2: - case_2: - if (ch <= 9 || (ch >= 11 && ch <= 12) || (ch >= 14 && ch <= L'!') || (ch >= L'#' && ch <= L'[') || (ch >= L']' && ch <= 65535)) {AddCh(); goto case_2;} - else if (ch == L'"') {AddCh(); goto case_4;} - else if (ch == 92) {AddCh(); goto case_3;} - else {t->kind = noSym; break;} - case 3: - case_3: - if ((ch >= L' ' && ch <= L'~')) {AddCh(); goto case_2;} - else {t->kind = noSym; break;} - case 4: - case_4: - {t->kind = 2; break;} - case 5: - if ((ch >= L'A' && ch <= L'Z') || ch == L'_' || (ch >= L'a' && ch <= L'z')) {AddCh(); goto case_6;} - else {t->kind = noSym; break;} - case 6: - case_6: - if ((ch >= L'0' && ch <= L'9') || (ch >= L'A' && ch <= L'Z') || ch == L'_' || (ch >= L'a' && ch <= L'z')) {AddCh(); goto case_6;} - else {t->kind = 3; break;} - case 7: - case_7: - if ((ch >= L'0' && ch <= L'9')) {AddCh(); goto case_8;} - else {t->kind = noSym; break;} - case 8: - case_8: - if ((ch >= L'0' && ch <= L'9')) {AddCh(); goto case_8;} - else {t->kind = 4; break;} - case 9: - case_9: - if ((ch >= L'0' && ch <= L'9')) {AddCh(); goto case_9;} - else if (ch == L'E' || ch == L'e') {AddCh(); goto case_10;} - else if (ch == L'.') {AddCh(); goto case_13;} - else {t->kind = 4; break;} - case 10: - case_10: - if ((ch >= L'0' && ch <= L'9')) {AddCh(); goto case_12;} - else if (ch == L'+' || ch == L'-') {AddCh(); goto case_11;} - else {t->kind = noSym; break;} - case 11: - case_11: - if ((ch >= L'0' && ch <= L'9')) {AddCh(); goto case_12;} - else {t->kind = noSym; break;} - case 12: - case_12: - if ((ch >= L'0' && ch <= L'9')) {AddCh(); goto case_12;} - else {t->kind = 4; break;} - case 13: - case_13: - if ((ch >= L'0' && ch <= L'9')) {AddCh(); goto case_13;} - else if (ch == L'E' || ch == L'e') {AddCh(); goto case_10;} - else {t->kind = 4; break;} - case 14: - {t->kind = 5; break;} - case 15: - {t->kind = 6; break;} - case 16: - {t->kind = 9; break;} - case 17: - {t->kind = 10; break;} - case 18: - {t->kind = 11; break;} - case 19: - {t->kind = 12; break;} - case 20: - {t->kind = 13; break;} - case 21: - if (ch == L'.') {AddCh(); goto case_7;} - else {t->kind = 8; break;} - case 22: - if (ch == L'.') {AddCh(); goto case_7;} - else {t->kind = 7; break;} - - } - AppendVal(t); - return t; -} - - -// get the next token (possibly a token already seen during peeking) -Token* Scanner::Scan() { - if (tokens->next == NULL) { - return pt = tokens = NextToken(); - } else { - pt = tokens = tokens->next; - return tokens; - } -} - - -// peek for the next token, ignore pragmas -Token* Scanner::Peek() { - do { - if (pt->next == NULL) { - pt->next = NextToken(); - } - pt = pt->next; - } while (pt->kind > maxT); // skip pragmas - - return pt; -} - - -// make sure that peeking starts at the current scan position -void Scanner::ResetPeek() { - pt = tokens; -} - - -// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // - -} // namespace -} // namespace -} // namespace - - -// ************************************************************************* // diff --git a/applications/test/dictionary/calcEntry/calcEntryScanner.h b/applications/test/dictionary/calcEntry/calcEntryScanner.h deleted file mode 100644 index 9ea17302c6..0000000000 --- a/applications/test/dictionary/calcEntry/calcEntryScanner.h +++ /dev/null @@ -1,396 +0,0 @@ - - -#ifndef COCO_calcEntrySCANNER_H__ -#define COCO_calcEntrySCANNER_H__ - -#include -#include -#include -#include -#include -#include -#include -#include - -// io.h and fcntl are used to ensure binary read from streams on windows -#if _MSC_VER >= 1300 -#include -#include -#endif - -#if _MSC_VER >= 1400 -#define coco_swprintf swprintf_s -#elif _MSC_VER >= 1300 -#define coco_swprintf _snwprintf -#else -// assume every other compiler knows swprintf -#define coco_swprintf swprintf -#endif - - -#define COCO_WCHAR_MAX 65535 - - -namespace Foam { -namespace functionEntries { -namespace calcEntryInternal { - - - -// * * * * * * * * * * Wide Character String Routines * * * * * * * * * * * // - -// -// string handling, wide character -// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -//! Create by copying str -wchar_t* coco_string_create(const wchar_t* str); - -//! Create a substring of str starting at index and length characters long -wchar_t* coco_string_create(const wchar_t* str, int index, int length); - -//! Create a lowercase string from str -wchar_t* coco_string_create_lower(const wchar_t* str); - -//! Create a lowercase substring from str starting at index and length characters long -wchar_t* coco_string_create_lower(const wchar_t* str, int index, int length); - -//! Create a string by concatenating str1 and str2 -wchar_t* coco_string_create_append(const wchar_t* str1, const wchar_t* str2); - -//! Create a string by concatenating a character to the end of str -wchar_t* coco_string_create_append(const wchar_t* str, const wchar_t ch); - -//! Free storage and nullify the argument -void coco_string_delete(wchar_t* &str); - -//! The length of the str, or 0 if the str is NULL -int coco_string_length(const wchar_t* str); - -//! Return true if the str ends with the endstr -bool coco_string_endswith(const wchar_t* str, const wchar_t* endstr); - -//! Return the index of the first occurrence of ch. -// Return -1 if nothing is found. -int coco_string_indexof(const wchar_t* str, const wchar_t ch); - -//! Return the index of the last occurrence of ch. -// Return -1 if nothing is found. -int coco_string_lastindexof(const wchar_t* str, const wchar_t ch); - -//! Append str to dest -void coco_string_merge(wchar_t* &dest, const wchar_t* str); - -//! Compare strings, return true if they are equal -bool coco_string_equal(const wchar_t* str1, const wchar_t* str2); - -//! Compare strings, return 0 if they are equal -int coco_string_compareto(const wchar_t* str1, const wchar_t* str2); - -//! Simple string hashing function -int coco_string_hash(const wchar_t* str); - -// -// String conversions -// ~~~~~~~~~~~~~~~~~~ - -//! Convert wide string to double -double coco_string_toDouble(const wchar_t* str); - -//! Convert wide string to float -float coco_string_toFloat(const wchar_t* str); - -// -// String handling, byte character -// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -//! Create by copying byte str -wchar_t* coco_string_create(const char* str); - -//! Create a substring of byte str starting at index and length characters long -wchar_t* coco_string_create(const char* str, int index, int length); - -//! Create a byte string by copying str -char* coco_string_create_char(const wchar_t* str); - -//! Create a byte substring of str starting at index and length characters long -char* coco_string_create_char(const wchar_t* str, int index, int length); - -//! Free storage and nullify the argument -void coco_string_delete(char* &str); - - -// -// String conversions, byte character -// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -//! Convert byte string to double -double coco_string_toDouble(const char* str); - -//! Convert byte string to float -float coco_string_toFloat(const char* str); - -// * * * * * * * * * End of Wide Character String Routines * * * * * * * * * // - - -//! Scanner Token -class Token -{ -public: - int kind; //!< token kind - int pos; //!< token position in the source text (starting at 0) - int col; //!< token column (starting at 1) - int line; //!< token line (starting at 1) - wchar_t* val; //!< token value - Token *next; //!< Peek tokens are kept in linked list - - Token(); //!< Construct null - ~Token(); //!< Destructor - cleanup allocated val?? -}; - - -//! Scanner Buffer -// -//! This Buffer supports the following cases: -//! -# seekable stream (file) -//! -# whole stream in buffer -//! -# part of stream in buffer -//! -# non seekable stream (network, console) -class Buffer { -private: - unsigned char *buf; //!< input buffer - int bufCapacity; //!< capacity of buf - int bufLen; //!< length of buffer - int bufPos; //!< current position in buffer - int bufStart; //!< position of first byte in buffer relative to input stream - int fileLen; //!< length of input stream (may change if the stream is no file) - FILE* cStream; //!< input stdio stream (normally seekable) - std::istream* stdStream; //!< STL std stream (seekable) - bool isUserStream_; //!< was the stream opened by the user? - - int ReadNextStreamChunk(); - bool CanSeek() const; //!< true if stream can be seeked otherwise false - -protected: - Buffer(Buffer*); //!< for the UTF8Buffer - -public: - static const int EoF = COCO_WCHAR_MAX + 1; - - //! Attach buffer to a stdio stream. - //! User streams are not closed in the destructor - Buffer(FILE*, bool isUserStream = true); - - //! Attach buffer to an STL std stream - //! User streams are not closed in the destructor - explicit Buffer(std::istream*, bool isUserStream = true); - - //! Copy buffer contents from constant string - //! Handled internally as an istringstream - explicit Buffer(std::string&); - - //! Copy buffer contents from constant character string - Buffer(const unsigned char* chars, int len); - //! Copy buffer contents from constant character string - Buffer(const char* chars, int len); - - //! Close stream (but not user streams) and free buf (if any) - virtual ~Buffer(); - - virtual void Close(); //!< Close stream (but not user streams) - virtual int Read(); //!< Get character from stream or buffer - virtual int Peek(); //!< Peek character from stream or buffer - - virtual int GetPos() const; - virtual void SetPos(int value); -}; - - -//! A Scanner buffer that handles UTF-8 characters -class UTF8Buffer : public Buffer { -public: - UTF8Buffer(Buffer* b) : Buffer(b) {} - virtual int Read(); -}; - - -//------------------------------------------------------------------------------ -// StartStates -//------------------------------------------------------------------------------ -//! maps characters (integers) to start states of tokens -class StartStates { - class Elem { - public: - int key, val; - Elem *next; - Elem(int k, int v) : - key(k), val(v), next(0) - {} - }; - - Elem **tab; - -public: - StartStates() : - tab(new Elem*[128]) - { - memset(tab, 0, 128*sizeof(Elem*)); - } - - virtual ~StartStates() { - for (int i = 0; i < 128; ++i) { - Elem *e = tab[i]; - while (e) { - Elem *next = e->next; - delete e; - e = next; - } - } - delete [] tab; - } - - void set(int key, int val) { - Elem *e = new Elem(key, val); - const int k = unsigned(key) % 128; - e->next = tab[k]; - tab[k] = e; - } - - int state(int key) { - Elem *e = tab[unsigned(key) % 128]; - while (e && e->key != key) e = e->next; - return e ? e->val : 0; - } -}; - - -//------------------------------------------------------------------------------ -// KeywordMap -//------------------------------------------------------------------------------ -//! maps strings to integers (identifiers to keyword kinds) -class KeywordMap { - class Elem { - public: - wchar_t *key; - int val; - Elem *next; - Elem(const wchar_t *k, int v) : - key(coco_string_create(k)), val(v), next(0) - {} - virtual ~Elem() { - coco_string_delete(key); - } - }; - - Elem **tab; - -public: - KeywordMap() : - tab(new Elem*[128]) - { - memset(tab, 0, 128*sizeof(Elem*)); - } - - virtual ~KeywordMap() { - for (int i = 0; i < 128; ++i) { - Elem *e = tab[i]; - while (e) { - Elem *next = e->next; - delete e; - e = next; - } - } - delete [] tab; - } - - void set(const wchar_t *key, int val) { - Elem *e = new Elem(key, val); - const int k = coco_string_hash(key) % 128; - e->next = tab[k]; - tab[k] = e; - } - - int get(const wchar_t *key, int defaultVal) { - Elem *e = tab[coco_string_hash(key) % 128]; - while (e && !coco_string_equal(e->key, key)) e = e->next; - return e ? e->val : defaultVal; - } -}; - - -//! A Coco/R Scanner -class Scanner { -private: - static const int maxT = 14; - static const int noSym = 14; - - static const int eofSym = 0; //!< end-of-file token id - static const char EOL = '\n'; //!< end-of-line character - - void *firstHeap; //!< the start of the heap management - void *heap; //!< the currently active block - void *heapTop; //!< the top of the heap - void **heapEnd; //!< the end of the last heap block - - StartStates start; //!< A map of start states for particular characters - KeywordMap keywords; //!< A hash of keyword literals to token kind - - Token *t; //!< current token - wchar_t *tval; //!< text of current token - int tvalLength; //!< maximum capacity (length) for tval - int tlen; //!< length of tval - - Token *tokens; //!< list of tokens already peeked (first token is a dummy) - Token *pt; //!< current peek token - - int ch; //!< current input character - - int pos; //!< byte position of current character - int line; //!< line number of current character - int col; //!< column number of current character - int oldEols; //!< the number of EOLs that appeared in a comment - - void CreateHeapBlock(); //!< add a heap block, freeing unused ones - Token* CreateToken(); //!< fit token on the heap - void AppendVal(Token* tok); //!< adjust tok->val to point to the heap and copy tval into it - - void Init(); //!< complete the initialization for the constructors - void NextCh(); //!< get the next input character into ch - void AddCh(); //!< append the character ch to tval - bool Comment0(); - bool Comment1(); - - Token* NextToken(); //!< get the next token - -public: - //! The scanner buffer - Buffer *buffer; - - //! Using an existing open file handle for the scanner - Scanner(FILE*); - - //! Using an existing open STL std stream - explicit Scanner(std::istream&); - - //! Open a file for reading and attach scanner - explicit Scanner(const wchar_t* fileName); - - //! Attach scanner to an existing character buffer - Scanner(const unsigned char* chars, int len); - //! Attach scanner to an existing character buffer - Scanner(const char* chars, int len); - - ~Scanner(); //!< free heap and allocated memory - Token* Scan(); //!< get the next token (possibly a token already seen during peeking) - Token* Peek(); //!< peek for the next token, ignore pragmas - void ResetPeek(); //!< ensure that peeking starts at the current scan position - -}; // end Scanner - -} // namespace -} // namespace -} // namespace - - -#endif // COCO_calcEntrySCANNER_H__ - diff --git a/wmake/rules/General/coco b/wmake/rules/General/coco new file mode 100644 index 0000000000..12c11df4cf --- /dev/null +++ b/wmake/rules/General/coco @@ -0,0 +1,6 @@ +.SUFFIXES: .ATG + +ATGtoo = Coco -single -frames $(WM_THIRD_PARTY_DIR)/coco-r/src $$SOURCE -o $(OBJECTS_DIR) ; $(CC) $(c++FLAGS) -c $*.cpp -o $@ + +.ATG.dep: + $(MAKE_DEP) diff --git a/wmake/rules/General/standard b/wmake/rules/General/standard index 809f9353a2..3188ac4413 100644 --- a/wmake/rules/General/standard +++ b/wmake/rules/General/standard @@ -4,6 +4,7 @@ include $(GENERAL_RULES)/sourceToDep include $(GENERAL_RULES)/flex include $(GENERAL_RULES)/flex++ +include $(GENERAL_RULES)/coco ## include $(GENERAL_RULES)/byacc ## include $(GENERAL_RULES)/btyacc++ include $(GENERAL_RULES)/bison From e0ba4cbb02dd8e5c8f271a41ac1bcd5de5e986c5 Mon Sep 17 00:00:00 2001 From: Mark Olesen Date: Sun, 3 Jan 2010 21:45:32 +0100 Subject: [PATCH 05/42] Adjust line number before/after #calc{} scanner for improved error messages. --- applications/test/dictionary/Make/files | 2 +- applications/test/dictionary/calcEntry/calcEntry.C | 14 ++++++++++---- .../{calcEntryParser.ATG => calcEntryParser.atg} | 0 wmake/rules/General/coco | 8 +++++--- 4 files changed, 16 insertions(+), 8 deletions(-) rename applications/test/dictionary/calcEntry/{calcEntryParser.ATG => calcEntryParser.atg} (100%) diff --git a/applications/test/dictionary/Make/files b/applications/test/dictionary/Make/files index 89d95d0298..6f1da0059a 100644 --- a/applications/test/dictionary/Make/files +++ b/applications/test/dictionary/Make/files @@ -1,6 +1,6 @@ dictionaryTest.C -calcEntry/calcEntryParser.ATG +calcEntry/calcEntryParser.atg calcEntry/calcEntryInternal.C calcEntry/calcEntry.C diff --git a/applications/test/dictionary/calcEntry/calcEntry.C b/applications/test/dictionary/calcEntry/calcEntry.C index 7e634bc8b4..0f0bfbbdc8 100644 --- a/applications/test/dictionary/calcEntry/calcEntry.C +++ b/applications/test/dictionary/calcEntry/calcEntry.C @@ -68,17 +68,23 @@ bool Foam::functionEntries::calcEntry::execute myErrorHandler("calcEntryInternal::Parser"); calcEntryInternal::Scanner scanner(iss); + + // set the starting line + scanner.Line(is.lineNumber()); + calcEntryInternal::Parser parser(&scanner, &myErrorHandler); // Attach dictionary context parser.dict(parentDict); - // Attach scalar functions - // parser.functions(parentDict); - parser.Parse(); - // make a small input list to contain the answer + // mostly have an extra newline in the lookahead token + // so subtract 1 to keep things vaguely in sync + // (this is still far from perfect) + is.lineNumber() = scanner.Line() - 1; + + // a small input list to contain the answer tokenList tokens(2); tokens[0] = parser.Result(); tokens[1] = token::END_STATEMENT; diff --git a/applications/test/dictionary/calcEntry/calcEntryParser.ATG b/applications/test/dictionary/calcEntry/calcEntryParser.atg similarity index 100% rename from applications/test/dictionary/calcEntry/calcEntryParser.ATG rename to applications/test/dictionary/calcEntry/calcEntryParser.atg diff --git a/wmake/rules/General/coco b/wmake/rules/General/coco index 12c11df4cf..97b345c512 100644 --- a/wmake/rules/General/coco +++ b/wmake/rules/General/coco @@ -1,6 +1,8 @@ -.SUFFIXES: .ATG +# handie Coco/R attributed grammars -ATGtoo = Coco -single -frames $(WM_THIRD_PARTY_DIR)/coco-r/src $$SOURCE -o $(OBJECTS_DIR) ; $(CC) $(c++FLAGS) -c $*.cpp -o $@ +.SUFFIXES: .atg -.ATG.dep: +atgtoo = Coco -single -frames $(WM_THIRD_PARTY_DIR)/coco-cpp/src $$SOURCE -o $(OBJECTS_DIR) ; $(CC) $(c++FLAGS) -c $*.cpp -o $@ + +.atg.dep: $(MAKE_DEP) From cf3e2a8abff5769a1a48ca5f392808eaedb4e31b Mon Sep 17 00:00:00 2001 From: Mark Olesen Date: Wed, 6 Jan 2010 12:27:14 +0100 Subject: [PATCH 06/42] Update calcEntry grammar to include copyright. Include character class (wchar_t or char) as a template parameter in CocoParserErrors. --- .../test/dictionary/calcEntry/calcEntryParser.atg | 14 +++++++++----- src/OpenFOAM/db/error/CocoParserErrors.H | 14 +++++++------- wmake/rules/General/coco | 7 ++++++- 3 files changed, 22 insertions(+), 13 deletions(-) diff --git a/applications/test/dictionary/calcEntry/calcEntryParser.atg b/applications/test/dictionary/calcEntry/calcEntryParser.atg index e1a1567700..7dfb17c107 100644 --- a/applications/test/dictionary/calcEntry/calcEntryParser.atg +++ b/applications/test/dictionary/calcEntry/calcEntryParser.atg @@ -1,8 +1,9 @@ +[copy] /*---------------------------------*- C++ -*---------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | - \\ / A nd | Copyright (C) 2009-2010 OpenCFD Ltd. + \\ / A nd | Copyright (C) 2010-2010 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License @@ -27,15 +28,19 @@ License Description An attributed Coco/R grammar to parse simple arithmetic expressions + Includes support for dictionary $variables and some scalar functions + (eg, sin, pow, ...) + SourceFiles generated \*---------------------------------------------------------------------------*/ +[/copy] /*---------------------------------------------------------------------------*\ compile with: Coco \ [-single] -frames $WM_THIRD_PARTY_DIR/coco-r \ - calcEntryParser.ATG + calcEntryParser.atg \*---------------------------------------------------------------------------*/ #include "dictionary.H" @@ -49,8 +54,6 @@ COMPILER calcEntry $namespace=Foam::functionEntries::calcEntryInternal $eof=true // grammar handles eof itself - // Simple four function calculator for OpenFOAM dictionaries - private: //- The parent dictionary dictionary* dict_; @@ -125,9 +128,10 @@ public: } -INITIALIZE +[initialize] dict_ = 0; val = 0; +[/initialize] /*---------------------------------------------------------------------------*/ diff --git a/src/OpenFOAM/db/error/CocoParserErrors.H b/src/OpenFOAM/db/error/CocoParserErrors.H index 21f574592d..d9d2155db2 100644 --- a/src/OpenFOAM/db/error/CocoParserErrors.H +++ b/src/OpenFOAM/db/error/CocoParserErrors.H @@ -2,7 +2,7 @@ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | - \\ / A nd | Copyright (C) 2009-2009 OpenCFD Ltd. + \\ / A nd | Copyright (C) 2009-2010 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License @@ -45,7 +45,7 @@ namespace Foam Class CocoParserErrors Declaration \*---------------------------------------------------------------------------*/ -template +template class CocoParserErrors : public BaseClass @@ -90,14 +90,14 @@ public: // Error Handling //- Handle a general warning 'msg' - virtual void Warning(const wchar_t* msg) + virtual void Warning(const CharClass* msg) { WarningIn(name_) << msg << endl; } //- Handle a general warning 'msg' - virtual void Warning(int line, int col, const wchar_t* msg) + virtual void Warning(int line, int col, const CharClass* msg) { WarningIn(name_) <<"line " << line << " col " << col << ": " @@ -105,7 +105,7 @@ public: } //- Handle general error 'msg' (eg, a semantic error) - virtual void Error(int line, int col, const wchar_t* msg) + virtual void Error(int line, int col, const CharClass* msg) { FatalErrorIn(name_) << "line " << line << " col " << col <<": " << msg << endl @@ -113,7 +113,7 @@ public: } //- Handle general error 'msg' (eg, a semantic error) - virtual void Error(const wchar_t* msg) + virtual void Error(const CharClass* msg) { FatalErrorIn(name_) << msg << endl @@ -121,7 +121,7 @@ public: } //- Handle a general exception 'msg' - virtual void Exception(const wchar_t* msg) + virtual void Exception(const CharClass* msg) { this->Error(msg); } diff --git a/wmake/rules/General/coco b/wmake/rules/General/coco index 97b345c512..46fae00453 100644 --- a/wmake/rules/General/coco +++ b/wmake/rules/General/coco @@ -2,7 +2,12 @@ .SUFFIXES: .atg -atgtoo = Coco -single -frames $(WM_THIRD_PARTY_DIR)/coco-cpp/src $$SOURCE -o $(OBJECTS_DIR) ; $(CC) $(c++FLAGS) -c $*.cpp -o $@ +atgtoo = \ + $(WM_THIRD_PARTY_DIR)/coco-cpp/platforms/$(WM_ARCH)/bin/coco-cpp \ + -single \ + -frames $(WM_THIRD_PARTY_DIR)/coco-cpp/platforms/share/coco-cpp \ + $$SOURCE -o $(OBJECTS_DIR) ; \ + $(CC) $(c++FLAGS) -c $*.cpp -o $@ .atg.dep: $(MAKE_DEP) From a132aadeb80bec0c67df902882f3f65bbe0b546f Mon Sep 17 00:00:00 2001 From: Mark Olesen Date: Mon, 11 Jan 2010 15:00:55 +0100 Subject: [PATCH 07/42] Output wchar_t as UTF-8 instead of simply truncating to char. --- src/OpenFOAM/primitives/chars/wchar/wchar.H | 10 ++- src/OpenFOAM/primitives/chars/wchar/wcharIO.C | 74 ++++++++++++++++--- 2 files changed, 72 insertions(+), 12 deletions(-) diff --git a/src/OpenFOAM/primitives/chars/wchar/wchar.H b/src/OpenFOAM/primitives/chars/wchar/wchar.H index c731a3dc81..61519a51d3 100644 --- a/src/OpenFOAM/primitives/chars/wchar/wchar.H +++ b/src/OpenFOAM/primitives/chars/wchar/wchar.H @@ -2,7 +2,7 @@ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | - \\ / A nd | Copyright (C) 2009-2009 OpenCFD Ltd. + \\ / A nd | Copyright (C) 2009-2010 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License @@ -31,6 +31,10 @@ Description SourceFiles wcharIO.C +SeeAlso + http://en.wikipedia.org/wiki/UTF-8 + http://en.wikibooks.org/wiki/Unicode/Character_reference + \*---------------------------------------------------------------------------*/ #ifndef wchar_H @@ -48,10 +52,10 @@ class Ostream; // * * * * * * * * * * * * * * * IOstream Operators * * * * * * * * * * * * // -//- Output via a normal char +//- Output wide character (Unicode) as UTF-8 Ostream& operator<<(Ostream&, const wchar_t); -//- Output string via normal char +//- Output wide character (Unicode) string as UTF-8 Ostream& operator<<(Ostream&, const wchar_t*); diff --git a/src/OpenFOAM/primitives/chars/wchar/wcharIO.C b/src/OpenFOAM/primitives/chars/wchar/wcharIO.C index 47a5ed0560..9796d4b6eb 100644 --- a/src/OpenFOAM/primitives/chars/wchar/wcharIO.C +++ b/src/OpenFOAM/primitives/chars/wchar/wcharIO.C @@ -2,7 +2,7 @@ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | - \\ / A nd | Copyright (C) 2009-2009 OpenCFD Ltd. + \\ / A nd | Copyright (C) 2009-2010 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License @@ -22,11 +22,6 @@ License along with OpenFOAM; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -Description - Reads a char from an input stream, for a given version - number and File format. If an ascii File is being read, then the line - numbers are counted and an erroneous read is reported. - \*---------------------------------------------------------------------------*/ #include "error.H" @@ -38,7 +33,68 @@ Description Foam::Ostream& Foam::operator<<(Ostream& os, const wchar_t wc) { - os.write(char(wc)); + if (!(wc & ~0x0000007F)) + { + // 0x00000000 - 0x0000007F: (1-byte output) + // 0xxxxxxx + os.write(char(wc)); + } + else if (!(wc & ~0x000007FF)) + { + // 0x00000080 - 0x000007FF: (2-byte output) + // 110bbbaa 10aaaaaa + os.write(char(0xC0 | ((wc >> 6) & 0x1F))); + os.write(char(0x80 | ((wc) & 0x3F))); + } + else if (!(wc & ~0x0000FFFF)) + { + // 0x00000800 - 0x0000FFFF: (3-byte output) + // 1110bbbb 10bbbbaa 10aaaaaa + os.write(char(0xE0 | ((wc >> 12) & 0x0F))); + os.write(char(0x80 | ((wc >> 6) & 0x3F))); + os.write(char(0x80 | ((wc) & 0x3F))); + } + else if (!(wc & ~0x001FFFFF)) + { + // 0x00010000 - 0x001FFFFF: (4-byte output) + // 11110ccc 10ccbbbb 10bbbbaa 10aaaaaa + os.write(char(0xF0 | ((wc >> 18) & 0x07))); + os.write(char(0x80 | ((wc >> 12) & 0x3F))); + os.write(char(0x80 | ((wc >> 6) & 0x3F))); + os.write(char(0x80 | ((wc) & 0x3F))); + } + else if (!(wc & ~0x03FFFFFF)) + { + // 0x00200000 - 0x03FFFFFF: (5-byte output) + // 111110dd 10cccccc 10ccbbbb 10bbbbaa 10aaaaaa + os.write(char(0xF8 | ((wc >> 24) & 0x03))); + os.write(char(0x80 | ((wc >> 18) & 0x3F))); + os.write(char(0x80 | ((wc >> 12) & 0x3F))); + os.write(char(0x80 | ((wc >> 6) & 0x3F))); + os.write(char(0x80 | ((wc) & 0x3F))); + } + else if (!(wc & ~0x7FFFFFFF)) + { + // 0x04000000 - 0x7FFFFFFF: (6-byte output) + // 1111110d 10dddddd 10cccccc 10ccbbbb 10bbbbaa 10aaaaaa + os.write(char(0xFC | ((wc >> 30) & 0x01))); + os.write(char(0x80 | ((wc >> 24) & 0x3F))); + os.write(char(0x80 | ((wc >> 18) & 0x3F))); + os.write(char(0x80 | ((wc >> 12) & 0x3F))); + os.write(char(0x80 | ((wc >> 6) & 0x3F))); + os.write(char(0x80 | ((wc) & 0x3F))); + } + else + { + // according to man page utf8(7) + // the Unicode standard specifies no characters above 0x0010FFFF, + // so Unicode characters can only be up to four bytes long in UTF-8. + + // report anything unknown/invalid as replacement character U+FFFD + os.write(char(0xEF)); + os.write(char(0xBF)); + os.write(char(0xBD)); + } os.check("Ostream& operator<<(Ostream&, const wchar_t)"); return os; @@ -51,10 +107,10 @@ Foam::Ostream& Foam::operator<<(Ostream& os, const wchar_t* ws) { for (const wchar_t* p = ws; *p; ++p) { - os.write(char(*p)); + os << *p; } } - os.check("Ostream& operator<<(Ostream&, const wchar_t*)"); + return os; } From 0d49e4711c93023f756d5359fa44d15509ab2a4d Mon Sep 17 00:00:00 2001 From: Mark Olesen Date: Fri, 15 Jan 2010 14:35:50 +0100 Subject: [PATCH 08/42] Begin code refactoring of third-party file formats. --- .../foamDebugSwitches/Make/options | 1 + .../surface/surfaceSubset/surfaceSubset.C | 30 +-- .../surface/surfaceSubset/surfaceSubsetDict | 2 +- src/Allwmake | 1 + src/edgeMesh/Make/options | 5 + src/edgeMesh/edgeFormats/nas/NASedgeFormat.C | 28 --- src/edgeMesh/edgeFormats/nas/NASedgeFormat.H | 11 +- .../edgeFormats/starcd/STARCDedgeFormat.C | 128 ------------- .../edgeFormats/starcd/STARCDedgeFormat.H | 13 +- src/fileFormats/Make/files | 4 + src/fileFormats/Make/options | 0 .../nas/NASCore.C} | 13 +- .../nas/NASCore.H} | 32 ++-- src/fileFormats/starcd/STARCDCore.C | 173 ++++++++++++++++++ src/fileFormats/starcd/STARCDCore.H | 131 +++++++++++++ src/surfMesh/Make/files | 1 - src/surfMesh/Make/options | 5 + .../surfaceFormats/nas/NASsurfaceFormat.H | 4 +- .../starcd/STARCDsurfaceFormatCore.C | 140 +------------- .../starcd/STARCDsurfaceFormatCore.H | 11 +- src/triSurface/Make/options | 6 +- 21 files changed, 380 insertions(+), 359 deletions(-) create mode 100644 src/fileFormats/Make/files create mode 100644 src/fileFormats/Make/options rename src/{surfMesh/surfaceFormats/nas/NASsurfaceFormatCore.C => fileFormats/nas/NASCore.C} (87%) rename src/{surfMesh/surfaceFormats/nas/NASsurfaceFormatCore.H => fileFormats/nas/NASCore.H} (81%) create mode 100644 src/fileFormats/starcd/STARCDCore.C create mode 100644 src/fileFormats/starcd/STARCDCore.H diff --git a/applications/utilities/miscellaneous/foamDebugSwitches/Make/options b/applications/utilities/miscellaneous/foamDebugSwitches/Make/options index e473b84bb9..7207b53927 100644 --- a/applications/utilities/miscellaneous/foamDebugSwitches/Make/options +++ b/applications/utilities/miscellaneous/foamDebugSwitches/Make/options @@ -18,6 +18,7 @@ EXE_LIBS = \ -lengine \ -lerrorEstimation \ -lfieldFunctionObjects \ + -lfileFormats \ -lfiniteVolume \ -lforces \ -lfvMotionSolvers \ diff --git a/applications/utilities/surface/surfaceSubset/surfaceSubset.C b/applications/utilities/surface/surfaceSubset/surfaceSubset.C index dd8a6ede00..6cc8ee4678 100644 --- a/applications/utilities/surface/surfaceSubset/surfaceSubset.C +++ b/applications/utilities/surface/surfaceSubset/surfaceSubset.C @@ -100,10 +100,8 @@ int main(int argc, char *argv[]) meshSubsetDict.lookup("addFaceNeighbours") ); - Switch invertSelection - ( - meshSubsetDict.lookup("invertSelection") - ); + const bool invertSelection = + meshSubsetDict.lookupOrDefault("invertSelection", false); // Mark the cells for the subset @@ -246,7 +244,7 @@ int main(int argc, char *argv[]) // bb of surface treeBoundBox bb(selectSurf.localPoints()); - // Radnom number generator + // Random number generator Random rndGen(354543); // search engine @@ -269,14 +267,11 @@ int main(int argc, char *argv[]) indexedOctree::volumeType t = selectTree.getVolumeType(fc); - if (t == indexedOctree::INSIDE && !outside) - { - facesToSubset[faceI] = true; - } - else if + if ( - t == indexedOctree::OUTSIDE - && outside + outside + ? (t == indexedOctree::OUTSIDE) + : (t == indexedOctree::INSIDE) ) { facesToSubset[faceI] = true; @@ -346,20 +341,11 @@ int main(int argc, char *argv[]) if (invertSelection) { Info<< "Inverting selection." << endl; - boolList newFacesToSubset(facesToSubset.size()); forAll(facesToSubset, i) { - if (facesToSubset[i]) - { - newFacesToSubset[i] = false; - } - else - { - newFacesToSubset[i] = true; - } + facesToSubset[i] = facesToSubset[i] ? false : true; } - facesToSubset.transfer(newFacesToSubset); } diff --git a/applications/utilities/surface/surfaceSubset/surfaceSubsetDict b/applications/utilities/surface/surfaceSubset/surfaceSubsetDict index 3a8db2cffd..f956a24789 100644 --- a/applications/utilities/surface/surfaceSubset/surfaceSubsetDict +++ b/applications/utilities/surface/surfaceSubset/surfaceSubsetDict @@ -36,7 +36,7 @@ zone surface { name "sphere.stl"; - outside yes; + outside yes; } // Extend selection with edge neighbours diff --git a/src/Allwmake b/src/Allwmake index a91f131e55..f24f2f370d 100755 --- a/src/Allwmake +++ b/src/Allwmake @@ -22,6 +22,7 @@ wmake libso OpenFOAM wmake libso lagrangian/basic +wmake libso fileFormats wmake libso edgeMesh wmake libso surfMesh wmake libso triSurface diff --git a/src/edgeMesh/Make/options b/src/edgeMesh/Make/options index e69de29bb2..7e207d0dbe 100644 --- a/src/edgeMesh/Make/options +++ b/src/edgeMesh/Make/options @@ -0,0 +1,5 @@ +EXE_INC = \ + -I$(LIB_SRC)/fileFormats/lnInclude + +LIB_LIBS = \ + -lfileFormats diff --git a/src/edgeMesh/edgeFormats/nas/NASedgeFormat.C b/src/edgeMesh/edgeFormats/nas/NASedgeFormat.C index 4b178d1dbd..fec0c883a3 100644 --- a/src/edgeMesh/edgeFormats/nas/NASedgeFormat.C +++ b/src/edgeMesh/edgeFormats/nas/NASedgeFormat.C @@ -29,34 +29,6 @@ License #include "IStringStream.H" #include "PackedBoolList.H" -// * * * * * * * * * * * * Protected Member Functions * * * * * * * * * * * // - -// Do weird things to extract a floating point number -Foam::scalar Foam::fileFormats::NASedgeFormat::parseNASCoord -( - const string& s -) -{ - size_t expSign = s.find_last_of("+-"); - - if (expSign != string::npos && expSign > 0 && !isspace(s[expSign-1])) - { - scalar mantissa = readScalar(IStringStream(s.substr(0, expSign))()); - scalar exponent = readScalar(IStringStream(s.substr(expSign+1))()); - - if (s[expSign] == '-') - { - exponent = -exponent; - } - return mantissa * pow(10, exponent); - } - else - { - return readScalar(IStringStream(s)()); - } -} - - // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // Foam::fileFormats::NASedgeFormat::NASedgeFormat diff --git a/src/edgeMesh/edgeFormats/nas/NASedgeFormat.H b/src/edgeMesh/edgeFormats/nas/NASedgeFormat.H index 600b880cb7..3ccd4397af 100644 --- a/src/edgeMesh/edgeFormats/nas/NASedgeFormat.H +++ b/src/edgeMesh/edgeFormats/nas/NASedgeFormat.H @@ -37,6 +37,7 @@ SourceFiles #define NASedgeFormat_H #include "edgeMesh.H" +#include "NASCore.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // @@ -51,7 +52,8 @@ namespace fileFormats class NASedgeFormat : - public edgeMesh + public edgeMesh, + public NASCore { // Private Member Functions @@ -61,13 +63,6 @@ class NASedgeFormat //- Disallow default bitwise assignment void operator=(const NASedgeFormat&); -protected: - - // Protected Member Functions - - //- Do weird things to extract number - static scalar parseNASCoord(const string&); - public: // Constructors diff --git a/src/edgeMesh/edgeFormats/starcd/STARCDedgeFormat.C b/src/edgeMesh/edgeFormats/starcd/STARCDedgeFormat.C index b6ecd4d19e..f2fec25cc5 100644 --- a/src/edgeMesh/edgeFormats/starcd/STARCDedgeFormat.C +++ b/src/edgeMesh/edgeFormats/starcd/STARCDedgeFormat.C @@ -59,134 +59,6 @@ inline void Foam::fileFormats::STARCDedgeFormat::writeLines // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // -bool Foam::fileFormats::STARCDedgeFormat::readHeader -( - IFstream& is, - const word& signature -) -{ - if (!is.good()) - { - FatalErrorIn - ( - "fileFormats::STARCDedgeFormat::readHeader(...)" - ) - << "cannot read " << signature << " " << is.name() - << abort(FatalError); - } - - word header; - label majorVersion; - - string line; - - is.getLine(line); - IStringStream(line)() >> header; - - is.getLine(line); - IStringStream(line)() >> majorVersion; - - // add other checks ... - if (header != signature) - { - Info<< "header mismatch " << signature << " " << is.name() - << endl; - } - - return true; -} - - -void Foam::fileFormats::STARCDedgeFormat::writeHeader -( - Ostream& os, - const char* filetype -) -{ - os << "PROSTAR_" << filetype << nl - << 4000 - << " " << 0 - << " " << 0 - << " " << 0 - << " " << 0 - << " " << 0 - << " " << 0 - << " " << 0 - << endl; -} - - -bool Foam::fileFormats::STARCDedgeFormat::readPoints -( - IFstream& is, - pointField& points, - labelList& ids -) -{ - // - // read .vrt file - // ~~~~~~~~~~~~~~ - - if (!is.good()) - { - FatalErrorIn - ( - "fileFormats::STARCDedgeFormat::readPoints(...)" - ) - << "Cannot read file " << is.name() - << exit(FatalError); - } - - readHeader(is, "PROSTAR_VERTEX"); - - DynamicList dynPoints; - DynamicList