blob: d7e1f263c562c4ce9979decdd7b351f0db70e44c [file] [log] [blame]
Daniel Jasper0df50932014-12-10 19:00:42 +00001//===--- UnwrappedLineFormatter.h - Format C++ code -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief Implements a combinartorial exploration of all the different
12/// linebreaks unwrapped lines can be formatted in.
13///
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEFORMATTER_H
17#define LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEFORMATTER_H
18
19#include "ContinuationIndenter.h"
20#include "clang/Format/Format.h"
21#include <map>
22#include <queue>
23#include <string>
24
25namespace clang {
26namespace format {
27
28class ContinuationIndenter;
29class WhitespaceManager;
30
31class UnwrappedLineFormatter {
32public:
33 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
34 WhitespaceManager *Whitespaces,
Nico Weberfac23712015-02-04 15:26:27 +000035 const FormatStyle &Style,
36 const AdditionalKeywords &Keywords)
37 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
38 Keywords(Keywords) {}
Daniel Jasper0df50932014-12-10 19:00:42 +000039
40 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
41 int AdditionalIndent = 0, bool FixBadIndentation = false);
42
Daniel Jasper289afc02015-04-23 09:23:17 +000043
44 /// \brief If the \p State's next token is an r_brace closing a nested block,
45 /// format the nested block before it.
46 ///
47 /// Returns \c true if all children could be placed successfully and adapts
48 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
49 /// creates changes using \c Whitespaces.
50 ///
51 /// The crucial idea here is that children always get formatted upon
52 /// encountering the closing brace right after the nested block. Now, if we
53 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
54 /// \c false), the entire block has to be kept on the same line (which is only
55 /// possible if it fits on the line, only contains a single statement, etc.
56 ///
57 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
58 /// break after the "{", format all lines with correct indentation and the put
59 /// the closing "}" on yet another new line.
60 ///
61 /// This enables us to keep the simple structure of the
62 /// \c UnwrappedLineFormatter, where we only have two options for each token:
63 /// break or don't break.
64 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
65 unsigned &Penalty);
66
Daniel Jasper0df50932014-12-10 19:00:42 +000067private:
68 /// \brief Formats an \c AnnotatedLine and returns the penalty.
69 ///
70 /// If \p DryRun is \c false, directly applies the changes.
71 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
72 bool DryRun);
73
74 /// \brief An edge in the solution space from \c Previous->State to \c State,
75 /// inserting a newline dependent on the \c NewLine.
76 struct StateNode {
77 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
78 : State(State), NewLine(NewLine), Previous(Previous) {}
79 LineState State;
80 bool NewLine;
81 StateNode *Previous;
82 };
83
84 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
85 ///
86 /// In case of equal penalties, we want to prefer states that were inserted
87 /// first. During state generation we make sure that we insert states first
88 /// that break the line as late as possible.
89 typedef std::pair<unsigned, unsigned> OrderedPenalty;
90
91 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
92 /// \c State has the given \c OrderedPenalty.
93 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
94
95 /// \brief The BFS queue type.
96 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
97 std::greater<QueueItem> > QueueType;
98
99 /// \brief Get the offset of the line relatively to the level.
100 ///
101 /// For example, 'public:' labels in classes are offset by 1 or 2
102 /// characters to the left from their level.
103 int getIndentOffset(const FormatToken &RootToken) {
Daniel Jasper83709082015-02-18 17:14:05 +0000104 if (Style.Language == FormatStyle::LK_Java ||
105 Style.Language == FormatStyle::LK_JavaScript)
Daniel Jasper0df50932014-12-10 19:00:42 +0000106 return 0;
Daniel Jasper53395402015-04-07 15:04:40 +0000107 if (RootToken.isAccessSpecifier(false) ||
Daniel Jasper03618142015-05-06 19:21:23 +0000108 RootToken.isObjCAccessSpecifier() ||
109 (RootToken.is(Keywords.kw_signals) && RootToken.Next &&
110 RootToken.Next->is(tok::colon)))
Daniel Jasper0df50932014-12-10 19:00:42 +0000111 return Style.AccessModifierOffset;
112 return 0;
113 }
114
115 /// \brief Add a new line and the required indent before the first Token
116 /// of the \c UnwrappedLine if there was no structural parsing error.
117 void formatFirstToken(FormatToken &RootToken,
118 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
119 unsigned Indent, bool InPPDirective);
120
121 /// \brief Get the indent of \p Level from \p IndentForLevel.
122 ///
123 /// \p IndentForLevel must contain the indent for the level \c l
124 /// at \p IndentForLevel[l], or a value < 0 if the indent for
125 /// that level is unknown.
126 unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level);
127
128 void join(AnnotatedLine &A, const AnnotatedLine &B);
129
130 unsigned getColumnLimit(bool InPPDirective) const {
131 // In preprocessor directives reserve two chars for trailing " \"
132 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
133 }
134
135 struct CompareLineStatePointers {
136 bool operator()(LineState *obj1, LineState *obj2) const {
137 return *obj1 < *obj2;
138 }
139 };
140
141 /// \brief Analyze the entire solution space starting from \p InitialState.
142 ///
143 /// This implements a variant of Dijkstra's algorithm on the graph that spans
144 /// the solution space (\c LineStates are the nodes). The algorithm tries to
145 /// find the shortest path (the one with lowest penalty) from \p InitialState
146 /// to a state where all tokens are placed. Returns the penalty.
147 ///
148 /// If \p DryRun is \c false, directly applies the changes.
149 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false);
150
151 void reconstructPath(LineState &State, StateNode *Current);
152
153 /// \brief Add the following state to the analysis queue \c Queue.
154 ///
155 /// Assume the current state is \p PreviousNode and has been reached with a
156 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
157 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
158 bool NewLine, unsigned *Count, QueueType *Queue);
159
Daniel Jasper0df50932014-12-10 19:00:42 +0000160 ContinuationIndenter *Indenter;
161 WhitespaceManager *Whitespaces;
162 FormatStyle Style;
Nico Weberfac23712015-02-04 15:26:27 +0000163 const AdditionalKeywords &Keywords;
Daniel Jasper0df50932014-12-10 19:00:42 +0000164
165 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
166
167 // Cache to store the penalty of formatting a vector of AnnotatedLines
168 // starting from a specific additional offset. Improves performance if there
169 // are many nested blocks.
170 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
171 unsigned> PenaltyCache;
172};
173} // end namespace format
174} // end namespace clang
175
176#endif // LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEFORMATTER_H