Skip to content

WIP: Refactor IAST::FormatSettings - #45649

Closed
murfel wants to merge 94 commits into
ClickHouse:masterfrom
murfel:formatimpl-refactoring
Closed

murfel wants to merge 94 commits into
ClickHouse:masterfrom
murfel:formatimpl-refactoring

Conversation

@murfel

@murfel murfel commented Jan 26, 2023 •

Copy link
Copy Markdown
Contributor

Template

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):

IAST::FormatSettings refactoring to encapsulate its fields. Now proper API added to be used mostly within IAST::formatImpl, primarily used for clickhouse-format.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Information about CI checks: https://clickhouse.com/docs/en/development/continuous-integration/

My comments

#45534

This PR will consist of several commits, each commit will encapsulate one field at a time. Each commit is supposed to keep the build stable.

Accidentally fixed issues

  1. show_secrets was missed in semi-copy-ctor - c0bcf98
  2. ~10 hiliting issues that I've found while refactoring clickhouse-format doesn't hilite some identifiers #45668

@murfel
murfel marked this pull request as draft January 26, 2023 10:49
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-improvement Pull request with some product improvements label Jan 26, 2023
@KochetovNicolai KochetovNicolai added the can be tested Allows running workflows for external contributors label Jan 26, 2023
@vitlibar vitlibar self-assigned this Jan 30, 2023
- hilite matching bracket
- remove accidentally added space
- remove unused field in Hiliter
Comment thread src/Parsers/IAST.h Resolved
@murfel

murfel commented Mar 10, 2023 •

Copy link
Copy Markdown
Contributor Author

I have started implementing merging the FormatSettings, FormatState, and FormatStateStacked together, and now have a couple of questions.

(still relevant) 1. API design. In IAST.h there are two functions, format and formatImpl. At first glance, format creates FormatState and calls formatImpl, and each implementation of formatImpl calls formatImpl on its children.

void format(const FormatSettings & settings) const
{
    FormatState state;
    formatImpl(settings, state, FormatStateStacked());
}

virtual void formatImpl(const FormatSettings & /*settings*/, FormatState & /*state*/, FormatStateStacked /*frame*/) const
{
    throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown element in AST: {}", getID());
}

However, there are about ~30 cases when formatImpl calls format, resetting the FormatState. E.g.
https://github.com/ClickHouse/ClickHouse/blob/master/src/Parsers/Access/ASTSettingsProfileElement.cpp#L101

a) Why do these usages need a blank state? I don't need to know that to recreate the behavior, I'm just curious to have an extra context behind this just in case.

b) Since we're incapsulating FormatSettings, FormatState, and FormatStateStacked into a new Formatter class, both format and formatImpl will have the same argument -- Formatter. It's now up to the user to pass a Formatter with a reset state. Thus we will only need one function, format. Please confirm if my understanding of the need for format and formatImpl is correct and if I could do that without causing something else to break.

Just clarifying - in your suggested snipped above there's no longer a need to expose neither FormatState, nor FormatStateStacked:

    void format(WriteBuffer & out, const FormatSettings & settings) const
    {
        FormatState state;  // no need to expose it here, let's create it within Formatter
        formatImpl(Formatter{out, settings, state});
    }
    
    virtual void formatImpl(const Formatter & formatter) const;

UPD On second thought, here are the benefits of keeping both methods:
c) format could also be used by external users only, and formatIml -- by internal methods, i.e. from other nodes' formatImpl, thus we need to make formatImpl private/protected.

d) We could also decide to hide Formatter for external users, only exposing WriteBuffer and FormatSettings. Then format comes in handy.

(more like not relevant, I made a decision to pass Formatter by const &) 2. C++ / API design.

My API aspirations for the Formatter class are to delete all its copy/move c-tors/assignment operators and provide several methods for creating a copy of the Formatter, e.g. Formatter copy(); to copy with a blank state, Formatter copyWithIndent(int); to copy with a specific indent set. All these copy methods will be based on the current usage.

The benefit of this approach compared with just copy-constructors is that you can have this:

void formatImpl(Formatter & out) {
...
    type->formatImpl(out.copyWithIndent(0));
...
}

Instead of this:

void formatImpl(Formatter & out) {
...
    Formatter stacked_formatter(out);
    stacked_formatter.setIndent(0);
    type->formatImpl(stacked_formatter);
...
}

(Adapted from https://github.com/ClickHouse/ClickHouse/blob/master/src/Parsers/ASTColumnDeclaration.cpp#L70)

However, since formatImpl takes Formatter by reference, it cannot bind to the temporary value of the copied Formatter in the first snipped.

Solution 1. Create a local variable to store a copy of Formatter, then pass it into formatImpl -- it requires an extra line of code which I was trying to avoid in the first place.

Formatter stacked_formatter = out.copyWithIndent(0);
type->format_impl(stacked_formatter);

Solution 2. Make format_impl accept std::unique_ptr<Formatter> -- this will create an extra unnecessary code at each call.

void formatImpl(std::unique_ptr<Formatter> out) {
    ...
    type->format_impl(out->copyWithIndent(0));
    ...
}

(Errr, this is not precisely correct, but should be enough as an idea.)

This solution is just as morally wrong as solution 3.

Solution 3. I could just take it by r-value reference in formatImpl, but it would be morally wrong, as Formatter keeps references to WriteBuffer, FormatSettings, and FormatState, and this r-value object shouldn't be possibly able to live longer than the life of the stack that it was created on.

(Preferred by me) Solution 4. Make Formatter a const reference in formatImpl, this will require making all the internal fields references. Specifically, all the fields of FormatStateStacked. This is bad because it is an intentional confusion of the reader, as we do very much 'modify' Formatter through its references, and having references in classes, in general, is just such a mislead. However, I would prefer this solution, as it creates a more concise code in the usage.

Just to be clear, the Formatter class would look like this:

class Formatter
{
    WriteBuffer & ostr;
    const FormatSettings & settings;
    std::shared_ptr<FormatState> state = std::make_shared<FormatState>();
    std::unique_ptr<FormatStateStacked> stacked_state = std::make_unique<FormatStateStacked>();
    ...
}

(I kept the FormatStateStacked as a separate class, instead of ingesting its fields into Formatter for ease for now. We could discuss it later, it shouldn't be too much code change to go from one way to the other.)

murfel added 10 commits March 11, 2023 08:25
- Encapsulates FormatSettings, FormatState, FormatStateStacked
- Change IAST.format and IAST.formatImpl signatures
- 7/450 usages fixed (grep -rn "formatImpl") with dependencies
- Committed files pass static checks
- Here all formatImpl overrides call a format* function within itself with just the FormatSettings argument, without the FormatState and FormatStateStacked. We need to make sure we pass a copy of the FormattingBuffer, to erase the state.
- TODO(me): check possible behaviour change, since we're keeping FormatState in the FormattingBuffer copy. I.e. check that those format*(FormatSettings) functions do not use or modify FormatState members.
- out.copy() (possibly?) needed when calling other format* methods w/o state
@murfel

murfel commented Mar 13, 2023 •

Copy link
Copy Markdown
Contributor Author

TODO:
Decisions needed:

  • decide on the IAST::format signature
  • FormattingBuffer
    • decide what copy*() should copy - FormatSettings always, FormatState? FormatStateStacked?
    • re-design copy*() and setters/getters

No decisions needed:

@murfel

murfel commented Mar 13, 2023 •

Copy link
Copy Markdown
Contributor Author

TODO: modify my code according to this description. My last few commits are wrong!

Squashing FormatSettings, FormatState, and FormatStateStacked into FormattingBuffer

This comment explores how different methods would be affected.

formatImpl - copy FormatStateStacked

NB: When I say formatImpl I mean all format*(const FormatSettings &, FormatState &, FormatStateStacked) methods that substitute formatImpl, e.g. formatLimit and formatQueryImpl here:
https://github.com/ClickHouse/ClickHouse/blob/master/src/Parsers/ASTShowTablesQuery.h#L46
https://github.com/ClickHouse/ClickHouse/blob/master/src/Parsers/ASTQueryWithOutput.h#L34

There are two main formatting functions:

void format(const FormatSettings & settings) const
{
    FormatState state;
    formatImpl(settings, state, FormatStateStacked());
}

virtual void formatImpl(const FormatSettings &, FormatState &, FormatStateStacked) const;

The main way for something to be formatted is to call formatImpl on the root of a tree, and it will call formatImpl on its successors. Most of the time, formatImpl would pass the same arguments that it has received to its successors, where FormatStateStacked will be copied.

Copying FormatStateStacked was a nice trick to apply some settings to format a child's node and preserve the original settings once the recursion is back from the child. I.e. increasing indent for a child's node.

After this change, there's only one argument to formatImpl:

class FormattingBuffer {
    const FormatSettings & settings;
    const FormatState & state;
    FormatStateStacked stacked_state;
};

virtual void formatImpl(const FormattingBuffer &) const;

Thus, to imitate the behavior of copying FormatStateStacked when passed to formatImpl, we create a copy() method which returns a new FormattingBuffer with a copy of the existing FormatStateStacked and the references to FormatSettings and FormatState preserved.

formatImpl - copy modified FormatStateStacked

In some cases, formatImpl will call other formatImpl with the copy of the existing FormatStateStacked, but slightly modified. For such cases, we add copy*(*) methods which copy the existing FormatStateStacked and apply the new settings.

Example:
https://github.com/ClickHouse/ClickHouse/blob/master/src/Parsers/ASTColumnDeclaration.cpp#L70

format

When I say format, I mean all format*(const FormatSettings &) methods that substitute IAST::format, e.g. formatLike
https://github.com/ClickHouse/ClickHouse/blob/master/src/Parsers/ASTShowTablesQuery.h#L45

In such calls, we need to pass a copy of FormattingBuffer with both empty states, i.e. preserving the const reference to FormatSettings only.

TODO: An interesting thing to explore (and the only decision-making point in this modification) is whether these format methods create their own states which they later pass to their children. If not, we can avoid making a copy of FormattingBuffer at all and pass it as is. It would later be useful e.g. for the limit line length issue since we'll need to add a current_line_length field which we'll store in FormatState.

@murfel

murfel commented Mar 13, 2023 •

Copy link
Copy Markdown
Contributor Author

Testing

I'm going to do some regression tests - take all *.SQL test, run old and new clickhouse-format on them, and compare that the output didn't change.

There's a caveat -- I've found a few small bugs in formatting, that I need to fix in a separate PR before doing the test.
#45668

Also, I'll need to implement a 'hiliting bytes merger' to cancel out some hiliting bytes.

E.g. if there were a line like this
s.ostr << hilite_function << name << "(" << hilite_none, I changed it into two writeFunction calls: s.writeFunction(name); s.writeFunction("("), which translates into s.ostr << hilite_function << name << hilite_none << hilite_function << "(" << hilite_none. The two middle hilite_non and hilite_function should be canceled out for the old and new outputs to match.

murfel added 2 commits March 13, 2023 14:09
# Conflicts:
#	src/Parsers/ASTColumnsTransformers.cpp
#	src/Parsers/ASTConstraintDeclaration.h
#	src/Parsers/ASTCreateQuery.cpp
#	src/Parsers/ASTCreateQuery.h
#	src/Parsers/ASTDeleteQuery.cpp
#	src/Parsers/ASTDictionary.h
#	src/Parsers/ASTFunction.cpp
#	src/Parsers/ASTIndexDeclaration.h
#	src/Parsers/ASTProjectionDeclaration.h
#	src/Parsers/ASTRenameQuery.h
#	src/Parsers/ASTSelectQuery.cpp
#	src/Parsers/ASTSetQuery.cpp
#	src/Parsers/ASTTableOverrides.h
#	src/Parsers/Access/ASTSetRoleQuery.h
#	src/Parsers/Access/ASTShowGrantsQuery.h
#	src/Parsers/IAST.h
@vitlibar

vitlibar commented Apr 7, 2023 •

Copy link
Copy Markdown
Member

Too many hiliting sequences. For example, let's consider the query SHOW TABLES. Now with your changes it's displayed as

\u001b[1m (hilite_keyword)
SHOW
\u001b[0m (hilite_none)

\u001b[1m (hilite_keyword)
\u001b[0m (hilite_none)

\u001b[1m (hilite_keyword)
TABLES
\u001b[0m (hilite_none)

And before your changes it was just

\u001b[1m (hilite_keyword)
SHOW TABLES
\u001b[0m (hilite_none)

The test 02105_backslash_letter_commands failed because of that.

Comment thread src/Parsers/IAST.cpp
void IAST::FormattingBuffer::writePossiblyHilited(std::string_view str, const char * hilite_type) const
{
Hiliter hiliter = createHiliter(hilite_type);
ostr << str;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A possible optimization: instead of writing a closing hiliter in ~Hiliter FormattingBuffer can remember the last opening hiliter and check it with next output. For example, if you have a sequence of writeKeyword() it would allow to write only one hilite_keyword and only one hilite_none.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking about but introducing a state machine would complicate the logic for no gain, as there's no need for the optimisation of hilite. There are so many public methods which will need to flush the buffer.

And if anyone ever goes back to implementing the original task of limiting line length, then it will become even more complicated, as it will probably need a state machine of its own.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And if anyone ever goes back to implementing the original task of limiting line length, then it will become even more complicated, as it will probably need a state machine of its own.

What is the original task?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In regard to #38317 I still don't see why it's better to format

\u001b[1mSHOW \u001b[0m\u001b[1m\u001b[0m\u001b[1mTABLES\u001b[0m

instead of

\u001b[1mSHOW TABLES\u001b[0m

In order to limit the length of a line the characters must be counted without hilite sequences anyway, I suppose. So FormattingBuffer needs to memorize the current number of characters in the current line. And I don't think there is a lot of difference here between memorizing one or two variables.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel like it's a premature optimisation. It doesn't affect performance, it only complicates the code logic.

I agree that squashing hilites together does improve readability for debugging, though. But it's a very abstract scenario.

However, I just realised that implementing squashing might over-complicate the whole PR. Earlier we agreed that I'll encapsulate FormattingBuffer.ostr in a separate PR because it affects ~1000 lines.

To summarize, here are pros for squashing hilites:

  • easier readability for debugging
  • XX% fewer bytes per hilited query (but does anyone care?)

Cons:

  • complicates the code (additional state machine)
  • complicates the PR (encapsulating ostr here)
  • I'll need to write more code instead of keeping everything as is :)

The question is, do you feel like the pros outweigh the cons? I'm honestly not very excited to write even more code at this point, and I feel like just merging this PR as is would already bring value.

@vitlibar vitlibar Jul 28, 2023 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

complicates the PR (encapsulating ostr here)

We can encapsulate ostr in a half-way manner:

class FormattingBuffer
{
public:
    ~FormattingBuffer() { setHilite(hilite_none); }

    WriteBuffer & out() { setHilite(hilite_none); return ostr; }

    void writeKeyword(std::string_view str) const
    {
        if (keyword.empty())
            return;
        setHilite(hilite_keyword);
        ostr << str;
    }

private:
    WriteBuffer & ostr;
    ...
};

and all will need to do is to mechanically replace every .ostr with .out(). It doesn't seem like a difficult task.

I feel like it's a premature optimisation. It doesn't affect performance, it only complicates the code logic.

I'm not 100% sure about performance, but anyway. We format ASTs very often, it's not like one-time task. So it would be nice to be accurate with that.

@@ -1 +0,0 @@
CREATE USER user IDENTIFIED WITH plaintext_password BY 'hello'

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's restore this test. Later we can think about removing it but currently it's better to see the changes in hiliting this PR makes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not exactly the same, so I think it's better to keep both tests for now.

Comment thread src/Parsers/IAST.h
void nlOrWs() const; // Write newline or whitespace.
void nlOrNothing() const;

void writeSecret(const String & secret = "") const;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use std::string_view for such arguments always in this class where it doesn't cause troubles.

@vitlibar

vitlibar commented Jul 28, 2023 •

Copy link
Copy Markdown
Member

For example, let's consider the query SHOW TABLES. Now with your changes it's displayed as

\u001b[1m (hilite_keyword)
SHOW
\u001b[0m (hilite_none)

\u001b[1m (hilite_keyword)
\u001b[0m (hilite_none)

\u001b[1m (hilite_keyword)
TABLES
\u001b[0m (hilite_none)

And before your changes it was just

\u001b[1m (hilite_keyword)
SHOW TABLES
\u001b[0m (hilite_none)

Here I just tried to make my comment more readable, the test's output was like

\u001b[1mSHOW \u001b[0m\u001b[1m\u001b[0m\u001b[1mTABLES\u001b[0m

@alexey-milovidov

Copy link
Copy Markdown
Member

@vitlibar This is a good pull request, and we need it.

@vitlibar

vitlibar commented Oct 9, 2023

Copy link
Copy Markdown
Member

@vitlibar This is a good pull request, and we need it.

Ok, I'll do rebasing of the PR and maybe also correct it a little bit.

@murfel

murfel commented Oct 9, 2023 •

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov @vitlibar I'd like to finish it myself, I'll get reactivated and finish it up :)

@vitlibar I'll do the hilite squishing, as you insist.

@murfel

murfel commented Apr 29, 2024

Copy link
Copy Markdown
Contributor Author

@vitlibar This is a good pull request, and we need it.

Ok, I'll do rebasing of the PR and maybe also correct it a little bit.

Seems like I won't be working on this after all, @vitlibar feel free to grab this.

@alexey-milovidov

Copy link
Copy Markdown
Member

Thank you! I will be very happy to have this merged.

@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2024

Copy link
Copy Markdown
Contributor

Dear @murfel, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

@vitlibar

vitlibar commented Jul 2, 2024

Copy link
Copy Markdown
Member

Dear @murfel, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

I'll continue working on this PR.

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2024

Copy link
Copy Markdown
Contributor

Dear @murfel, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

@alexey-milovidov

Copy link
Copy Markdown
Member

We need this!

@vitlibar

vitlibar commented Dec 3, 2024 •

Copy link
Copy Markdown
Member

I'll split this PR into parts and merge them one by one:
part 1
part 2

vitlibar added a commit to vitlibar/ClickHouse that referenced this pull request Dec 12, 2024
vitlibar added a commit to vitlibar/ClickHouse that referenced this pull request Dec 13, 2024
@rschu1ze

Copy link
Copy Markdown
Member

Done in #72723 and #73163.

@rschu1ze rschu1ze closed this Jan 16, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants