Skip to content

Commit 7755e78

Browse files
author
Kapil Borle
committed
Add methods to get one line if-else braces
1 parent f99ae8f commit 7755e78

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

Engine/TokenOperations.cs

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,86 @@ private IEnumerable<Token> GetBraceInCommandElement(TokenKind tokenKind)
110110
}
111111
}
112112

113+
public IEnumerable<Token> GetCloseBraceInOneLineIfStatement()
114+
{
115+
return GetBraceInOneLineIfStatment(TokenKind.RCurly);
116+
}
117+
118+
public IEnumerable<Token> GetOpenBraceInOneLineIfStatement()
119+
{
120+
return GetBraceInOneLineIfStatment(TokenKind.LCurly);
121+
}
122+
123+
// TODO Fix code duplication in the following method and GetBraceInCommandElement
124+
private IEnumerable<Token> GetBraceInOneLineIfStatment(TokenKind tokenKind)
125+
{
126+
var ifStatementAsts = ast.FindAll(ast =>
127+
{
128+
var ifAst = ast as IfStatementAst;
129+
if (ifAst == null)
130+
{
131+
return false;
132+
}
133+
134+
return ifAst.Extent.StartLineNumber == ifAst.Extent.EndLineNumber;
135+
},
136+
true);
137+
138+
if (ifStatementAsts == null)
139+
{
140+
yield break;
141+
}
142+
143+
var braceTokens = new List<Token>();
144+
foreach (var ast in ifStatementAsts)
145+
{
146+
var ifStatementAst = ast as IfStatementAst;
147+
foreach (var clause in ifStatementAst.Clauses)
148+
{
149+
var tokenIf
150+
= tokenKind == TokenKind.LCurly
151+
? GetTokens(clause.Item2).FirstOrDefault()
152+
: GetTokens(clause.Item2).LastOrDefault();
153+
if (tokenIf != null)
154+
{
155+
yield return tokenIf;
156+
}
157+
}
158+
159+
if (ifStatementAst.ElseClause == null)
160+
{
161+
continue;
162+
}
163+
164+
var tokenElse
165+
= tokenKind == TokenKind.LCurly
166+
? GetTokens(ifStatementAst.ElseClause).FirstOrDefault()
167+
: GetTokens(ifStatementAst.ElseClause).LastOrDefault();
168+
if (tokenElse != null)
169+
{
170+
yield return tokenElse;
171+
}
172+
}
173+
}
174+
175+
private IEnumerable<Token> GetTokens(Ast ast)
176+
{
177+
int k = 0;
178+
while (k < tokens.Length && tokens[k].Extent.EndOffset <= ast.Extent.StartOffset)
179+
{
180+
k++;
181+
}
182+
183+
while (k < tokens.Length && tokens[k].Extent.EndOffset <= ast.Extent.EndOffset)
184+
{
185+
var token = tokens[k++];
186+
if (token.Extent.StartOffset >= ast.Extent.StartOffset)
187+
{
188+
yield return token;
189+
}
190+
}
191+
}
192+
113193
public IEnumerable<LinkedListNode<Token>> GetTokenNodes(TokenKind kind)
114194
{
115195
return GetTokenNodes((token) => token.Kind == kind);

0 commit comments

Comments
 (0)