ALox  V. 2402 R. 0
Home ALox for C++ ALox for C# ALox for Java Download
Public Fields | Public Methods | Protected Types | Protected Fields | Protected Methods | Private Methods | List of all members
FormatterStdImpl Class Referenceabstract
Inheritance diagram for FormatterStdImpl:
[legend]
Collaboration diagram for FormatterStdImpl:
[legend]

Class Description


Base class for ALib built-in formatters. This class implements abstract method Formatter.format and introduces a set of new abstract methods that have to be implemented by descendants.

The documentation of the class is split into two sections: The first addresses users of descendent classes, the second provides information on how to extend this class to implement a custom formatter.

Documentation For Users Of Derived Classes

The following public fields may be modified with descendent types:

Documentation For Implementing Derived, Custom Formatters

Derived types need to set default values for attributes in fields DefaultNumberFormat and AlternativeNumberFormat within their constructor once - according to defaults specified by the formatting syntax. This should not be repeated per format operation. This way users of the type are allowed to change such default setting (even if they this may the formatter deviates from the standard it implements).

All fields of this class named with prefix pha (for example, phaAlignment) together comprise the set of formatting attributes which can be modified by placeholder semantics of the format string. If further attributes are needed, derived types are free to define custom members to store such attributes. Implementations provided with ALib give such extended attributes the prefix phaExt.

When parsing a placeholder of a format string, abstract method parsePlaceholder may set field phaFormatSpec to reflect a format-specific portion the placeholder string. If it does, it will be checked if the argument supports C# interface IFormattable and if so, interface method ToString(String, IFormatProvider) is invoked with this string as String parameter. In case the argument is of .Net-type DateTime, field

DateTimeFormatProvider is passed as second parameter.

Otherwise, the second parameter is left null.

If the argument does not support the interface, method parseStdFormatSpec is invoked to now parse this portion of the placeholder string in a default way.
This concept allows customized format specifications and customized implementations in a C# compatible way. As an example, a format specification for arguments of type DateTime supports a custom format string like "yyyy-MM-dd HH:mm:ss".

Note
This concept is implemented with class FormatterPythonStyle as the "Python format mini language" supports such custom format specifications. Class FormatterJavaStyle does not support this mechanism.

The following describes the formatting process in detail (the implementation of method format) and this way helps to understand what is required from the implementation of the abstract methods:

  1. A newline character check is made and formatting is aborted if one was found (as proposed by contract with parent class).
  2. Method parameters are stored in fields targetString, formatString, arguments and argOffset. This way, the parameters can be accessed from any implemented method without the need of passing them as parameters once more.
    In addition, field parser is initialized. This Substring is used to parse the format string. Parsed portions will be consumed from the front of the string. Finally fields argsConsumed and nextAutoIdx are initialized to value 0.
  3. Start of the loop to find and process placeholders in the format string.
  4. Abstract method findPlaceholder is invoked. If this fails (no further placeholder was found) parsing stops. If, and only if, a placeholder was found before, the rest of the string in parser is written and abstract method replaceEscapeSequences is invoked for this rest.
  5. The portion of the format string before the placeholder position is written and abstract method replaceEscapeSequences is invoked on this portion (if not empty).
  6. Method resetPHAs is invoked, to reset the attributes that will be parsed in the next step. The values that are set are implementation specific and need to reflect the default formatting options if no specific options are given in the format string.
  7. Abstract Method parsePlaceholder is invoked to parse and consume tokens from string parser and while doing this, to store the parsed format attributes in the fields with name prefix pha (or extended attributes of a derived formatter type).
    If an argument (positional) index is found during parsing, then method setArgument is to be invoked by abstract method parsePlaceholder providing that index.
    If the format syntax of the formatter contains a separated format specification string (a substring of the placeholder string), then the method may store such format substring in field phaFormatSpec.
  8. Next, it is checked if an argument was set by parsePlaceholder. If not, setArgument is invoked providing -1 for the index to indicate auto-indexing.
    Note
    If auto-indexing should be implemented differently than done with default method setArgument, then a custom formatter might either override the method or, in the case no index is given in the format string, just set fields phaArgument and phaArgumentIdx already in parsePlaceholder according to its own strategy
  9. Method preAndPostProcess is invoked with parameter startIdx equalling -1 (indicating pre-processing). This allows for example to insert tab fill-characters (tab stops) prior to writing the contents of the field.
  10. Method writeCustomFormat is invoked. This allows derived formatters to write arguments in a custom way. If the method returns true, the loop is continued ( → Step 4.).
    The default implementation checks if a format specification was stored in phaFormatSpec" and if yes, if C# interface IFormattable in implemented for phaArgument. If this is true, the interface is invoked and true is returned.
  11. Again, if a format specification was stored in phaFormatSpec method parseStdFormatSpec is invoked which needs to set further attributes in the Placeholder object according to to the standard format specification of the formatter.
  12. Now, as all fields that represent formatting attributes (fields with prefix pha) are well set (or kept with their defaulted value), method checkStdFieldAgainstArgument is invoked. This method is virtual but not abstract. Its default implementation checks the placeholder attributes against the provided argument type and raises an error if the argument does not fit to the placeholder format specification.
  13. Method writeStdArgument is invoked. This method is virtual but not abstract. Its default implementation writes the argument value formatted according to the attribute fields.
  14. Finally preAndPostProcess is invoked with parameter startIdx pointing to the first character in targetString of the argument written. Here, actions like case conversion might be done on the field written.
    1. End of loop ( → Step 4.)

Public Fields

NumberFormat AlternativeNumberFormat = new NumberFormat()
 
DateTimeFormatInfo DateTimeFormatProvider = DateTimeFormatInfo.InvariantInfo
 
NumberFormat DefaultNumberFormat = new NumberFormat()
 
bool WriteALibErrorReports = true
 
bool WriteErrorsToTargetString = true
 
- Public Fields inherited from Formatter
Formatter Next
 

Public Methods

 FormatterStdImpl (String formatterClassName)
 
virtual void CloneSettings (FormatterStdImpl reference)
 
- Public Methods inherited from Formatter
virtual void Format (AString target, List< Object > args)
 
virtual void Format (AString target, params Object[] args)
 
virtual void Reset ()
 

Protected Types

enum  PHType {
  NotGiven, String, Character, IntBase10,
  IntBinary, IntOctal, IntHex, Float,
  Bool, HashCode, Fill
}
 

Protected Fields

int argOffset
 
int argsConsumed
 
List< Object > arguments
 
AString fieldBuffer = new AString()
 
Substring formatString = new Substring()
 
String formatterName
 
int nextAutoIdx
 
Substring parser = new Substring()
 
Alignment phaAlignment
 
bool phaAlignmentSpecified
 
Object phaArgument
 
int phaArgumentIdx
 
int phaCutContent
 
char phaFillChar
 
Substring phaFormatSpec = new Substring()
 
bool phaIsPercentage
 
NumberFormat phaNF = new NumberFormat()
 
int phaPreviousArgumentIdx
 
bool phaSignPaddingMode
 
PHType phaType
 
char phaTypeCode
 
int phaWidth
 
bool phaWriteBinOctHexPrefix
 
AString targetString
 
int targetStringStartLength
 
- Protected Fields inherited from Formatter
List< Object > boxes
 
Substring lamFormatString = new Substring()
 

Protected Methods

virtual bool checkStdFieldAgainstArgument ()
 
virtual void errorFormatString (String msg)
 
abstract int findPlaceholder ()
 
override int format (AString targetString, Substring formatString, List< Object > arguments, int argOffset)
 
abstract bool parsePlaceholder ()
 
abstract bool parseStdFormatSpec ()
 
virtual bool preAndPostProcess (int startIdx, AString target=null)
 
abstract void replaceEscapeSequences (int startIdx)
 
virtual void resetPHAs ()
 
virtual bool setArgument (int pos, bool countStartsWith_1)
 
virtual bool writeCustomFormat ()
 
virtual void writeStdArgument ()
 
- Protected Methods inherited from Formatter
virtual void initializeFormat ()
 

Private Methods

long getSIntegral ()
 
ulong getUIntegral ()
 
bool isSIntegral ()
 
bool isUIntegral ()
 

Additional Inherited Members

- Public Static Methods inherited from Formatter
static Formatter AcquireDefault ()
 
static void ReleaseDefault ()
 
- Protected Static Fields inherited from Formatter
static Formatter defaultFormatter
 
static ThreadLock defaultFormatterLock = new ThreadLock()
 

Member Enumeration Documentation

◆ PHType

enum PHType
strongprotected

Denotes the requested value type of placeholders.

Enumerator
NotGiven 

The default.

String 

String type requested

Character 

Converts a given character or integer number to the corresponding unicode character before printing.

IntBase10 

Outputs a given number in base 10. The default.

IntBinary 

Outputs a given number in base 2.

IntOctal 

Outputs a given number in base 8.

IntHex 

Outputs a given number in base 16.

Float 

Outputs a number in floating point format.

Bool 

Writes "true" or "false".

HashCode 

Writes raw box data as hex.

Fill 

Writes phaFillChar x-times. Used with python-style conversion {!Fill[C]}

Constructor & Destructor Documentation

◆ FormatterStdImpl()

FormatterStdImpl ( String  formatterClassName)
inline

Constructor.

Parameters
formatterClassNameThe name of the derived class. Used to generate error messages including a link into the online documentation. (Therefor has to be the exact name.

Member Function Documentation

◆ checkStdFieldAgainstArgument()

virtual bool checkStdFieldAgainstArgument ( )
inlineprotectedvirtual

Virtual method invoked after parseStdFormatSpec and before writeStdArgument(). The default implementation checks the settings of placeholder attribute values (fields with prefix pha), which were set by parsePlaceholder and optionally by parseStdFormatSpec, against the type of the argument given.

If type and format information is missing in the format string, reasonable default values are set depending on the type of the argument.

If the argument type contradicts the replacement field type, errorFormatString is invoked.

Returns
true if OK, false if replacement should be aborted.

Reimplemented in FormatterPythonStyle, and FormatterJavaStyle.

◆ CloneSettings()

virtual void CloneSettings ( FormatterStdImpl  reference)
inlinevirtual

Clones the settings from the given formatter.

Parameters
referenceThe formatter to copy settings from.

◆ errorFormatString()

virtual void errorFormatString ( String  msg)
inlineprotectedvirtual

Helper method (overridable) that optionally

This method can (and should) be invoked by descendent types in case of format string syntax errors, argument index errors, etc.

Parameters
msgThe error message.

◆ findPlaceholder()

abstract int findPlaceholder ( )
protectedpure virtual

Abstract method to search the next index of an argument placeholder in the remaining substring (field parser) of the format string.

Returns
The index found, -1 if not found.

Implemented in FormatterPythonStyle, and FormatterJavaStyle.

◆ format()

override int format ( AString  targetString,
Substring  formatString,
List< Object >  arguments,
int  argOffset 
)
inlineprotectedvirtual

Implemented abstract format method which invokes a set of new abstract methods as described in the main documentation of this class.

Parameters
targetStringAn AString that takes the result.
formatStringThe format string.
argumentsThe objects to convert.
argOffsetThe first object in arguments to use.
Returns
The number of args consumed.

Implements Formatter.

◆ getSIntegral()

long getSIntegral ( )
inlineprivate

Extracts a signed integral value from phaArgument. Must be used only if isSIntegral returned true.

Returns
The contents of phaArgument casted as long.

◆ getUIntegral()

ulong getUIntegral ( )
inlineprivate

Extracts an unsigned integral value from phaArgument. Must be used only if isUIntegral returned true.

Returns
The contents of phaArgument casted as ulong.

◆ isSIntegral()

bool isSIntegral ( )
inlineprivate

Helper method to detect if phaArgument holds a signed integral type.

Returns
true if phaArgument holds a signed integral type.

◆ isUIntegral()

bool isUIntegral ( )
inlineprivate

Helper method to detect if phaArgument holds an unsigned integral type.

Returns
true if phaArgument holds an unsigned integral type.

◆ parsePlaceholder()

abstract bool parsePlaceholder ( )
protectedpure virtual

Abstract method to parse the format definition at the start of string parser and set the placeholder attributes accordingly.
Field phaFormatSpec might be set by this method to portion of the placeholder format string. If so, methods writeCustomFormat and parseStdFormatSpec are used to then parse this portion of the placeholder string.

Returns
true on success, false on errors.

Implemented in FormatterPythonStyle, and FormatterJavaStyle.

◆ parseStdFormatSpec()

abstract bool parseStdFormatSpec ( )
protectedpure virtual

Abstract method to parse the format specification for standard types (those that are not processed by writeCustomFormat). This method may be left empty (just return constant true) if method parsePlaceholder will never sets field phaFormatSpec.

Returns
true on success, false on errors.

Implemented in FormatterPythonStyle, and FormatterJavaStyle.

◆ preAndPostProcess()

virtual bool preAndPostProcess ( int  startIdx,
AString  target = null 
)
inlineprotectedvirtual

Virtual method to do pre- and post- processing of the field written. Pre-processing could for example be adding tabulator spaces, letter case conversions,

A negative given index startIdx indicates the pre-processing phase. If target is given, this indicates an "intermediate phase": The argument has been written, but no alignment or cutting has been done, yet. This phase should usually be ignored, but is for example important for search and replacement actions. If a field has a custom format implementation (e.g. time and date values), then the intermediate phase is never called.

Note
The reason why this method is not implemented as two different ones is that derived classes might do some more complicated parsing of parts of the placeholder string in this method. In this case, the parsing is needed to be implemented only once, while the finally parsed commands are only conditionally executed depending if executed as pre or post phase.
Parameters
startIdxIf -1 pre-processing is indicated, otherwise post-processing and the index of the start of the field written in targetString is given.
targetThe target string, only if different from field targetString, which indicates intermediate phase.
Returns
false, if the placeholder should be skipped (nothing is written for it). true otherwise.

Reimplemented in FormatterPythonStyle, and FormatterJavaStyle.

◆ replaceEscapeSequences()

abstract void replaceEscapeSequences ( int  startIdx)
protectedpure virtual

Replace "escaped" placeholder field characters. For example these are "{{" in python style or "%%" in JAVA style.
In addition other escape sequences defined with the format are to be replaced with this method.

Parameters
startIdxThe start of the region to replace

Implemented in FormatterPythonStyle, and FormatterJavaStyle.

◆ resetPHAs()

virtual void resetPHAs ( )
inlineprotectedvirtual

Overridable method to clean and reset the fields representing the current placeholder attributes (those with name prefix pha) prior to parsing them.

The default implementation sets all pha-fields as documented per field.

Note
Derived classes (aka the specific formatter classes) are to invoke this (parent) implementation first and then to make some own adjustments to meet the defaults that apply to the formatting specification implemented by the derived class and - if this applies - also to reset extended attributes of the derived formatter type.

Reimplemented in FormatterPythonStyle, and FormatterJavaStyle.

◆ setArgument()

virtual bool setArgument ( int  pos,
bool  countStartsWith_1 
)
inlineprotectedvirtual

Helper method (overridable) that usually is invoked by implementation of parsePlaceholder when an argument index is read from the format string,

If this does not happen, method format will invoke this method providing -1 for value of parameter pos to automatically choose the next argument.

Consequently, this method sets the fields Argument and ArgumentIdx in given field. For auto-values, it increments nextAutoIdx. Finally, this method is responsible for the correct book-keeping of argsConsumed.

Parameters
posThe index of the argument. If -1 is given, the index is auto-incremented using field nextAutoIdx.
countStartsWith_1If true, given pos is counting arguments with 1 being the first. Otherwise with 0.
Returns
true on success, false on errors.

◆ writeCustomFormat()

virtual bool writeCustomFormat ( )
inlineprotectedvirtual

Virtual method that may write an argument using a custom method/format. The default implementation checks if phaFormatSpec is set and object phaArgument supports an own format specifier by providing C# interface IFormattable. If so, the result of the formatting is written directly into the targetString and true is returned which causes method format (which invokes this method) to continue with the next replacement field. If false is returned, method format continues the field processing by invoking parseStdFormatSpec, checkStdFieldAgainstArgument and writeStdArgument.

Returns
true if phaArgument was written, false otherwise.

◆ writeStdArgument()

virtual void writeStdArgument ( )
inlineprotectedvirtual

Virtual method to write the argument. The default implementation should be sufficient for most derived formatter implementations, but of-course can be overridden and extended.

Member Data Documentation

◆ AlternativeNumberFormat

NumberFormat AlternativeNumberFormat = new NumberFormat()

This number format is used to store alternative attributes. Likewise DefaultNumberFormat, it is never used directly for formatting. Instead when processing the placeholder syntax, alternatives get copied from either this object or from DefaultNumberFormat.

This object is initialized in the constructor (of descendants) once to meet the formatting defaults of the corresponding specification.

Not all fields in this object are used. The ones used are:

◆ argOffset

int argOffset
protected

The offset of the first argument to use. Provided with method Format.

◆ argsConsumed

int argsConsumed
protected

The number of arguments consumed by the current format string.

◆ arguments

List<Object> arguments
protected

The list of arguments provided with method Format.

◆ DateTimeFormatProvider

DateTimeFormatInfo DateTimeFormatProvider = DateTimeFormatInfo.InvariantInfo

The iFormatProvider used to format objects of .Net-type DateTime. By default, this is set to DateTimeFormatInfo.InvariantInfo. To have date and time values respect the current locale, this object can be changed to DateTimeFormatInfo.CurrentInfo.

◆ DefaultNumberFormat

NumberFormat DefaultNumberFormat = new NumberFormat()

This number format is used to store default attributes for formatting numbers. Likewise AlternativeNumberFormat, it is never used directly for formatting. Instead, at the beginning of parsing a next placeholder field, values are copied to phaNF. During the parsing process, values are then modified only in phaNF, probably taken from AlternativeNumberFormat.

This object is initialized in the constructor (of descendants) once to meet the formatting defaults of the corresponding specification.

Note
Changing attribute values of this object allows to change the default formatting options of numbers!

◆ fieldBuffer

AString fieldBuffer = new AString()
protected

A buffer to be used when writing aligned fields.

◆ formatString

Substring formatString = new Substring()
protected

The format string as provided with method Format.

◆ formatterName

String formatterName
protected

The name of the formatter as provided in the constructor. Used for generating error messages.

◆ nextAutoIdx

int nextAutoIdx
protected

Counter for auto-indexed arguments.

◆ parser

Substring parser = new Substring()
protected

The current (remaining) format string.

◆ phaAlignment

Alignment phaAlignment
protected

The alignment of the contents within a field. This is set to Alignment.Left in default implementation of resetPHAs.

◆ phaAlignmentSpecified

bool phaAlignmentSpecified
protected

If true, an alignment was explicitly specified. This is set to false in default implementation of resetPHAs.

◆ phaArgument

Object phaArgument
protected

The current Box. This is set by parsePlaceholder if explicit indexing is used. Otherwise by format which invokes setArgument if parsePlaceholder did not set it yet. Set to null in default implementation of resetPHAs.

◆ phaArgumentIdx

int phaArgumentIdx
protected

The positional index of the current phaArgument. This is set by parsePlaceholder if explicit indexing is used. Otherwise by format which invokes setArgument if parsePlaceholder did not set it yet. Set to -1 in default implementation of resetPHAs.

◆ phaCutContent

int phaCutContent
protected

If not negative, the string representation of the argument is cut prior to applying any field operation. It could be also named "precision", hence the number of characters to show - even if the field will be wider. This is set to -1 in default implementation of resetPHAs.

◆ phaFillChar

char phaFillChar
protected

The filling character for fields that are larger than their content. Method resetPHAs will set this to ' '.

◆ phaFormatSpec

Substring phaFormatSpec = new Substring()
protected

The portion of the replacement field that represents the format specification. This field might be set in method parsePlaceholder and consumed in methods writeCustomFormat and parseStdFormatSpec.
This field is nulled in default implementation of resetPHAs.

◆ phaIsPercentage

bool phaIsPercentage
protected

Can be true for float-types. If true, the value is multiplied with 100 and a percentage symbol '%' is printed after the value. Set to false in default implementation of resetPHAs.

◆ phaNF

NumberFormat phaNF = new NumberFormat()
protected

The number format object for the actual attribute. With method resetPHAs values found in object DefaultNumberFormat will be copied into this.

◆ phaPreviousArgumentIdx

int phaPreviousArgumentIdx
protected

The index of the previous argument. Used when addressing previous argument number (eg. in Java formatting style this could be "%<$..."). This is set to phaArgumentIdx in default implementation of resetPHAs.

◆ phaSignPaddingMode

bool phaSignPaddingMode
protected

Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120'. This alignment option is only valid for numeric types. Set to false in default implementation of resetPHAs.

◆ phaType

PHType phaType
protected

The type of the attribute as specified in the placeholder. This is set to PHType.NotGiven in default implementation of resetPHAs.

◆ phaTypeCode

char phaTypeCode
protected

This is the (format specific) type code of the current format operation. Used only to display error messages. May be used differently in derived classes. Is nulled in default implementation of resetPHAs.

◆ phaWidth

int phaWidth
protected

The (minimum) width of the output. This is set to 0 in default implementation of resetPHAs.

◆ phaWriteBinOctHexPrefix

bool phaWriteBinOctHexPrefix
protected

Used with binary, octal, or hexadecimal output. Specifies that the output will be prefixed by strings found in fields BinLiteralPrefix, HexLiteralPrefix or OctLiteralPrefix which default to "0b", "0o" and "0x". Set to false in default implementation of resetPHAs.

◆ targetString

AString targetString
protected

The target string as provided with method Format.

◆ targetStringStartLength

int targetStringStartLength
protected

The length of the target string before adding the formatted contents.

◆ WriteALibErrorReports

bool WriteALibErrorReports = true

Flag that causes the creation of ALib error reports on format syntax errors, argument type errors, etc. Defaults to true. (Ignored in release compilations. see class Report for more information.)

◆ WriteErrorsToTargetString

bool WriteErrorsToTargetString = true

Flag that causes error messages to be written into the target string. Defaults to true.


The documentation for this class was generated from the following file: