ENH: driver/parser/scanner for patch expressions

This commit is contained in:
Mark Olesen
2019-12-03 12:34:36 +01:00
parent 019fe7deff
commit 82a1e32526
16 changed files with 6572 additions and 0 deletions

View File

@ -258,6 +258,13 @@ $(expr)/base/fvExprDriverFields.C
$(expr)/base/fvExprDriverIO.C $(expr)/base/fvExprDriverIO.C
$(expr)/base/fvExprDriverNew.C $(expr)/base/fvExprDriverNew.C
patchExpr = $(expr)/patch
$(patchExpr)/patchExpr.C
$(patchExpr)/patchExprDriver.C
$(patchExpr)/patchExprDriverFields.C
$(patchExpr)/patchExprLemonParser.lyy-m4
$(patchExpr)/patchExprScanner.cc
fvMatrices/fvMatrices.C fvMatrices/fvMatrices.C
fvMatrices/fvScalarMatrix/fvScalarMatrix.C fvMatrices/fvScalarMatrix/fvScalarMatrix.C

View File

@ -0,0 +1,13 @@
#!/bin/sh
cd ${0%/*} || exit 1 # Run from this directory
# Manually create ragel scanner and lemon parser header
prefix=patchExpr
"${WM_PROJECT_DIR:?}/wmake/scripts/makeParser" \
-prefix="$prefix" \
-scanner=Scanner.rl \
-parser=LemonParser.lyy-m4 \
"$@"
#------------------------------------------------------------------------------

View File

@ -0,0 +1,45 @@
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2019 OpenCFD Ltd.
-------------------------------------------------------------------------------
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 3 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, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "patchExprFwd.H"
#include "defineDebugSwitch.H"
// * * * * * * * * * * * * * * * * Globals * * * * * * * * * * * * * * * * * //
namespace Foam
{
namespace expressions
{
defineDebugSwitchWithName(patchExpr, "patchExpr", 0);
registerDebugSwitchWithName(patchExpr, patchExpr, "patchExpr");
} // End namespace expressions
} // End namespace Foam
// ************************************************************************* //

View File

@ -0,0 +1,188 @@
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2019 OpenCFD Ltd.
-------------------------------------------------------------------------------
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 3 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, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "patchExprDriver.H"
#include "patchExprScanner.H"
#include "error.H"
#include "fvPatch.H"
#include "fvMesh.H"
#include "className.H"
#include "addToRunTimeSelectionTable.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
namespace Foam
{
namespace expressions
{
namespace patchExpr
{
defineTypeNameAndDebug(parseDriver, 0);
addNamedToRunTimeSelectionTable
(
fvExprDriver,
parseDriver,
dictionary,
patch
);
addNamedToRunTimeSelectionTable
(
fvExprDriver,
parseDriver,
idName,
patch
);
} // End namespace patchExpr
} // End namespace expressions
} // End namespace Foam
// * * * * * * * * * * * * * * * Local Functions * * * * * * * * * * * * * * //
namespace Foam
{
static label getPatchID(const fvMesh& mesh, const word& patchName)
{
const auto& bMesh = mesh.boundaryMesh();
const label patchId = bMesh.findPatchID(patchName);
if (patchId < 0)
{
FatalErrorInFunction
<< "No patch " << patchName << " found in "
<< flatOutput(bMesh.names()) << nl
<< exit(FatalError);
}
return patchId;
}
static inline const fvPatch& findFvPatch
(
const fvMesh& mesh,
const word& patchName
)
{
return mesh.boundary()[getPatchID(mesh, patchName)];
}
} // End namespace Foam
// * * * * * * * * * * * * * Static Member Functions * * * * * * * * * * * * //
const Foam::fvPatch& Foam::expressions::patchExpr::parseDriver::getFvPatch
(
const fvMesh& fvm,
const dictionary& dict
)
{
return findFvPatch
(
regionMesh(dict, fvm, true),
dict.get<word>("patch")
);
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
Foam::expressions::patchExpr::parseDriver::parseDriver(const fvPatch& p)
:
parsing::genericRagelLemonDriver(),
expressions::fvExprDriver(),
patch_(p)
{}
Foam::expressions::patchExpr::parseDriver::parseDriver
(
const fvPatch& p,
const dictionary& dict
)
:
parsing::genericRagelLemonDriver(),
expressions::fvExprDriver(dict),
patch_(p)
{}
Foam::expressions::patchExpr::parseDriver::parseDriver
(
const fvPatch& p,
const parseDriver& driver_
)
:
parsing::genericRagelLemonDriver(),
expressions::fvExprDriver(driver_),
patch_(p)
{}
Foam::expressions::patchExpr::parseDriver::parseDriver
(
const word& patchName,
const fvMesh& mesh
)
:
parseDriver(findFvPatch(mesh, patchName))
{}
Foam::expressions::patchExpr::parseDriver::parseDriver
(
const dictionary& dict,
const fvMesh& mesh
)
:
parseDriver(getFvPatch(mesh, dict), dict)
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
unsigned Foam::expressions::patchExpr::parseDriver::parse
(
const std::string& expr,
size_t pos,
size_t len
)
{
scanner scan(this->debugScanner());
scan.process(expr, pos, len, *this);
return 0;
}
// ************************************************************************* //

View File

@ -0,0 +1,305 @@
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2019 OpenCFD Ltd.
-------------------------------------------------------------------------------
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 3 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, see <http://www.gnu.org/licenses/>.
Class
Foam::expressions::patchExpr::parseDriver
Description
Driver for patch expressions
In addition to the standard mathematical functions, operations and
logical and relational operations, the volume expression support the
following driver-specific functions:
Functions
\table
Function | Description | Number of arguments |
vol | The cell volumes | 0 |
pos | The face centres | 0 |
pts | The face points | 0 |
area | The face area magnitudes | 0 |
weightAverage| Area weighted average | 1 |
weightSum | Area weighted sum | 1 |
face | The face areaNormal vectors | 0 |
point | A point-field point value | 1 |
faceToPoint | Interpolate face values onto points | 1 |
pointToFace | Interpolate point values onto faces | 1 |
rand | Random field | 0/1 |
\endtable
SourceFiles
patchExprDriver.C
patchExprDriverFields.C
patchExprDriverTemplates.C
\*---------------------------------------------------------------------------*/
#ifndef expressions_patchExprDriver_H
#define expressions_patchExprDriver_H
#include "patchExprFwd.H"
#include "fvExprDriver.H"
#include "Enum.H"
#include "volFields.H"
#include "surfaceFields.H"
#include "pointFields.H"
#include "genericRagelLemonDriver.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
namespace expressions
{
namespace patchExpr
{
/*---------------------------------------------------------------------------*\
Class parseDriver Declaration
\*---------------------------------------------------------------------------*/
class parseDriver
:
public parsing::genericRagelLemonDriver,
public expressions::fvExprDriver
{
// Private Member Functions
static const fvPatch& getFvPatch
(
const fvMesh& fvm,
const dictionary& dict
);
protected:
// Protected Data
//- The referenced patch
const fvPatch& patch_;
// Protected Member Functions
// No copy copy construct
parseDriver(const parseDriver&) = delete;
// No copy assignment
void operator=(const parseDriver&) = delete;
public:
ClassName("patchExpr::driver");
// Constructors
//- Construct for specified patch
explicit parseDriver(const fvPatch& p);
//- Construct for specified patch with given dictionary
parseDriver(const fvPatch& p, const dictionary& dict);
//- Construct for specified patch with copy of driver context
parseDriver(const fvPatch& p, const parseDriver& driver_);
//- Construct with patchName for the given mesh
parseDriver(const word& patchName, const fvMesh& mesh);
//- Construct with "patch" (mandatory) and "region" (optional)
//- specified in dictionary
parseDriver(const dictionary& dict, const fvMesh& mesh);
//- Clone
virtual autoPtr<expressions::fvExprDriver> clone() const
{
return autoPtr<expressions::fvExprDriver>
(
new parseDriver(this->patch_, *this)
);
}
//- Destructor
virtual ~parseDriver() = default;
// Public Member Functions
//- The mesh we are attached to
virtual const fvMesh& mesh() const
{
return patch_.boundaryMesh().mesh();
}
//- The underlying field size for the expression
virtual label size() const
{
return patch_.patch().size();
}
//- The underlying point field size for the expression
virtual label pointSize() const
{
return patch_.patch().nPoints();
}
//- Field size associated with different geometric field types
inline label size(const FieldAssociation geoType) const;
// Evaluation
//- Perform parsing on (sub) string
using genericRagelLemonDriver::content;
//- Execute the parser
virtual unsigned parse
(
const std::string& expr,
size_t pos = 0,
size_t len = std::string::npos
);
// Field Information
// Fields
//- Set result
template<class Type>
void setResult(Field<Type>* ptr, bool pointVal = false)
{
result().setResult<Type>(ptr, pointVal);
}
//- Retrieve variable as field if possible.
// Test tmp for validity to determine success of the operation.
template<class Type>
tmp<Field<Type>> getVariableIfAvailable(const word& fldName) const;
//- Retrieve field (vol field)
template<class Type>
tmp<Field<Type>>
getVolField(const word& fldName);
//- Retrieve field (surface field)
template<class Type>
tmp<Field<Type>>
getSurfaceField(const word& fldName);
//- Retrieve field (point field)
template<class Type>
tmp<Field<Type>>
getPointField(const word& fldName);
//- Return named field
template<class Type>
tmp<Field<Type>> getField(const word& fldName);
// Field "shape" conversions
//- Interpolate face to point
template<class Type>
tmp<Field<Type>> faceToPoint(const Field<Type>& field) const;
//- Interpolate point to face values
template<class Type>
tmp<Field<Type>> pointToFace(const Field<Type>& field) const;
// Custom Field Functions
//- The area-weighted average of a field
template<class Type>
Type areaAverage(const Field<Type>& fld) const
{
return weightedAverage(patch_.magSf(), fld);
}
//- The area-weighted sum of a field
template<class Type>
Type areaSum(const Field<Type>& fld) const
{
return weightedSum(patch_.magSf(), fld);
}
//- The face area magnitudes [magSf] - (swak = area)
tmp<scalarField> field_faceArea() const;
//- The face centres - (swak = pos)
tmp<vectorField> field_faceCentre() const;
//- The face areas with their vector direction [Sf] - (swak = face)
tmp<vectorField> field_areaNormal() const;
//- The patch point locations - (swak = pts)
tmp<vectorField> field_pointField() const;
//- A uniform random field
tmp<scalarField> field_rand(label seed=0, bool gaussian=false) const;
//- A Gaussian random field
tmp<scalarField> field_randGaussian(label seed=0) const
{
return field_rand(seed, true);
}
};
// Template specializations
//- Retrieve field (surface field: bool)
template<>
tmp<Field<bool>> parseDriver::getSurfaceField<bool>(const word& fldName);
//- Retrieve field (point field: bool)
template<>
tmp<Field<bool>> parseDriver::getPointField<bool>(const word& fldName);
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace patchExpr
} // End namespace expressions
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#include "patchExprDriverI.H"
#ifdef NoRepository
#include "patchExprDriverTemplates.C"
#endif
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //

View File

@ -0,0 +1,100 @@
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2019 OpenCFD Ltd.
-------------------------------------------------------------------------------
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 3 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, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "patchExprDriver.H"
#include "fvPatch.H"
#include "error.H"
// * * * * * * * * * * * * Template Specializations * * * * * * * * * * * * //
template<>
Foam::tmp<Foam::Field<bool>>
Foam::expressions::patchExpr::parseDriver::getSurfaceField<bool>
(
const word& name
)
{
return getVariable<bool>(name, this->size());
}
template<>
Foam::tmp<Foam::Field<bool>>
Foam::expressions::patchExpr::parseDriver::getPointField<bool>
(
const word& name
)
{
return getVariable<bool>(name, this->pointSize());
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
Foam::tmp<Foam::scalarField>
Foam::expressions::patchExpr::parseDriver::field_faceArea() const
{
return patch_.magSf();
}
Foam::tmp<Foam::vectorField>
Foam::expressions::patchExpr::parseDriver::field_faceCentre() const
{
return patch_.Cf();
}
Foam::tmp<Foam::vectorField>
Foam::expressions::patchExpr::parseDriver::field_areaNormal() const
{
return patch_.Sf();
}
Foam::tmp<Foam::vectorField>
Foam::expressions::patchExpr::parseDriver::field_pointField() const
{
return patch_.patch().localPoints();
}
Foam::tmp<Foam::scalarField>
Foam::expressions::patchExpr::parseDriver::field_rand
(
label seed,
bool gaussian
) const
{
auto tresult = tmp<scalarField>::New(this->size());
fill_random(tresult.ref(), seed, gaussian);
return tresult;
}
// ************************************************************************* //

View File

@ -0,0 +1,50 @@
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2019 OpenCFD Ltd.
-------------------------------------------------------------------------------
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 3 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, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
inline Foam::label Foam::expressions::patchExpr::parseDriver::size
(
const FieldAssociation geoType
) const
{
switch (geoType)
{
case FieldAssociation::POINT_DATA :
return patch_.patch().nPoints();
break;
case FieldAssociation::SURFACE_DATA :
return patch_.patch().size();
break;
default:
break;
}
return 0;
}
// ************************************************************************* //

View File

@ -0,0 +1,228 @@
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2019 OpenCFD Ltd.
-------------------------------------------------------------------------------
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 3 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, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "primitivePatchInterpolation.H"
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class Type>
Foam::tmp<Foam::Field<Type>>
Foam::expressions::patchExpr::parseDriver::getVariableIfAvailable
(
const word& name
) const
{
bool isPointVal = false;
bool isUniformVal = false;
tmp<Field<Type>> tfield;
if (hasVariable(name) && variable(name).isType<Type>())
{
const expressions::exprResult& var = variable(name);
isPointVal = var.isPointValue();
isUniformVal = var.isUniform();
tfield = var.cref<Type>().clone();
}
else if (isGlobalVariable<Type>(name, false))
{
const expressions::exprResult& var = lookupGlobal(name);
isUniformVal = var.isUniform();
tfield = var.cref<Type>().clone();
}
if (tfield.valid())
{
const label fldLen = tfield().size();
const label len = (isPointVal ? this->pointSize() : this->size());
if (returnReduce((fldLen == len), andOp<bool>()))
{
return tfield;
}
if (!isUniformVal)
{
WarningInFunction
<< "Variable " << name
<< " does not fit the size and is not a uniform value." << nl
<< "Using average value" << endl;
}
return tmp<Field<Type>>::New(this->size(), gAverage(tfield));
}
return tfield;
}
template<class Type>
Foam::tmp<Foam::Field<Type>>
Foam::expressions::patchExpr::parseDriver::getVolField(const word& name)
{
return getField<Type>(name);
}
template<class Type>
Foam::tmp<Foam::Field<Type>>
Foam::expressions::patchExpr::parseDriver::getSurfaceField(const word& name)
{
return getField<Type>(name);
}
template<class Type>
Foam::tmp<Foam::Field<Type>>
Foam::expressions::patchExpr::parseDriver::getPointField(const word& name)
{
return getField<Type>(name);
}
template<class Type>
Foam::tmp<Foam::Field<Type>>
Foam::expressions::patchExpr::parseDriver::getField(const word& name)
{
tmp<Field<Type>> tfield = getVariableIfAvailable<Type>(name);
if (tfield.valid())
{
return tfield;
}
typedef GeometricField<Type, fvPatchField, volMesh> vfieldType;
typedef GeometricField<Type, fvsPatchField, surfaceMesh> sfieldType;
typedef GeometricField<Type, pointPatchField, pointMesh> pfieldType;
const objectRegistry& obr = this->mesh().thisDb();
const vfieldType* vfield = obr.findObject<vfieldType>(name);
const sfieldType* sfield = obr.findObject<sfieldType>(name);
const pfieldType* pfield = obr.findObject<pfieldType>(name);
// Local, temporary storage
tmp<vfieldType> t_vfield;
tmp<sfieldType> t_sfield;
tmp<pfieldType> t_pfield;
if (searchFiles() && !vfield && !sfield && !pfield)
{
const word fldType = this->getTypeOfField(name);
if (fldType == vfieldType::typeName)
{
t_vfield = this->readAndRegister<vfieldType>(name, mesh());
vfield = t_vfield.get();
}
else if (fldType == sfieldType::typeName)
{
t_sfield = this->readAndRegister<sfieldType>(name, mesh());
sfield = t_sfield.get();
}
else if (fldType == pfieldType::typeName)
{
t_pfield = this->readAndRegister<pfieldType>
(
name,
pointMesh::New(mesh())
);
pfield = t_pfield.get();
}
}
const label patchIndex = patch_.index();
if (vfield)
{
return tmp<Field<Type>>::New
(
vfield->boundaryField()[patchIndex]
);
}
if (sfield)
{
return tmp<Field<Type>>::New
(
sfield->boundaryField()[patchIndex]
);
}
if (pfield)
{
return pfield->boundaryField()[patchIndex].patchInternalField();
}
FatalErrorInFunction
<< "No field '" << name << "' of type "
<< pTraits<Type>::typeName << nl << nl
<< vfieldType::typeName << " Fields: "
<< flatOutput(obr.sortedNames<vfieldType>()) << nl
<< sfieldType::typeName << " Fields: "
<< flatOutput(obr.sortedNames<sfieldType>()) << nl
<< pfieldType::typeName << " Fields: "
<< flatOutput(obr.sortedNames<pfieldType>()) << nl
<< exit(FatalError);
return tmp<Field<Type>>::New();
}
template<class Type>
Foam::tmp<Foam::Field<Type>>
Foam::expressions::patchExpr::parseDriver::faceToPoint
(
const Field<Type>& field
) const
{
primitivePatchInterpolation interp(patch_.patch());
return interp.pointToFaceInterpolate(field);
}
template<class Type>
Foam::tmp<Foam::Field<Type>>
Foam::expressions::patchExpr::parseDriver::pointToFace
(
const Field<Type>& field
) const
{
primitivePatchInterpolation interp(patch_.patch());
return interp.faceToPointInterpolate(field);
}
// ************************************************************************* //

View File

@ -0,0 +1,84 @@
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2019 OpenCFD Ltd.
-------------------------------------------------------------------------------
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 3 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, see <http://www.gnu.org/licenses/>.
Namespace
Foam::expressions::patchExpr
Description
Namespace for patch expressions parsing and evaluation
\*---------------------------------------------------------------------------*/
#ifndef expressions_patchExprFwd_H
#define expressions_patchExprFwd_H
namespace Foam
{
namespace expressions
{
namespace patchExpr
{
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Forward Declarations
class parser;
class scanner;
class parseDriver;
union scanToken;
//- Static debugging option
extern int debug;
//- The field association for patch expressions (mutually exclusive)
enum FieldAssociation : unsigned char
{
NO_DATA = 0, //!< No data
POINT_DATA = 1, //!< Point data
SURFACE_DATA = 2 //!< Surface data
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace patchExpr
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
//- Typedef for patchExpr parseDriver
typedef patchExpr::parseDriver patchExprDriver;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace expressions
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //

View File

@ -0,0 +1,110 @@
#define TOK_QUESTION 1
#define TOK_COLON 2
#define TOK_LOR 3
#define TOK_LAND 4
#define TOK_BIT_XOR 5
#define TOK_BIT_AND 6
#define TOK_EQUAL 7
#define TOK_NOT_EQUAL 8
#define TOK_LESS_EQ 9
#define TOK_GREATER_EQ 10
#define TOK_LESS 11
#define TOK_GREATER 12
#define TOK_PLUS 13
#define TOK_MINUS 14
#define TOK_TIMES 15
#define TOK_DIVIDE 16
#define TOK_PERCENT 17
#define TOK_NEGATE 18
#define TOK_NOT 19
#define TOK_DOT 20
#define TOK_NUMBER 21
#define TOK_ZERO 22
#define TOK_PI 23
#define TOK_LPAREN 24
#define TOK_RPAREN 25
#define TOK_DEG_TO_RAD 26
#define TOK_RAD_TO_DEG 27
#define TOK_TIME 28
#define TOK_SCALAR_ID 29
#define TOK_SSCALAR_ID 30
#define TOK_MIN 31
#define TOK_COMMA 32
#define TOK_MAX 33
#define TOK_SUM 34
#define TOK_AVERAGE 35
#define TOK_EXP 36
#define TOK_LOG 37
#define TOK_LOG10 38
#define TOK_SQR 39
#define TOK_SQRT 40
#define TOK_CBRT 41
#define TOK_SIN 42
#define TOK_COS 43
#define TOK_TAN 44
#define TOK_ASIN 45
#define TOK_ACOS 46
#define TOK_ATAN 47
#define TOK_SINH 48
#define TOK_COSH 49
#define TOK_TANH 50
#define TOK_POW 51
#define TOK_ATAN2 52
#define TOK_POS 53
#define TOK_NEG 54
#define TOK_POS0 55
#define TOK_NEG0 56
#define TOK_SIGN 57
#define TOK_FLOOR 58
#define TOK_CEIL 59
#define TOK_ROUND 60
#define TOK_HYPOT 61
#define TOK_RAND 62
#define TOK_VECTOR_ID 63
#define TOK_SVECTOR_ID 64
#define TOK_SPH_TENSOR_ID 65
#define TOK_SSPH_TENSOR_ID 66
#define TOK_SYM_TENSOR_ID 67
#define TOK_SSYM_TENSOR_ID 68
#define TOK_UNIT_TENSOR 69
#define TOK_TENSOR_ID 70
#define TOK_STENSOR_ID 71
#define TOK_LTRUE 72
#define TOK_LFALSE 73
#define TOK_BOOL 74
#define TOK_SBOOL_ID 75
#define TOK_FACE_AREA 76
#define TOK_FACE_EXPR 77
#define TOK_WEIGHT_AVERAGE 78
#define TOK_WEIGHT_SUM 79
#define TOK_POINT_EXPR 80
#define TOK_PSCALAR_ID 81
#define TOK_PVECTOR_ID 82
#define TOK_PSPH_TENSOR_ID 83
#define TOK_PSYM_TENSOR_ID 84
#define TOK_PTENSOR_ID 85
#define TOK_PBOOL_ID 86
#define TOK_POINTS 87
#define TOK_MAG 88
#define TOK_MAGSQR 89
#define TOK_VECTOR 90
#define TOK_TENSOR 91
#define TOK_SYM_TENSOR 92
#define TOK_SPH_TENSOR 93
#define TOK_CMPT_X 94
#define TOK_CMPT_Y 95
#define TOK_CMPT_Z 96
#define TOK_CMPT_XX 97
#define TOK_CMPT_XY 98
#define TOK_CMPT_XZ 99
#define TOK_CMPT_YX 100
#define TOK_CMPT_YY 101
#define TOK_CMPT_YZ 102
#define TOK_CMPT_ZX 103
#define TOK_CMPT_ZY 104
#define TOK_CMPT_ZZ 105
#define TOK_CMPT_II 106
#define TOK_TRANSPOSE 107
#define TOK_DIAG 108
#define TOK_POINT_TO_FACE 109
#define TOK_FACE_TO_POINT 110

View File

@ -0,0 +1,565 @@
%include
{
/*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2019 OpenCFD Ltd.
-------------------------------------------------------------------------------
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 3 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, see <http://www.gnu.org/licenses/>.
Description
Lemon grammar for patch expressions.
https://www.sqlite.org/src/doc/trunk/doc/lemon.html
See detailed notes in the field expression parser.
\*---------------------------------------------------------------------------*/
} // %include
/*
* include[patchExprLemonParserMacros.m4]
*include(`patchExprLemonParserMacros.m4')dnl
!done in a comment since many editors have issues matching m4 quotes!
*/
%include
{
#include "patchExprDriver.H"
#include "patchExprParser.H"
#include "patchExprScanner.H"
#include "unitConversion.H"
#include "error.H"
#include "volFields.H"
#include "exprOps.H"
#include "exprDriverOps.H"
#include "GeometricFieldOps.H"
// Enable ParseTrace
#undef NDEBUG
compiler_pragmas()
// Local Functions
tmp_management()
} // %include
// ------------------------------------------------------------------------- //
%namespace {}
// Use extra argument for the return value
%extra_context { Foam::expressions::patchExpr::parseDriver* driver }
%parse_failure { driver->reportFatal("Parse failure, giving up..."); }
%syntax_error { driver->reportFatal("Syntax error"); }
%token_prefix TOK_
// Terminals
%token_type {Foam::expressions::patchExpr::scanToken*}
// Non-terminals
%type ivalue { Foam::label }
%type svalue { Foam::scalar }
%type ident { Foam::word* }
// Face fields
declare_field(lfield, Foam::boolField, bool, newField, getSurfaceField)
declare_field(sfield, Foam::scalarField, Foam::scalar, newField, getField)
declare_field(vfield, Foam::vectorField, Foam::vector, newField, getField)
declare_field(hfield, Foam::sphericalTensorField, Foam::sphericalTensor, newField, getField)
declare_field(yfield, Foam::symmTensorField, Foam::symmTensor, newField, getField)
declare_field(tfield, Foam::tensorField, Foam::tensor, newField, getField)
// Point fields
declare_field(plfield, Foam::boolField, bool, newPointField, getPointField)
declare_field(psfield, Foam::scalarField, Foam::scalar, newPointField, getPointField)
declare_field(pvfield, Foam::vectorField, Foam::vector, newPointField, getPointField)
declare_field(phfield, Foam::sphericalTensorField, Foam::sphericalTensor, newPointField, getPointField)
declare_field(pyfield, Foam::symmTensorField, Foam::symmTensor, newPointField, getPointField)
declare_field(ptfield, Foam::tensorField, Foam::tensor, newPointField, getPointField)
// For each rule action with code, destruction must be done by that code block
// Lemon does not generate a destructor for that.
// So do not use Lemon destructors for anything.
operator_precedence()
%start_symbol evaluate
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
/*---------------------------------------------------------------------------*\
* Productions (scalar)
\*---------------------------------------------------------------------------*/
svalue (lhs) ::= NUMBER (a) . { lhs = (a)->svalue; } // From scanToken
svalue (lhs) ::= ZERO . { lhs = Foam::Zero; }
svalue (lhs) ::= PI LPAREN RPAREN . { lhs = Foam::constant::mathematical::pi; }
svalue (lhs) ::= DEG_TO_RAD LPAREN RPAREN . { lhs = Foam::degToRad(); }
svalue (lhs) ::= RAD_TO_DEG LPAREN RPAREN . { lhs = Foam::radToDeg(); }
svalue (lhs) ::= TIME LPAREN RPAREN . { lhs = driver->timeValue(); }
/* * * * * * * * * * * * * * * * * Face Fields * * * * * * * * * * * * * * * *\
dnl
define([_logic_], [lfield])dnl
define([_scalar_], [sfield])dnl
define([_vector_], [vfield])dnl
define([_sphTensor_], [hfield])dnl
define([_symTensor_], [yfield])dnl
define([_tensor_], [tfield])dnl
dnl
\* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*---------------------------------------------------------------------------*\
* Productions (scalarField)
dnl
define([_target_], [sfield])dnl
define([_value_type_], [Foam::scalar])dnl
dnl
\*---------------------------------------------------------------------------*/
evaluate ::= _target_ (a) . { driver->setResult(a); }
rule_field_from_value(_target_, svalue)
rule_get_field(_target_, SCALAR_ID)
rule_get_field(_target_, SSCALAR_ID)
rules_standard(_target_, _value_type_, _logic_)
rules_inplace_gUnary(_target_)
rules_scalar_operations()
rules_scalar_functions()
// Non-standard but manage via FieldOps::assign
rule_unary_assign(_target_, _target_, FLOOR, Foam::floorOp<Foam::scalar>())
rule_unary_assign(_target_, _target_, CEIL, Foam::ceilOp<Foam::scalar>())
rule_unary_assign(_target_, _target_, ROUND, Foam::roundOp<Foam::scalar>())
// Non-standard but works directly for scalarField
rule_binary_func(_target_, _target_, _target_, HYPOT, Foam::hypot)
// Other functions
_target_ (lhs) ::= RAND LPAREN RPAREN.
{
lhs = driver->field_rand().ptr();
}
_target_ (lhs) ::= RAND LPAREN NUMBER (seed) RPAREN.
{
// Call with -ve seed to signal use of time index as seed
lhs = driver->field_rand(std::round(-(seed)->svalue)).ptr();
}
/*---------------------------------------------------------------------------*\
* Productions (vectorField)
dnl
define([_target_], [vfield])dnl
define([_value_type_], [Foam::vector])dnl
dnl
\*---------------------------------------------------------------------------*/
evaluate ::= _target_ (a) . { driver->setResult(a); }
rule_get_field(_target_, VECTOR_ID)
rule_get_field(_target_, SVECTOR_ID)
rules_standard(_target_, _value_type_, _logic_)
rules_inplace_gUnary(_target_)
rules_vector_operations()
rules_vector_functions()
/*---------------------------------------------------------------------------*\
* Productions (sphericalTensorField)
dnl
define([_target_], [hfield])dnl
define([_value_type_], [Foam::sphericalTensor])dnl
dnl
\*---------------------------------------------------------------------------*/
evaluate ::= _target_ (a) . { driver->setResult(a); }
rule_get_field(_target_, SPH_TENSOR_ID)
rule_get_field(_target_, SSPH_TENSOR_ID)
rules_standard(_target_, _value_type_, _logic_)
rules_inplace_gUnary(_target_)
rules_sphTensor_operations()
rules_sphTensor_functions()
/*---------------------------------------------------------------------------*\
* Productions (symmTensorField)
dnl
define([_target_], [yfield])dnl
define([_value_type_], [Foam::symmTensor])dnl
dnl
\*---------------------------------------------------------------------------*/
evaluate ::= _target_ (a) . { driver->setResult(a); }
rule_get_field(_target_, SYM_TENSOR_ID)
rule_get_field(_target_, SSYM_TENSOR_ID)
rules_standard(_target_, _value_type_, _logic_)
rules_inplace_gUnary(_target_)
rules_symTensor_operations()
rules_symTensor_functions()
/*---------------------------------------------------------------------------*\
* Productions (tensorField)
dnl
define([_target_], [tfield])dnl
define([_value_type_], [Foam::tensor])dnl
dnl
\*---------------------------------------------------------------------------*/
evaluate ::= _target_ (a) . { driver->setResult(a); }
tfield (lhs) ::= UNIT_TENSOR . { lhs = _new_tfield(Foam::tensor::I); }
rule_get_field(_target_, TENSOR_ID)
rule_get_field(_target_, STENSOR_ID)
rules_standard(_target_, _value_type_, _logic_)
rules_inplace_gUnary(_target_)
rules_tensor_operations()
rules_tensor_functions()
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
/*---------------------------------------------------------------------------*\
* Logic field productions (boolField)
dnl
define([_target_], [lfield])dnl
define([_value_type_], [bool])dnl
dnl
\*---------------------------------------------------------------------------*/
evaluate ::= _target_ (a) . { driver->setResult(a); }
_logic_ (lhs) ::= LTRUE . { lhs = _new_lfield(_logic_true_); }
_logic_ (lhs) ::= LFALSE . { lhs = _new_lfield(_logic_false_); }
rule_cast_logical(_target_, _target_)
rule_cast_logical(_target_, _scalar_, Foam::scalar)
dnl/* Handling of named logic fields not really tested (disable in scanner) */
rule_get_field(_target_, SBOOL_ID)
rules_logical_operations(_logic_, _value_type_)
/*---------------------------------------------------------------------------*\
* General Surface-related productions
\*---------------------------------------------------------------------------*/
rules_driver_surface_functions()
/* * * * * * * * * * * * * * * * Point Fields * * * * * * * * * * * * * * * *\
dnl
define([_logic_], [plfield])dnl
define([_scalar_], [psfield])dnl
define([_vector_], [pvfield])dnl
define([_sphTensor_], [phfield])dnl
define([_symTensor_], [pyfield])dnl
define([_tensor_], [ptfield])dnl
dnl
\* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*---------------------------------------------------------------------------*\
* Productions (point scalarField)
dnl
define([_target_], [psfield])dnl
define([_value_type_], [Foam::scalar])dnl
dnl
\*---------------------------------------------------------------------------*/
evaluate ::= _target_ (a) . { driver->setResult(a, true); /* Point */ }
rule_field_from_value(_target_, svalue, POINT_EXPR)
rule_get_field(_target_, PSCALAR_ID)
rules_standard(_target_, _value_type_, _logic_)
rules_inplace_gUnary(_target_)
rules_scalar_operations()
rules_scalar_functions()
// Non-standard but manage via FieldOps::assign
rule_unary_assign(_target_, _target_, FLOOR, Foam::floorOp<Foam::scalar>())
rule_unary_assign(_target_, _target_, CEIL, Foam::ceilOp<Foam::scalar>())
rule_unary_assign(_target_, _target_, ROUND, Foam::roundOp<Foam::scalar>())
// Non-standard but works directly for scalarField
rule_binary_func(_target_, _target_, _target_, HYPOT, Foam::hypot)
/*---------------------------------------------------------------------------*\
* Productions (point vectorField)
dnl
define([_target_], [pvfield])dnl
define([_value_type_], [Foam::vector])dnl
dnl
\*---------------------------------------------------------------------------*/
evaluate ::= _target_ (a) . { driver->setResult(a, true); /* Point */ }
rule_get_field(_target_, PVECTOR_ID)
rules_standard(_target_, _value_type_, _logic_)
rules_inplace_gUnary(_target_)
rules_vector_operations()
rules_vector_functions()
/*---------------------------------------------------------------------------*\
* Productions (point sphericalTensorField)
dnl
define([_target_], [phfield])dnl
define([_value_type_], [Foam::sphericalTensor])dnl
dnl
\*---------------------------------------------------------------------------*/
evaluate ::= _target_ (a) . { driver->setResult(a, true); /* Point */ }
rule_get_field(_target_, PSPH_TENSOR_ID)
rules_standard(_target_, _value_type_, _logic_)
rules_inplace_gUnary(_target_)
rules_sphTensor_operations()
rules_sphTensor_functions()
/*---------------------------------------------------------------------------*\
* Productions (point symmTensorField)
dnl
define([_target_], [pyfield])dnl
define([_value_type_], [Foam::symmTensor])dnl
dnl
\*---------------------------------------------------------------------------*/
evaluate ::= _target_ (a) . { driver->setResult(a, true); /* Point */ }
rule_get_field(_target_, PSYM_TENSOR_ID)
rules_standard(_target_, _value_type_, _logic_)
rules_inplace_gUnary(_target_)
rules_symTensor_operations()
rules_symTensor_functions()
/*---------------------------------------------------------------------------*\
* Productions (point tensorField)
dnl
define([_target_], [ptfield])dnl
define([_value_type_], [Foam::tensor])dnl
dnl
\*---------------------------------------------------------------------------*/
evaluate ::= _target_ (a) . { driver->setResult(a, true); /* Point */ }
rule_get_field(_target_, PTENSOR_ID)
rules_standard(_target_, _value_type_, _logic_)
rules_inplace_gUnary(_target_)
rules_tensor_operations()
rules_tensor_functions()
/*---------------------------------------------------------------------------*\
* Logic field productions (point boolField)
dnl
define([_target_], [plfield])dnl
define([_value_type_], [bool])dnl
dnl
\*---------------------------------------------------------------------------*/
evaluate ::= _target_ (a) . { driver->setResult(a, true); /* Point */ }
_logic_ (lhs) ::= POINT_EXPR LPAREN LTRUE RPAREN . { lhs = _new_plfield(_logic_true_); }
_logic_ (lhs) ::= POINT_EXPR LPAREN LFALSE RPAREN . { lhs = _new_plfield(_logic_false_); }
rule_cast_logical(_target_, _target_)
rule_cast_logical(_target_, _scalar_, Foam::scalar)
dnl/* Handling of named logic fields not really tested (disable in scanner) */
rule_get_field(_target_, PBOOL_ID)
rules_logical_operations(_logic_, _value_type_)
/*---------------------------------------------------------------------------*\
* General Point-related productions
\*---------------------------------------------------------------------------*/
rules_driver_point_functions()
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
/*---------------------------------------------------------------------------*\
* Face field composition
\*---------------------------------------------------------------------------*/
rule_mag_logical(sfield, lfield)
rules_mag_functions(sfield, sfield)
rules_mag_functions(sfield, vfield)
rules_mag_functions(sfield, tfield)
rules_mag_functions(sfield, yfield)
rules_mag_functions(sfield, hfield)
rule_vector_zip(vfield, sfield, VECTOR)
rule_tensor_zip(tfield, sfield, TENSOR)
rule_symTensor_zip(yfield, sfield, SYM_TENSOR)
rule_sphTensor_zip(hfield, sfield, SPH_TENSOR)
rule_vector_components(sfield, vfield)
rule_tensor_components(sfield, tfield)
rule_symTensor_components(sfield, yfield)
rule_sphTensor_components(sfield, hfield)
rule_tensor_transpose(tfield)
rule_symTensor_transpose(yfield)
rule_sphTensor_transpose(hfield)
rule_tensor_unzipDiag(vfield, yfield)
rule_tensor_unzipAll(vfield, tfield)
rule_pointToFace(sfield, psfield)
rule_pointToFace(vfield, pvfield)
rule_pointToFace(tfield, ptfield)
rule_pointToFace(yfield, pyfield)
rule_pointToFace(hfield, phfield)
/*---------------------------------------------------------------------------*\
* Point field composition
\*---------------------------------------------------------------------------*/
rule_mag_logical(psfield, plfield)
rules_mag_functions(psfield, psfield)
rules_mag_functions(psfield, pvfield)
rules_mag_functions(psfield, ptfield)
rules_mag_functions(psfield, pyfield)
rules_mag_functions(psfield, phfield)
rule_vector_zip(pvfield, psfield, VECTOR)
rule_tensor_zip(ptfield, psfield, TENSOR)
rule_symTensor_zip(pyfield, psfield, SYM_TENSOR)
rule_sphTensor_zip(phfield, psfield, SPH_TENSOR)
rule_vector_components(psfield, pvfield)
rule_tensor_components(psfield, ptfield)
rule_symTensor_components(psfield, pyfield)
rule_sphTensor_components(psfield, phfield)
rule_tensor_transpose(ptfield)
rule_symTensor_transpose(pyfield)
rule_sphTensor_transpose(phfield)
rule_tensor_unzipDiag(pvfield, pyfield)
rule_tensor_unzipAll(pvfield, ptfield)
rule_faceToPoint(psfield, sfield)
rule_faceToPoint(pvfield, vfield)
rule_faceToPoint(ptfield, tfield)
rule_faceToPoint(pyfield, yfield)
rule_faceToPoint(phfield, hfield)
// ************************************************************************* //
dnl/* Standard m4 quoting
changequote([`],['])dnl
dnl*/
%code
{
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
void Foam::expressions::patchExpr::parser::stop()
{
if (lemon_)
{
ParseFree(lemon_, ::operator delete);
#ifndef NDEBUG
ParseTrace(nullptr, nullptr);
#endif
lemon_ = nullptr;
}
}
void Foam::expressions::patchExpr::parser::start(parseDriver& driver_)
{
this->stop();
lemon_ = ParseAlloc(::operator new, &driver_);
if (debug || driver_.debugParser())
{
#ifndef NDEBUG
ParseTrace(stderr, const_cast<char*>(prompt_));
#endif
}
}
void Foam::expressions::patchExpr::parser::parse
(
int tokenId,
scanToken* tokenVal
)
{
Parse(lemon_, tokenId, tokenVal);
}
Foam::word Foam::expressions::patchExpr::parser::nameOfToken
(
int tokenId
) const
{
#ifndef NDEBUG
if
(
tokenId > 0
&& unsigned(tokenId) < (sizeof(yyTokenName) / sizeof(char*))
)
{
return yyTokenName[tokenId];
}
return "<invalid>";
#else
return word();
#endif
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End of %code
// ************************************************************************* //

View File

@ -0,0 +1,109 @@
divert(-1)dnl
#-----------------------------------*- m4 -*-----------------------------------
# ========= |
# \\ / F ield | OpenFOAM: The Open Source CFD Toolbox
# \\ / O peration |
# \\ / A nd | www.openfoam.com
# \\/ M anipulation |
#------------------------------------------------------------------------------
# Copyright (C) 2019 OpenCFD Ltd.
#------------------------------------------------------------------------------
# License
# This file is part of OpenFOAM, licensed under GNU General Public License
# <http://www.gnu.org/licenses/>.
#
# Description
# Driver-specific m4/lemon macros for patch expressions.
#
#------------------------------------------------------------------------------
include(`m4/lemon/base-setup.m4')dnl
include([m4/lemon/operator-precedence.m4])dnl
dnl
include([m4/lemon/rules-standard.m4])dnl
include([m4/lemon/rules-operations.m4])dnl
include([m4/lemon/rules-functions.m4])dnl
include([m4/lemon/rules-components.m4])dnl
include([m4/lemon/rules-fields-components.m4])dnl
include([m4/lemon/rules-scalar-logic.m4])dnl
dnl
divert(-1)dnl
use_bool_logic()dnl # Use boolField directly
#-------------------------------------------------------------------------------
# Driver rules
#-------------------------------------------------------------------------------
define([rules_driver_surface_functions],
[dnl
rule_driver_nullary(_scalar_, FACE_AREA, field_faceArea)dnl
rule_driver_nullary(_vector_, POS, field_faceCentre)dnl FACE_CENTRE
rule_driver_nullary(_vector_, FACE_EXPR, field_areaNormal)dnl
dnl
rule_driver_inplace_unary(_scalar_, WEIGHT_AVERAGE, areaAverage)dnl
rule_driver_inplace_unary(_vector_, WEIGHT_AVERAGE, areaAverage)dnl
rule_driver_inplace_unary(_sphTensor_, WEIGHT_AVERAGE, areaAverage)dnl
rule_driver_inplace_unary(_symTensor_, WEIGHT_AVERAGE, areaAverage)dnl
rule_driver_inplace_unary(_tensor_, WEIGHT_AVERAGE, areaAverage)dnl
dnl
rule_driver_inplace_unary(_scalar_, WEIGHT_SUM, areaSum)dnl
rule_driver_inplace_unary(_vector_, WEIGHT_SUM, areaSum)dnl
rule_driver_inplace_unary(_sphTensor_, WEIGHT_SUM, areaSum)dnl
rule_driver_inplace_unary(_symTensor_, WEIGHT_SUM, areaSum)dnl
rule_driver_inplace_unary(_tensor_, WEIGHT_SUM, areaSum)dnl
dnl
])
define([rules_driver_point_functions],
[dnl
rule_driver_nullary(_vector_, POINTS, field_pointField)dnl
dnl
dnl NB use non-driver versions for points - ie, unweighted
dnl
rule_inplace_unary(_scalar_, WEIGHT_AVERAGE, Foam::gAverage)dnl
rule_inplace_unary(_vector_, WEIGHT_AVERAGE, Foam::gAverage)dnl
rule_inplace_unary(_sphTensor_, WEIGHT_AVERAGE, Foam::gAverage)dnl
rule_inplace_unary(_symTensor_, WEIGHT_AVERAGE, Foam::gAverage)dnl
rule_inplace_unary(_tensor_, WEIGHT_AVERAGE, Foam::gAverage)dnl
dnl
rule_inplace_unary(_scalar_, WEIGHT_SUM, Foam::gSum)dnl
rule_inplace_unary(_vector_, WEIGHT_SUM, Foam::gSum)dnl
rule_inplace_unary(_sphTensor_, WEIGHT_SUM, Foam::gSum)dnl
rule_inplace_unary(_symTensor_, WEIGHT_SUM, Foam::gSum)dnl
rule_inplace_unary(_tensor_, WEIGHT_SUM, Foam::gSum)dnl
dnl
])
#------------------------------------------------------------------------------
# rule_faceToPoint(out, in)
# rule_pointToFace(out, in)
#
# Description
# Production rules for driver faceToPoint, pointToFace,
# methods
#------------------------------------------------------------------------------
define([rule_faceToPoint],
[rule_driver_unary($1, $2, FACE_TO_POINT, faceToPoint)])
define([rule_pointToFace],
[rule_driver_unary($1, $2, POINT_TO_FACE, pointToFace)])
#------------------------------------------------------------------------------
# Standard rules for fields: declaration, new/get, driver functions etc.
include([m4/lemon/rules-fields.m4])dnl
divert(-1)dnl
#------------------------------------------------------------------------------
# Additional safety measures
undefine([substr])dnl # Avoid collision with C/C++ naming
#------------------------------------------------------------------------------
divert(0)dnl

View File

@ -0,0 +1,106 @@
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2019 OpenCFD Ltd.
-------------------------------------------------------------------------------
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 3 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, see <http://www.gnu.org/licenses/>.
Class
Foam::expressions::patchExpr::parser
Description
Lemon parser interface for patch expressions grammar
\*---------------------------------------------------------------------------*/
#ifndef expressions_patchExprParser_H
#define expressions_patchExprParser_H
#include "patchExprFwd.H"
namespace Foam
{
namespace expressions
{
namespace patchExpr
{
/*---------------------------------------------------------------------------*\
Class parser Declaration
\*---------------------------------------------------------------------------*/
class parser
{
// Private Data
//- Prompt for parser tracing
static constexpr const char* const prompt_ = "patchExpr:";
//- The lemon parser (demand-driven)
void* lemon_;
public:
//- Local object debugging
int debug;
// Constructors
//- Construct null
parser() : lemon_(nullptr), debug(patchExpr::debug) {}
//- Destructor, deletes parser backend
~parser()
{
stop();
}
// Member Functions
//- Start parsing, with the given driver context
void start(parseDriver& driver_);
//- Stop parsing, freeing the allocated parser
void stop();
//- Push token/value to parser
void parse(int tokenId, scanToken* tokenVal);
//- Return the text name corresponding to the tokenId
word nameOfToken(int tokenId) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace patchExpr
} // End namespace expressions
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //

View File

@ -0,0 +1,162 @@
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2019 OpenCFD Ltd.
-------------------------------------------------------------------------------
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 3 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, see <http://www.gnu.org/licenses/>.
Class
Foam::expressions::patchExpr::scanner
Description
Ragel lexer/scanner interface for patch expressions.
Note
Ragel code generated with the ./createCode script.
\*---------------------------------------------------------------------------*/
#ifndef expressions_patchExprScanner_H
#define expressions_patchExprScanner_H
#include "patchExprFwd.H"
#include "scalar.H"
namespace Foam
{
namespace expressions
{
namespace patchExpr
{
/*---------------------------------------------------------------------------*\
Class scanToken Declaration
\*---------------------------------------------------------------------------*/
union scanToken
{
Foam::label ivalue;
Foam::scalar svalue;
Foam::word* name;
//- Null construct, bit-wise zero for union content
scanToken() : ivalue(0) {}
};
/*---------------------------------------------------------------------------*\
Class scanner Declaration
\*---------------------------------------------------------------------------*/
class scanner
{
// Private Data
//- Wrapped lemon parser
parser* parser_;
// Ragel code state, action
int cs, act;
// Private Member Functions
//- Dispatch .method to parser (if known) or Fatal
bool dispatch_method
(
const parseDriver& driver_,
scanToken& scanTok,
word&& ident
) const;
//- Dispatch identifier to parser (if possible) or Fatal
bool dispatch_ident
(
const parseDriver& driver_,
scanToken& scanTok,
word&& ident
) const;
public:
//- Local debugging
int debug;
// Constructors
//- Construct null, optionally setting debugging
explicit scanner(bool withDebug = false)
:
parser_(nullptr),
debug(patchExpr::debug)
{
if (withDebug)
{
debug |= 4;
}
}
//- Destructor, deletes parser
~scanner();
// Member Functions
//- Evaluate sub-string
bool process
(
const std::string& str, size_t pos, size_t len,
parseDriver& driver_
);
//- Evaluate sub-string
bool process
(
const std::string& str, size_t pos,
parseDriver& driver_
)
{
return process(str, pos, std::string::npos, driver_);
}
//- Evaluate string
bool process(const std::string& str, parseDriver& driver_)
{
return process(str, 0, std::string::npos, driver_);
}
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace patchExpr
} // End namespace expressions
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,664 @@
/*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2019 OpenCFD Ltd.
-------------------------------------------------------------------------------
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 3 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, see <http://www.gnu.org/licenses/>.
Description
Ragel lexer interface for lemon grammar for patch expressions
\*---------------------------------------------------------------------------*/
#include "patchExprScanner.H"
#include "patchExprDriver.H"
#include "patchExprLemonParser.h"
#include "patchExprParser.H"
#include "Enum.H"
#include "macros.H"
#pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
#pragma GCC diagnostic ignored "-Wold-style-cast"
// Debugging to stderr
#undef DebugInfo
#define DebugInfo if (debug) InfoErr
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
namespace Foam
{
//- Paste token prefix
#define TOKEN_OF(T) TOK_##T
//- An {int, c_str} enum pairing
#define TOKEN_PAIR(Name,T) { TOKEN_OF(T), Name }
#undef HAS_LOOKBEHIND_TOKENS
// Special handling of predefined method types. Eg, .x(), .y(), ...
static const Enum<int> fieldMethodEnums
({
TOKEN_PAIR("x", CMPT_X),
TOKEN_PAIR("y", CMPT_Y),
TOKEN_PAIR("z", CMPT_Z),
TOKEN_PAIR("xx", CMPT_XX),
TOKEN_PAIR("xy", CMPT_XY),
TOKEN_PAIR("xz", CMPT_XZ),
TOKEN_PAIR("yx", CMPT_YX),
TOKEN_PAIR("yy", CMPT_YY),
TOKEN_PAIR("yz", CMPT_YZ),
TOKEN_PAIR("zx", CMPT_ZX),
TOKEN_PAIR("zy", CMPT_ZY),
TOKEN_PAIR("zz", CMPT_ZZ),
TOKEN_PAIR("ii", CMPT_II),
TOKEN_PAIR("diag", DIAG), /* tensors only */
TOKEN_PAIR("T", TRANSPOSE), /* tensors only */
});
// Known field-token types
static const Enum<int> fieldTokenEnums
({
#ifdef TOK_SCALAR_ID
TOKEN_PAIR(volScalarField::typeName.c_str(), SCALAR_ID),
TOKEN_PAIR(volVectorField::typeName.c_str(), VECTOR_ID),
TOKEN_PAIR(volTensorField::typeName.c_str(), TENSOR_ID),
TOKEN_PAIR(volSymmTensorField::typeName.c_str(), SYM_TENSOR_ID),
TOKEN_PAIR(volSphericalTensorField::typeName.c_str(), SPH_TENSOR_ID),
#else
#error TOK_SCALAR_ID not defined
#endif
#ifdef TOK_SSCALAR_ID
TOKEN_PAIR(surfaceScalarField::typeName.c_str(), SSCALAR_ID),
TOKEN_PAIR(surfaceVectorField::typeName.c_str(), SVECTOR_ID),
TOKEN_PAIR(surfaceTensorField::typeName.c_str(), STENSOR_ID),
TOKEN_PAIR(surfaceSymmTensorField::typeName.c_str(), SSYM_TENSOR_ID),
TOKEN_PAIR(surfaceSphericalTensorField::typeName.c_str(), SSPH_TENSOR_ID),
#else
#error TOK_SSCALAR_ID not defined
#endif
#ifdef TOK_PSCALAR_ID
TOKEN_PAIR(pointScalarField::typeName.c_str(), PSCALAR_ID),
TOKEN_PAIR(pointVectorField::typeName.c_str(), PVECTOR_ID),
TOKEN_PAIR(pointTensorField::typeName.c_str(), PTENSOR_ID),
TOKEN_PAIR(pointSymmTensorField::typeName.c_str(), PSYM_TENSOR_ID),
TOKEN_PAIR(pointSphericalTensorField::typeName.c_str(), PSPH_TENSOR_ID),
#else
#warning TOK_PSCALAR_ID not defined
#endif
});
// Simple compile-time function name declarations.
// Useful for handling driver-specific dispatching, or functions that
// are not universally available.
static const Enum<int> funcTokenEnums
({
#ifdef TOK_FLOOR
TOKEN_PAIR("floor", FLOOR),
TOKEN_PAIR("ceil", CEIL),
TOKEN_PAIR("round", ROUND),
#endif
#ifdef TOK_HYPOT /* Can use hypot? */
TOKEN_PAIR("hypot", HYPOT),
#endif
// Already parsed as function: TOKEN_PAIR("pos", FACE_CENTRE),
TOKEN_PAIR("point", POINT_EXPR), // Point value
TOKEN_PAIR("face", FACE_EXPR), // Face areaNormal
TOKEN_PAIR("faceToPoint", FACE_TO_POINT),
TOKEN_PAIR("pointToFace", POINT_TO_FACE),
TOKEN_PAIR("area", FACE_AREA),
TOKEN_PAIR("pts", POINTS),
});
} // End namespace Foam
// * * * * * * * * * * * * * * * Local Functions * * * * * * * * * * * * * * //
namespace Foam
{
// Classifying token type based on an identifier name is indeed ugly.
//
// 1)
// Handle special cases (eg, cellSet,...) first that have been tagged
// as expected content with the stashed "look-behind" token.
// Handle not-found errors here directly.
//
// 2)
// Fallback to determining which field-type (volScalarField etc) the name
// corresponds to.
// Handle not-found errors by return -1.
//
static int driverTokenType
(
const expressions::patchExpr::parseDriver& driver_,
const word& ident
)
{
#if 0
// Get stashed "look-behind" to decide what type of identifier we expect
const int lookBehind = driver_.resetStashedTokenId();
if (lookBehind && lookBehindTokenEnums.found(lookBehind))
{
bool good = false;
switch (lookBehind)
{
case TOK_CSET : good = driver_.isCellSet(ident); break;
case TOK_FSET : good = driver_.isFaceSet(ident); break;
case TOK_PSET : good = driver_.isPointSet(ident); break;
case TOK_CZONE : good = driver_.isCellZone(ident); break;
case TOK_FZONE : good = driver_.isFaceZone(ident); break;
case TOK_PZONE : good = driver_.isPointZone(ident); break;
}
if (good)
{
return TOK_IDENTIFIER;
}
// Fatal
driver_.reportFatal
(
"Error no " + lookBehindTokenEnums.get(lookBehind) + ": " + ident
);
return -2; // Extra safety
}
#endif
// Face variables
#ifdef TOK_SSCALAR_ID
{
#undef checkFieldToken
#define checkFieldToken(TokType, Type) \
if (driver_.isVariable<Type>(ident, false)) \
{ \
return TokType; \
}
checkFieldToken(TOK_SSCALAR_ID, scalar);
checkFieldToken(TOK_SVECTOR_ID, vector);
checkFieldToken(TOK_SSYM_TENSOR_ID, symmTensor);
checkFieldToken(TOK_SSPH_TENSOR_ID, sphericalTensor);
checkFieldToken(TOK_STENSOR_ID, tensor);
// Not tested: checkFieldToken(TOK_SBOOL_ID, bool);
}
#endif
// Point variables
#ifdef TOK_PSCALAR_ID
{
#undef checkFieldToken
#define checkFieldToken(TokType, Type) \
if (driver_.isVariable<Type>(ident, true)) \
{ \
return TokType; \
}
checkFieldToken(TOK_PSCALAR_ID, scalar);
checkFieldToken(TOK_PVECTOR_ID, vector);
checkFieldToken(TOK_PTENSOR_ID, tensor);
checkFieldToken(TOK_PTENSOR_ID, tensor);
checkFieldToken(TOK_PSYM_TENSOR_ID, symmTensor);
checkFieldToken(TOK_PSPH_TENSOR_ID, sphericalTensor);
// Not tested: checkFieldToken(TOK_PBOOL_ID, bool);
}
#endif
#undef checkFieldToken
// Check registered fields and/or disk-files
{
const word fieldType(driver_.getFieldClassName(ident));
int tokType = fieldTokenEnums.get(fieldType, -1);
if (tokType > 0)
{
return tokType;
}
}
return -1;
}
} // End anonymous namespace
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
// Ragel machine definition
// Ragel variables (p, pe, eof, cs, top, stack, ts, te, act) defined later...
//
// Can use 'variable p xxx;' etc to change these names
#define EMIT_TOKEN(T) \
driver_.parsePosition() = (ts-buf); \
DebugInfo<< STRINGIFY(T) << ": " << driver_.parsePosition() << nl; \
parser_->parse(TOKEN_OF(T), nullptr); \
driver_.parsePosition() = (p-buf);
%%{
machine patchExpr;
write data;
action emit_number {
driver_.parsePosition() = (ts-buf);
DebugInfo
<< "Number:" << std::string(ts, te-ts).c_str()
<< " at " << driver_.parsePosition() << nl;
if (readScalar(std::string(ts, te-ts), scanTok.svalue))
{
parser_->parse(TOKEN_OF(NUMBER), &scanTok);
}
else
{
driver_.reportFatal
(
"Error parsing number: " + std::string(ts, te-ts)
);
}
driver_.parsePosition() = (p-buf);
}
action emit_ident {
driver_.parsePosition() = (ts-buf);
dispatch_ident(driver_, scanTok, word(ts, te-ts, false));
driver_.parsePosition() = (p-buf);
}
action emit_method {
// Tokenized ".method" - dispatch '.' and "method" separately
driver_.parsePosition() = (ts-buf);
dispatch_method(driver_, scanTok, word(ts+1, te-ts-1, false));
driver_.parsePosition() = (p-buf);
}
decimal = ((digit* '.' digit+) | (digit+ '.'?)) ;
number = ((digit+ | decimal) ([Ee][\-+]? digit+)?) ;
ident = ((alpha|'_') . ((alnum|[._])**)) ;
dquoted = '"' [^\"]+ '"' ;
squoted = "'" [^\']+ "'" ;
## The scanner
main := |*
space*;
number => emit_number;
## operators
'!' =>{ EMIT_TOKEN(NOT); };
'%' =>{ EMIT_TOKEN(PERCENT); };
'(' =>{ EMIT_TOKEN(LPAREN); };
')' =>{ EMIT_TOKEN(RPAREN); };
'*' =>{ EMIT_TOKEN(TIMES); };
'+' =>{ EMIT_TOKEN(PLUS); };
'-' =>{ EMIT_TOKEN(MINUS); };
',' =>{ EMIT_TOKEN(COMMA); };
'.' =>{ EMIT_TOKEN(DOT); };
'/' =>{ EMIT_TOKEN(DIVIDE); };
'?' =>{ EMIT_TOKEN(QUESTION); };
':' =>{ EMIT_TOKEN(COLON); };
'<' =>{ EMIT_TOKEN(LESS); };
'<=' =>{ EMIT_TOKEN(LESS_EQ); };
'>' =>{ EMIT_TOKEN(GREATER); };
'>=' =>{ EMIT_TOKEN(GREATER_EQ); };
'==' =>{ EMIT_TOKEN(EQUAL); };
'!=' =>{ EMIT_TOKEN(NOT_EQUAL); };
'&&' =>{ EMIT_TOKEN(LAND); };
'||' =>{ EMIT_TOKEN(LOR); };
'&' =>{ EMIT_TOKEN(BIT_AND); };
## Not needed? '|' =>{ EMIT_TOKEN(BIT_OK); };
'^' =>{ EMIT_TOKEN(BIT_XOR); };
## Some '.method' - Error if unknown
'.' alpha+ => emit_method;
## Regular functions
"pi" =>{ EMIT_TOKEN(PI); };
"degToRad" =>{ EMIT_TOKEN(DEG_TO_RAD); };
"radToDeg" =>{ EMIT_TOKEN(RAD_TO_DEG); };
"exp" =>{ EMIT_TOKEN(EXP); };
"log" =>{ EMIT_TOKEN(LOG); };
"log10" =>{ EMIT_TOKEN(LOG10); };
"pow" =>{ EMIT_TOKEN(POW); };
"sqr" =>{ EMIT_TOKEN(SQR); };
"sqrt" =>{ EMIT_TOKEN(SQRT); };
"cbrt" =>{ EMIT_TOKEN(CBRT); };
"sin" =>{ EMIT_TOKEN(SIN); };
"cos" =>{ EMIT_TOKEN(COS); };
"tan" =>{ EMIT_TOKEN(TAN); };
"asin" =>{ EMIT_TOKEN(ASIN); };
"acos" =>{ EMIT_TOKEN(ACOS); };
"atan" =>{ EMIT_TOKEN(ATAN); };
"atan2" =>{ EMIT_TOKEN(ATAN2); };
"sinh" =>{ EMIT_TOKEN(SINH); };
"cosh" =>{ EMIT_TOKEN(COSH); };
"tanh" =>{ EMIT_TOKEN(TANH); };
"mag" =>{ EMIT_TOKEN(MAG); };
"magSqr" =>{ EMIT_TOKEN(MAGSQR); };
"pos" =>{ EMIT_TOKEN(POS); };
"neg" =>{ EMIT_TOKEN(NEG); };
"pos0" =>{ EMIT_TOKEN(POS0); };
"neg0" =>{ EMIT_TOKEN(NEG0); };
"sign" =>{ EMIT_TOKEN(SIGN); };
## Reductions, or other special functions
"min" =>{ EMIT_TOKEN(MIN); };
"max" =>{ EMIT_TOKEN(MAX); };
"average" =>{ EMIT_TOKEN(AVERAGE); };
"sum" =>{ EMIT_TOKEN(SUM); };
"weightAverage" =>{ EMIT_TOKEN(WEIGHT_AVERAGE); };
"weightSum" =>{ EMIT_TOKEN(WEIGHT_SUM); };
"rand" =>{ EMIT_TOKEN(RAND); };
## Types
"bool" =>{ EMIT_TOKEN(BOOL); };
"vector" =>{ EMIT_TOKEN(VECTOR); };
"tensor" =>{ EMIT_TOKEN(TENSOR); };
"symmTensor" =>{ EMIT_TOKEN(SYM_TENSOR); };
"sphericalTensor" =>{ EMIT_TOKEN(SPH_TENSOR); };
## Single value (constants, etc)
"Zero" =>{ EMIT_TOKEN(ZERO); };
"true" =>{ EMIT_TOKEN(LTRUE); };
"false" =>{ EMIT_TOKEN(LFALSE); };
"tensor::I" =>{ EMIT_TOKEN(UNIT_TENSOR); };
"time" =>{ EMIT_TOKEN(TIME); };
## Identifier (field, etc - error if unknown)
## Handle 'bare' names and single/double quoted ones
ident => emit_ident;
dquoted => emit_ident;
squoted => emit_ident;
space*;
*|;
}%%
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
Foam::expressions::patchExpr::scanner::~scanner()
{
if (parser_)
{
delete parser_;
}
}
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
bool Foam::expressions::patchExpr::scanner::dispatch_method
(
const parseDriver& driver_,
scanToken& scanTok,
word&& ident
) const
{
if (ident[0] == '.')
{
ident.erase(0, 1);
}
DebugInfo
<< "Method:" << ident
<< " at " << driver_.parsePosition() << nl;
const int methType = fieldMethodEnums.get(ident, -1);
if (methType > 0)
{
// Dispatch '.' and "method" separately
parser_->parse(TOK_DOT, nullptr);
parser_->parse(methType, nullptr);
return true;
}
driver_.reportFatal("Unknown method: " + ident);
return false;
}
bool Foam::expressions::patchExpr::scanner::dispatch_ident
(
const parseDriver& driver_,
scanToken& scanTok,
word&& ident
) const
{
int tokType = -1;
const bool quoted =
(
(ident.front() == '"' || ident.front() == '\'')
&& (ident.front() == ident.back())
);
if (quoted)
{
ident.erase(ident.size()-1);
ident.erase(0, 1);
}
else
{
// Check for function name
tokType = funcTokenEnums.get(ident, -1);
if (tokType > 0)
{
DebugInfo
<< "Emit:" << ident << " function:"
<< parser_->nameOfToken(tokType) << nl;
parser_->parse(tokType, nullptr);
return true;
}
#ifdef HAS_LOOKBEHIND_TOKENS
// Specials such "cset" also reset the look-behind
tokType = lookBehindTokenEnums.get(ident, -1);
if (tokType > 0)
{
DebugInfo
<< "Emit:" << ident << " as look-behind:"
<< parser_->nameOfToken(tokType) << nl;
driver_.resetStashedTokenId(tokType);
parser_->parse(tokType, nullptr);
return true;
}
#endif
}
// Can also peek at stashed "look-behind"
// const int lookBehind = driver_.stashedTokenId();
tokType = driverTokenType(driver_, ident);
if (tokType > 0)
{
DebugInfo
<< "Emit:" << ident << " token:"
<< parser_->nameOfToken(tokType) << nl;
scanTok.name = new Foam::word(std::move(ident));
parser_->parse(tokType, &scanTok);
return true;
}
// Not found? Attempt to strip off '.x' endings etc,
// but not when quoted
const auto dot = ident.rfind('.');
const int methType =
(
quoted || dot == std::string::npos
? -1
: fieldMethodEnums.get(ident.substr(dot+1), -1)
);
if
(
methType > 0
&& (tokType = driverTokenType(driver_, ident.substr(0, dot))) > 0
)
{
DebugInfo
<< "Emit:" << ident.substr(0, dot).c_str() << " token:"
<< parser_->nameOfToken(tokType) << " with "
<< ident.substr(dot).c_str() << " token:"
<< parser_->nameOfToken(methType) << nl;
// The field (before the ".")
ident.erase(dot);
scanTok.name = new Foam::word(std::move(ident));
parser_->parse(tokType, &scanTok);
// Dispatch '.' and "method" separately
parser_->parse(TOK_DOT, nullptr);
parser_->parse(methType, nullptr);
return true;
}
driver_.reportFatal
(
"Object " + ident + " does not exist or wrong type"
);
return false;
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
bool Foam::expressions::patchExpr::scanner::process
(
const std::string& str,
size_t strBeg,
size_t strLen,
parseDriver& driver_
)
{
// Save debug value
const int oldDebug = debug;
if (driver_.debugScanner())
{
debug |= 4;
}
if (!parser_)
{
parser_ = new parser();
}
driver_.content(str, strBeg, strLen);
size_t strEnd = str.length();
if (strBeg > str.length())
{
strBeg = str.length();
}
else if (strLen != std::string::npos)
{
strLen += strBeg;
if (strLen < str.length())
{
strEnd = strLen;
}
}
parser_->start(driver_);
// Scan token type
scanToken scanTok;
// Ragel token start/end (required naming)
const char* ts;
const char* te;
// Local buffer data.
// - p, pe, eof are required Ragel naming
// - buf is our own naming
const char* buf = &(str[strBeg]);
const char* eof = &(str[strEnd]);
const char* p = buf;
const char* pe = eof;
// Initialize FSM variables
%%{write init;}%% /* ^^^ FSM initialization here ^^^ */;
%%{write exec;}%% /* ^^^ FSM execution here ^^^ */;
if (%%{write error;}%% == cs)
{
driver_.reportFatal("Parse error while scanning", (p-buf));
}
if (p != eof)
{
driver_.reportFatal("Parsing failed with remaining content", (p-buf));
}
// Terminate parser execution
parser_->parse(0, nullptr);
parser_->stop();
// Restore debug value
debug = oldDebug;
return true;
}
// ************************************************************************* //