Skip to content

Commit ecb3690

Browse files
jneenjneen
andauthored
c++: expand support for c++ float literals (#2123)
* c++: support f, F as float suffixes Fixes #577 * fix the regex nesting and add visual spec * add support for hex floats and exps --------- Co-authored-by: jneen <[email protected]>
1 parent bdcdc59 commit ecb3690

File tree

2 files changed

+45
-3
lines changed

2 files changed

+45
-3
lines changed

lib/rouge/lexers/cpp.rb

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,10 @@ def self.reserved
6262
rule %r/(class|struct)\b/, Keyword, :classname
6363
rule %r/template\b/, Keyword, :template
6464
rule %r/#{dq}(\.#{dq})?(?:y|d|h|(?:min)|s|(?:ms)|(?:us)|(?:ns)|i|(?:if)|(?:il))\b/, Num::Other
65-
rule %r((#{dq}[.]#{dq}?|[.]#{dq})(e[+-]?#{dq}[lu]*)?)i, Num::Float
66-
rule %r(#{dq}e[+-]?#{dq}[lu]*)i, Num::Float
67-
rule %r/0x\h('?\h)*[lu]*/i, Num::Hex
65+
rule %r((#{dq}[.]#{dq}?|[.]#{dq})([ep][+-]?#{dq})?[luf]*)i, Num::Float
66+
rule %r(#{dq}[ep][+-]?#{dq}[luf]*)i, Num::Float
67+
rule %r/0x\h('?\h)*([ep][+-]?#{dq})?[lu]*/i, Num::Hex
68+
rule %r/0x\h('?\h)*[.]\h+([ep][+-]?#{dq})[luf]*/i, Num::Hex
6869
rule %r/0b[01]+('[01]+)*/, Num::Bin
6970
rule %r/0[0-7]('?[0-7])*[lu]*/i, Num::Oct
7071
rule %r/#{dq}[lu]*/i, Num::Integer

spec/visual/samples/cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,3 +277,44 @@ export struct Shape {
277277
int m_x;
278278
int m_y;
279279
}
280+
281+
float test(8.874L);
282+
float test(8.874l);
283+
float test(8.874F);
284+
float test(8.874f);
285+
float test(8.874U);
286+
float test(8.874u);
287+
288+
// via https://en.cppreference.com/w/cpp/language/floating_literal
289+
int main()
290+
{
291+
std::cout
292+
<< "Literal" "\t" "Printed value" << std::left
293+
<< OUT( 58. ) // double
294+
<< OUT( 4e2 ) // double
295+
<< OUT( 123.456e-67 ) // double
296+
<< OUT( 123.456e-67f ) // float, truncated to zero
297+
<< OUT( .1E4f ) // float
298+
<< OUT( 0x10.1p0 ) // double
299+
<< OUT( 0x1p5 ) // double
300+
<< OUT( 0x1e5 ) // integer literal, not floating-point
301+
<< OUT( 3.14'15'92 ) // double, single quotes ignored (C++14)
302+
<< OUT( 1.18e-4932l ) // long double
303+
<< std::setprecision(39)
304+
<< OUT( 3.4028234e38f ) // float
305+
<< OUT( 3.4028234e38 ) // double
306+
<< OUT( 3.4028234e38l ) // long double
307+
<< '\n';
308+
309+
static_assert(3.4028234e38f == std::numeric_limits<float>::max());
310+
311+
static_assert(3.4028234e38f == // ends with 4
312+
3.4028235e38f); // ends with 5
313+
314+
static_assert(3.4028234e38 != // ends with 4
315+
3.4028235e38); // ends with 5
316+
317+
// Both floating-point constants below are 3.4028234e38
318+
static_assert(3.4028234e38f != // a float (then promoted to double)
319+
3.4028234e38); // a double
320+
}

0 commit comments

Comments
 (0)