r332045 - implementing Cursor.get_included_file in python bindings

2018-05-10 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Thu May 10 14:39:29 2018
New Revision: 332045

URL: http://llvm.org/viewvc/llvm-project?rev=332045&view=rev
Log:
implementing Cursor.get_included_file in python bindings

Summary:
adding function: `Cursor.get_included_file` , so the C API's 
`clang_getIncludedFile` function is available on the python binding interface
also adding test to unittests

related ticket: https://bugs.llvm.org/show_bug.cgi?id=15223

Reviewers: mgorny, arphaman, jbcoe

Reviewed By: jbcoe

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D46383

Patch by jlaz (József Láz)

Modified:
cfe/trunk/bindings/python/clang/cindex.py
cfe/trunk/bindings/python/tests/cindex/test_translation_unit.py

Modified: cfe/trunk/bindings/python/clang/cindex.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/cindex.py?rev=332045&r1=332044&r2=332045&view=diff
==
--- cfe/trunk/bindings/python/clang/cindex.py (original)
+++ cfe/trunk/bindings/python/clang/cindex.py Thu May 10 14:39:29 2018
@@ -1511,6 +1511,12 @@ class Cursor(Structure):
 another translation unit."""
 return conf.lib.clang_getCursorUSR(self)
 
+def get_included_file(self):
+"""Returns the File that is included by the current inclusion 
cursor."""
+assert self.kind == CursorKind.INCLUSION_DIRECTIVE
+
+return conf.lib.clang_getIncludedFile(self)
+
 @property
 def kind(self):
 """Return the kind of this cursor."""
@@ -3085,8 +3091,9 @@ class File(ClangObject):
 return "" % (self.name)
 
 @staticmethod
-def from_cursor_result(res, fn, args):
-assert isinstance(res, File)
+def from_result(res, fn, args):
+assert isinstance(res, c_object_p)
+res = File(res)
 
 # Copy a reference to the TranslationUnit to prevent premature GC.
 res._tu = args[0]._tu
@@ -3701,8 +3708,8 @@ functionList = [
 
   ("clang_getIncludedFile",
[Cursor],
-   File,
-   File.from_cursor_result),
+   c_object_p,
+   File.from_result),
 
   ("clang_getInclusions",
[TranslationUnit, callbacks['translation_unit_includes'], py_object]),

Modified: cfe/trunk/bindings/python/tests/cindex/test_translation_unit.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/tests/cindex/test_translation_unit.py?rev=332045&r1=332044&r2=332045&view=diff
==
--- cfe/trunk/bindings/python/tests/cindex/test_translation_unit.py (original)
+++ cfe/trunk/bindings/python/tests/cindex/test_translation_unit.py Thu May 10 
14:39:29 2018
@@ -108,6 +108,18 @@ int SOME_DEFINE;
 for i in zip(inc, tu.get_includes()):
 eq(i[0], i[1])
 
+def test_inclusion_directive(self):
+src = os.path.join(kInputsDir, 'include.cpp')
+h1 = os.path.join(kInputsDir, "header1.h")
+h2 = os.path.join(kInputsDir, "header2.h")
+h3 = os.path.join(kInputsDir, "header3.h")
+inc = [h1, h3, h2, h3, h1]
+
+tu = TranslationUnit.from_source(src, 
options=TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD)
+inclusion_directive_files = [c.get_included_file().name for c in 
tu.cursor.get_children() if c.kind == CursorKind.INCLUSION_DIRECTIVE]
+for i in zip(inc, inclusion_directive_files):
+self.assert_normpaths_equal(i[0], i[1])
+
 def test_save(self):
 """Ensure TranslationUnit.save() works."""
 


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r315958 - [libclang] Visit attributes for function and class templates

2017-10-16 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Mon Oct 16 16:43:02 2017
New Revision: 315958

URL: http://llvm.org/viewvc/llvm-project?rev=315958&view=rev
Log:
[libclang] Visit attributes for function and class templates

Summary: Previously, `VisitAttributes` was not called for function and class 
templates and thus their attributes were not accessible using libclang.

Reviewers: bkramer, arphaman, rsmith, jbcoe

Reviewed By: jbcoe

Subscribers: cfe-commits

Tags: #clang

Patch by jklaehn (Johann Klähn)

Differential Revision: https://reviews.llvm.org/D36955

Modified:
cfe/trunk/bindings/python/tests/cindex/test_cursor.py
cfe/trunk/test/Index/annotate-attribute.cpp
cfe/trunk/tools/libclang/CIndex.cpp

Modified: cfe/trunk/bindings/python/tests/cindex/test_cursor.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/tests/cindex/test_cursor.py?rev=315958&r1=315957&r2=315958&view=diff
==
--- cfe/trunk/bindings/python/tests/cindex/test_cursor.py (original)
+++ cfe/trunk/bindings/python/tests/cindex/test_cursor.py Mon Oct 16 16:43:02 
2017
@@ -377,6 +377,26 @@ def test_annotation_attribute():
 else:
 assert False, "Couldn't find annotation"
 
+def test_annotation_template():
+annotation = '__attribute__ ((annotate("annotation")))'
+for source, kind in [
+('int foo (T value) %s;', CursorKind.FUNCTION_TEMPLATE),
+('class %s foo {};', CursorKind.CLASS_TEMPLATE),
+]:
+source = 'template ' + (source % annotation)
+tu = get_tu(source, lang="cpp")
+
+foo = get_cursor(tu, 'foo')
+assert foo is not None
+assert foo.kind == kind
+
+for c in foo.get_children():
+if c.kind == CursorKind.ANNOTATE_ATTR:
+assert c.displayname == "annotation"
+break
+else:
+assert False, "Couldn't find annotation for {}".format(kind)
+
 def test_result_type():
 tu = get_tu('int foo();')
 foo = get_cursor(tu, 'foo')

Modified: cfe/trunk/test/Index/annotate-attribute.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/annotate-attribute.cpp?rev=315958&r1=315957&r2=315958&view=diff
==
--- cfe/trunk/test/Index/annotate-attribute.cpp (original)
+++ cfe/trunk/test/Index/annotate-attribute.cpp Mon Oct 16 16:43:02 2017
@@ -16,6 +16,12 @@ protected:
   void methodWithoutAttribute();
 };
 
+template 
+class __attribute__((annotate("works"))) TemplateTest {};
+
+template 
+int templateFunction(T value) __attribute__((annotate("works")));
+
 // CHECK: ClassDecl=Test:3:7 (Definition) Extent=[3:1 - 17:2]
 // CHECK-NEXT: CXXAccessSpecifier=:4:1 (Definition) Extent=[4:1 - 4:8]
 // CHECK-NEXT: CXXMethod=aMethod:5:51 Extent=[5:3 - 5:60]
@@ -31,3 +37,9 @@ protected:
 // CHECK-NEXT: CompoundStmt= Extent=[12:23 - 12:25]
 // CHECK-NEXT: CXXAccessSpecifier=:14:1 (Definition) Extent=[14:1 - 14:11]
 // CHECK-NEXT: CXXMethod=methodWithoutAttribute:16:8 Extent=[16:3 - 16:32]
+// CHECK: ClassTemplate=TemplateTest:20:42 (Definition) Extent=[19:1 - 20:57]
+// CHECK-NEXT: TemplateTypeParameter=T:19:20 (Definition) Extent=[19:11 - 
19:21] [access=public]
+// CHECK-NEXT: attribute(annotate)=works Extent=[20:22 - 20:39]
+// CHECK: FunctionTemplate=templateFunction:23:5 Extent=[22:1 - 23:65]
+// CHECK-NEXT: TemplateTypeParameter=T:22:20 (Definition) Extent=[22:11 - 
22:21] [access=public]
+// CHECK-NEXT: attribute(annotate)=works Extent=[23:46 - 23:63]

Modified: cfe/trunk/tools/libclang/CIndex.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/libclang/CIndex.cpp?rev=315958&r1=315957&r2=315958&view=diff
==
--- cfe/trunk/tools/libclang/CIndex.cpp (original)
+++ cfe/trunk/tools/libclang/CIndex.cpp Mon Oct 16 16:43:02 2017
@@ -907,7 +907,8 @@ bool CursorVisitor::VisitFunctionTemplat
   if (VisitTemplateParameters(D->getTemplateParameters()))
 return true;
   
-  return VisitFunctionDecl(D->getTemplatedDecl());
+  auto* FD = D->getTemplatedDecl();
+  return VisitAttributes(FD) || VisitFunctionDecl(FD);
 }
 
 bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
@@ -916,7 +917,8 @@ bool CursorVisitor::VisitClassTemplateDe
   if (VisitTemplateParameters(D->getTemplateParameters()))
 return true;
   
-  return VisitCXXRecordDecl(D->getTemplatedDecl());
+  auto* CD = D->getTemplatedDecl();
+  return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
 }
 
 bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) 
{


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r315959 - [libclang] Add support for querying cursor availability

2017-10-16 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Mon Oct 16 16:46:02 2017
New Revision: 315959

URL: http://llvm.org/viewvc/llvm-project?rev=315959&view=rev
Log:
[libclang] Add support for querying cursor availability

Summary:
This patch allows checking the availability of cursors through libclang and 
clang.cindex (Python).
This e.g. allows to check whether a C++ member function has been marked as 
deleted.

Reviewers: arphaman, jbcoe

Reviewed By: jbcoe

Subscribers: cfe-commits

Tags: #clang

Patch by jklaehn (Johann Klähn)

Differential Revision: https://reviews.llvm.org/D36973

Modified:
cfe/trunk/bindings/python/clang/cindex.py
cfe/trunk/bindings/python/tests/cindex/test_cursor.py

Modified: cfe/trunk/bindings/python/clang/cindex.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/cindex.py?rev=315959&r1=315958&r2=315959&view=diff
==
--- cfe/trunk/bindings/python/clang/cindex.py (original)
+++ cfe/trunk/bindings/python/clang/cindex.py Mon Oct 16 16:46:02 2017
@@ -1587,6 +1587,16 @@ class Cursor(Structure):
 return StorageClass.from_id(self._storage_class)
 
 @property
+def availability(self):
+"""
+Retrieves the availability of the entity pointed at by the cursor.
+"""
+if not hasattr(self, '_availability'):
+self._availability = conf.lib.clang_getCursorAvailability(self)
+
+return AvailabilityKind.from_id(self._availability)
+
+@property
 def access_specifier(self):
 """
 Retrieves the access specifier (if any) of the entity pointed at by the
@@ -1923,6 +1933,24 @@ StorageClass.OPENCLWORKGROUPLOCAL = Stor
 StorageClass.AUTO = StorageClass(6)
 StorageClass.REGISTER = StorageClass(7)
 
+### Availability Kinds ###
+
+class AvailabilityKind(BaseEnumeration):
+"""
+Describes the availability of an entity.
+"""
+
+# The unique kind objects, indexed by id.
+_kinds = []
+_name_map = None
+
+def __repr__(self):
+return 'AvailabilityKind.%s' % (self.name,)
+
+AvailabilityKind.AVAILABLE = AvailabilityKind(0)
+AvailabilityKind.DEPRECATED = AvailabilityKind(1)
+AvailabilityKind.NOT_AVAILABLE = AvailabilityKind(2)
+AvailabilityKind.NOT_ACCESSIBLE = AvailabilityKind(3)
 
 ### C++ access specifiers ###
 
@@ -3491,6 +3519,10 @@ functionList = [
[TranslationUnit, SourceLocation],
Cursor),
 
+  ("clang_getCursorAvailability",
+   [Cursor],
+   c_int),
+
   ("clang_getCursorDefinition",
[Cursor],
Cursor,
@@ -4106,6 +4138,7 @@ conf = Config()
 register_enumerations()
 
 __all__ = [
+'AvailabilityKind',
 'Config',
 'CodeCompletionResults',
 'CompilationDatabase',

Modified: cfe/trunk/bindings/python/tests/cindex/test_cursor.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/tests/cindex/test_cursor.py?rev=315959&r1=315958&r2=315959&view=diff
==
--- cfe/trunk/bindings/python/tests/cindex/test_cursor.py (original)
+++ cfe/trunk/bindings/python/tests/cindex/test_cursor.py Mon Oct 16 16:46:02 
2017
@@ -1,6 +1,7 @@
 import ctypes
 import gc
 
+from clang.cindex import AvailabilityKind
 from clang.cindex import CursorKind
 from clang.cindex import TemplateArgumentKind
 from clang.cindex import TranslationUnit
@@ -405,6 +406,30 @@ def test_result_type():
 t = foo.result_type
 assert t.kind == TypeKind.INT
 
+def test_availability():
+tu = get_tu('class A { A(A const&) = delete; };', lang='cpp')
+
+# AvailabilityKind.AVAILABLE
+cursor = get_cursor(tu, 'A')
+assert cursor.kind == CursorKind.CLASS_DECL
+assert cursor.availability == AvailabilityKind.AVAILABLE
+
+# AvailabilityKind.NOT_AVAILABLE
+cursors = get_cursors(tu, 'A')
+for c in cursors:
+if c.kind == CursorKind.CONSTRUCTOR:
+assert c.availability == AvailabilityKind.NOT_AVAILABLE
+break
+else:
+assert False, "Could not find cursor for deleted constructor"
+
+# AvailabilityKind.DEPRECATED
+tu = get_tu('void test() __attribute__((deprecated));', lang='cpp')
+cursor = get_cursor(tu, 'test')
+assert cursor.availability == AvailabilityKind.DEPRECATED
+
+# AvailabilityKind.NOT_ACCESSIBLE is only used in the code completion 
results
+
 def test_get_tokens():
 """Ensure we can map cursors back to tokens."""
 tu = get_tu('int foo(int i);')


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r341930 - [python bindings] Expose getNumTemplateArguments

2018-09-11 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Tue Sep 11 05:44:52 2018
New Revision: 341930

URL: http://llvm.org/viewvc/llvm-project?rev=341930&view=rev
Log:
[python bindings] Expose getNumTemplateArguments

Expose the C bindings for clang_Type_getNumTemplateArguments() and
clang_Type_getTemplateArgumentAsType() in the python API.

Patch by kjteske (Kyle Teske).

Reviewed By: jbcoe

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D51299

Modified:
cfe/trunk/bindings/python/clang/cindex.py
cfe/trunk/bindings/python/tests/cindex/test_type.py

Modified: cfe/trunk/bindings/python/clang/cindex.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/cindex.py?rev=341930&r1=341929&r2=341930&view=diff
==
--- cfe/trunk/bindings/python/clang/cindex.py (original)
+++ cfe/trunk/bindings/python/clang/cindex.py Tue Sep 11 05:44:52 2018
@@ -2254,6 +2254,12 @@ class Type(Structure):
 
 return res
 
+def get_num_template_arguments(self):
+return conf.lib.clang_Type_getNumTemplateArguments(self)
+
+def get_template_argument_type(self, num):
+return conf.lib.clang_Type_getTemplateArgumentAsType(self, num)
+
 def get_canonical(self):
 """
 Return the canonical type for a Type.
@@ -3999,6 +4005,15 @@ functionList = [
Type,
Type.from_result),
 
+  ("clang_Type_getNumTemplateArguments",
+   [Type],
+   c_int),
+
+  ("clang_Type_getTemplateArgumentAsType",
+   [Type, c_uint],
+   Type,
+   Type.from_result),
+
   ("clang_Type_getOffsetOf",
[Type, c_interop_string],
c_longlong),

Modified: cfe/trunk/bindings/python/tests/cindex/test_type.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/tests/cindex/test_type.py?rev=341930&r1=341929&r2=341930&view=diff
==
--- cfe/trunk/bindings/python/tests/cindex/test_type.py (original)
+++ cfe/trunk/bindings/python/tests/cindex/test_type.py Tue Sep 11 05:44:52 2018
@@ -436,3 +436,28 @@ class TestType(unittest.TestCase):
 
 self.assertIsNotNone(testInteger, "Could not find testInteger.")
 self.assertEqual(testInteger.type.get_address_space(), 2)
+
+def test_template_arguments(self):
+source = """
+class Foo {
+};
+template 
+class Template {
+};
+Template instance;
+int bar;
+"""
+tu = get_tu(source, lang='cpp')
+
+# Varible with a template argument.
+cursor = get_cursor(tu, 'instance')
+cursor_type = cursor.type
+self.assertEqual(cursor.kind, CursorKind.VAR_DECL)
+self.assertEqual(cursor_type.spelling, 'Template')
+self.assertEqual(cursor_type.get_num_template_arguments(), 1)
+template_type = cursor_type.get_template_argument_type(0)
+self.assertEqual(template_type.spelling, 'Foo')
+
+# Variable without a template argument.
+cursor = get_cursor(tu, 'bar')
+self.assertEqual(cursor.get_num_template_arguments(), -1)


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r335282 - [bindings] Fix most Python binding unittests on Windows

2018-06-21 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Thu Jun 21 13:07:03 2018
New Revision: 335282

URL: http://llvm.org/viewvc/llvm-project?rev=335282&view=rev
Log:
[bindings] Fix most Python binding unittests on Windows

Summary:
This fixes all but one of the test cases for Windows. TestCDB will
take more work to debug, as CompilationDatabase seems not to work correctly.

Reviewers: bkramer, wanders, jbcoe

Reviewed By: bkramer, jbcoe

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D47864

Patch written by ethanhs (Ethan)

Modified:
cfe/trunk/bindings/python/tests/cindex/test_cdb.py
cfe/trunk/bindings/python/tests/cindex/test_cursor.py
cfe/trunk/bindings/python/tests/cindex/test_translation_unit.py

Modified: cfe/trunk/bindings/python/tests/cindex/test_cdb.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/tests/cindex/test_cdb.py?rev=335282&r1=335281&r2=335282&view=diff
==
--- cfe/trunk/bindings/python/tests/cindex/test_cdb.py (original)
+++ cfe/trunk/bindings/python/tests/cindex/test_cdb.py Thu Jun 21 13:07:03 2018
@@ -5,11 +5,13 @@ from clang.cindex import CompileCommand
 import os
 import gc
 import unittest
+import sys
 
 
 kInputsDir = os.path.join(os.path.dirname(__file__), 'INPUTS')
 
 
+@unittest.skipIf(sys.platform == 'win32', "TODO: Fix these tests on Windows")
 class TestCDB(unittest.TestCase):
 def test_create_fail(self):
 """Check we fail loading a database with an assertion"""

Modified: cfe/trunk/bindings/python/tests/cindex/test_cursor.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/tests/cindex/test_cursor.py?rev=335282&r1=335281&r2=335282&view=diff
==
--- cfe/trunk/bindings/python/tests/cindex/test_cursor.py (original)
+++ cfe/trunk/bindings/python/tests/cindex/test_cursor.py Thu Jun 21 13:07:03 
2018
@@ -335,7 +335,7 @@ class TestCursor(unittest.TestCase):
 
 self.assertEqual(enum.kind, CursorKind.ENUM_DECL)
 enum_type = enum.enum_type
-self.assertEqual(enum_type.kind, TypeKind.UINT)
+self.assertIn(enum_type.kind, (TypeKind.UINT, TypeKind.INT))
 
 def test_enum_type_cpp(self):
 tu = get_tu('enum TEST : long long { FOO=1, BAR=2 };', lang="cpp")
@@ -561,4 +561,4 @@ class TestCursor(unittest.TestCase):
 # all valid manglings.
 # [c-index-test handles this by running the source through clang, 
emitting
 #  an AST file and running libclang on that AST file]
-self.assertIn(foo.mangled_name, ('_Z3fooii', '__Z3fooii', 
'?foo@@YAHHH'))
+self.assertIn(foo.mangled_name, ('_Z3fooii', '__Z3fooii', 
'?foo@@YAHHH', '?foo@@YAHHH@Z'))

Modified: cfe/trunk/bindings/python/tests/cindex/test_translation_unit.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/tests/cindex/test_translation_unit.py?rev=335282&r1=335281&r2=335282&view=diff
==
--- cfe/trunk/bindings/python/tests/cindex/test_translation_unit.py (original)
+++ cfe/trunk/bindings/python/tests/cindex/test_translation_unit.py Thu Jun 21 
13:07:03 2018
@@ -1,3 +1,4 @@
+from contextlib import contextmanager
 import gc
 import os
 import tempfile
@@ -19,15 +20,15 @@ from .util import get_tu
 kInputsDir = os.path.join(os.path.dirname(__file__), 'INPUTS')
 
 
+@contextmanager
 def save_tu(tu):
 """Convenience API to save a TranslationUnit to a file.
 
 Returns the filename it was saved to.
 """
-_, path = tempfile.mkstemp()
-tu.save(path)
-
-return path
+with tempfile.NamedTemporaryFile() as t:
+tu.save(t.name)
+yield t.name
 
 
 class TestTranslationUnit(unittest.TestCase):
@@ -125,10 +126,9 @@ int SOME_DEFINE;
 
 tu = get_tu('int foo();')
 
-path = save_tu(tu)
-self.assertTrue(os.path.exists(path))
-self.assertGreater(os.path.getsize(path), 0)
-os.unlink(path)
+with save_tu(tu) as path:
+self.assertTrue(os.path.exists(path))
+self.assertGreater(os.path.getsize(path), 0)
 
 def test_save_translation_errors(self):
 """Ensure that saving to an invalid directory raises."""
@@ -149,21 +149,18 @@ int SOME_DEFINE;
 
 tu = get_tu('int foo();')
 self.assertEqual(len(tu.diagnostics), 0)
-path = save_tu(tu)
-
-self.assertTrue(os.path.exists(path))
-self.assertGreater(os.path.getsize(path), 0)
-
-tu2 = TranslationUnit.from_ast_file(filename=path)
-self.assertEqual(len(tu2.diagnostics), 0)
+with save_tu(tu) as path:
+self.assertTrue(os.path.exists(path))
+self.assertGreater(os.path.getsize(path), 0)
 
-foo = get_cursor(tu2, 'foo')
-self.assertIsNotNone(foo)
+tu2 = TranslationUnit.from_ast_file(filename=path)
+self.assertEqual(

r312622 - Fix __repr__ for Diagnostic in clang.cindex

2017-09-06 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Wed Sep  6 00:33:32 2017
New Revision: 312622

URL: http://llvm.org/viewvc/llvm-project?rev=312622&view=rev
Log:
Fix __repr__ for Diagnostic in clang.cindex

Summary: Also move misplaced tests for exception specification to fix failing 
Python tests.

Reviewers: hans, compnerd

Reviewed By: compnerd

Subscribers: cfe-commits

Tags: #clang-c

Differential Revision: https://reviews.llvm.org/D37490

Added:
cfe/trunk/bindings/python/tests/cindex/test_exception_specification_kind.py
Removed:
cfe/trunk/bindings/python/tests/test_exception_specification_kind.py
Modified:
cfe/trunk/bindings/python/clang/cindex.py
cfe/trunk/bindings/python/tests/cindex/test_diagnostics.py

Modified: cfe/trunk/bindings/python/clang/cindex.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/cindex.py?rev=312622&r1=312621&r2=312622&view=diff
==
--- cfe/trunk/bindings/python/clang/cindex.py (original)
+++ cfe/trunk/bindings/python/clang/cindex.py Wed Sep  6 00:33:32 2017
@@ -207,7 +207,7 @@ class _CXString(Structure):
 conf.lib.clang_disposeString(self)
 
 @staticmethod
-def from_result(res, fn, args):
+def from_result(res, fn=None, args=None):
 assert isinstance(res, _CXString)
 return conf.lib.clang_getCString(res)
 
@@ -459,8 +459,7 @@ class Diagnostic(object):
 """The command-line option that disables this diagnostic."""
 disable = _CXString()
 conf.lib.clang_getDiagnosticOption(self, byref(disable))
-
-return conf.lib.clang_getCString(disable)
+return _CXString.from_result(disable)
 
 def format(self, options=None):
 """
@@ -473,8 +472,7 @@ class Diagnostic(object):
 options = conf.lib.clang_defaultDiagnosticDisplayOptions()
 if options & ~Diagnostic._FormatOptionsMask:
 raise ValueError('Invalid format options')
-formatted = conf.lib.clang_formatDiagnostic(self, options)
-return conf.lib.clang_getCString(formatted)
+return conf.lib.clang_formatDiagnostic(self, options)
 
 def __repr__(self):
 return "" % (

Modified: cfe/trunk/bindings/python/tests/cindex/test_diagnostics.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/tests/cindex/test_diagnostics.py?rev=312622&r1=312621&r2=312622&view=diff
==
--- cfe/trunk/bindings/python/tests/cindex/test_diagnostics.py (original)
+++ cfe/trunk/bindings/python/tests/cindex/test_diagnostics.py Wed Sep  6 
00:33:32 2017
@@ -92,3 +92,11 @@ def test_diagnostic_children():
 assert children[0].spelling.endswith('declared here')
 assert children[0].location.line == 1
 assert children[0].location.column == 1
+
+def test_diagnostic_string_repr():
+tu = get_tu('struct MissingSemicolon{}')
+assert len(tu.diagnostics) == 1
+d = tu.diagnostics[0]
+
+assert repr(d) == ', spelling "expected \';\' after struct">'
+

Added: 
cfe/trunk/bindings/python/tests/cindex/test_exception_specification_kind.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/tests/cindex/test_exception_specification_kind.py?rev=312622&view=auto
==
--- cfe/trunk/bindings/python/tests/cindex/test_exception_specification_kind.py 
(added)
+++ cfe/trunk/bindings/python/tests/cindex/test_exception_specification_kind.py 
Wed Sep  6 00:33:32 2017
@@ -0,0 +1,27 @@
+import clang.cindex
+from clang.cindex import ExceptionSpecificationKind
+from .util import get_tu
+
+
+def find_function_declarations(node, declarations=[]):
+if node.kind == clang.cindex.CursorKind.FUNCTION_DECL:
+declarations.append((node.spelling, node.exception_specification_kind))
+for child in node.get_children():
+declarations = find_function_declarations(child, declarations)
+return declarations
+
+
+def test_exception_specification_kind():
+source = """int square1(int x);
+int square2(int x) noexcept;
+int square3(int x) noexcept(noexcept(x * x));"""
+
+tu = get_tu(source, lang='cpp', flags=['-std=c++14'])
+
+declarations = find_function_declarations(tu.cursor)
+expected = [
+('square1', ExceptionSpecificationKind.NONE),
+('square2', ExceptionSpecificationKind.BASIC_NOEXCEPT),
+('square3', ExceptionSpecificationKind.COMPUTED_NOEXCEPT)
+]
+assert declarations == expected

Removed: cfe/trunk/bindings/python/tests/test_exception_specification_kind.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/tests/test_exception_specification_kind.py?rev=312621&view=auto
==
--- cfe/trunk/bindings/python/tests/test_exception_specification_kind.py 
(original)
+++ cfe/trunk/bindings/

r313913 - [libclang] Keep track of TranslationUnit instance when annotating tokens

2017-09-21 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Thu Sep 21 13:48:43 2017
New Revision: 313913

URL: http://llvm.org/viewvc/llvm-project?rev=313913&view=rev
Log:
[libclang] Keep track of TranslationUnit instance when annotating tokens

Summary:
Previously the `_tu` was not propagated to the returned cursor, leading to 
errors when calling any
method on that cursor (e.g. `cursor.referenced`).

Reviewers: jbcoe, rsmith

Reviewed By: jbcoe

Subscribers: cfe-commits

Tags: #clang

Patch by jklaehn (Johann Klähn)

Differential Revision: https://reviews.llvm.org/D36953

Modified:
cfe/trunk/bindings/python/clang/cindex.py
cfe/trunk/bindings/python/tests/cindex/test_cursor.py

Modified: cfe/trunk/bindings/python/clang/cindex.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/cindex.py?rev=313913&r1=313912&r2=313913&view=diff
==
--- cfe/trunk/bindings/python/clang/cindex.py (original)
+++ cfe/trunk/bindings/python/clang/cindex.py Thu Sep 21 13:48:43 2017
@@ -3216,6 +3216,7 @@ class Token(Structure):
 def cursor(self):
 """The Cursor this Token corresponds to."""
 cursor = Cursor()
+cursor._tu = self._tu
 
 conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor))
 

Modified: cfe/trunk/bindings/python/tests/cindex/test_cursor.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/tests/cindex/test_cursor.py?rev=313913&r1=313912&r2=313913&view=diff
==
--- cfe/trunk/bindings/python/tests/cindex/test_cursor.py (original)
+++ cfe/trunk/bindings/python/tests/cindex/test_cursor.py Thu Sep 21 13:48:43 
2017
@@ -395,6 +395,28 @@ def test_get_tokens():
 assert tokens[0].spelling == 'int'
 assert tokens[1].spelling == 'foo'
 
+def test_get_token_cursor():
+"""Ensure we can map tokens to cursors."""
+tu = get_tu('class A {}; int foo(A var = A());', lang='cpp')
+foo = get_cursor(tu, 'foo')
+
+for cursor in foo.walk_preorder():
+if cursor.kind.is_expression() and not cursor.kind.is_statement():
+break
+else:
+assert False, "Could not find default value expression"
+
+tokens = list(cursor.get_tokens())
+assert len(tokens) == 4, [t.spelling for t in tokens]
+assert tokens[0].spelling == '='
+assert tokens[1].spelling == 'A'
+assert tokens[2].spelling == '('
+assert tokens[3].spelling == ')'
+t_cursor = tokens[1].cursor
+assert t_cursor.kind == CursorKind.TYPE_REF
+r_cursor = t_cursor.referenced # should not raise an exception
+assert r_cursor.kind == CursorKind.CLASS_DECL
+
 def test_get_arguments():
 tu = get_tu('void foo(int i, int j);')
 foo = get_cursor(tu, 'foo')


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r330557 - [python bindings] Fix Cursor.result_type for ObjC method declarations - Bug 36677

2018-04-22 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Sun Apr 22 13:51:05 2018
New Revision: 330557

URL: http://llvm.org/viewvc/llvm-project?rev=330557&view=rev
Log:
[python bindings] Fix Cursor.result_type for ObjC method declarations - Bug 
36677

Summary:
In cindex.py, Cursor.result_type called into the wrong libclang
function, causing cursors for ObjC method declarations to return invalid
result types. Fixes Bug 36677.

Reviewers: jbcoe, rsmith

Reviewed By: jbcoe

Subscribers: cfe-commits, llvm-commits

Differential Revision: https://reviews.llvm.org/D45671

Patch by kjteske (Kyle Teske).

Modified:
cfe/trunk/bindings/python/clang/cindex.py
cfe/trunk/bindings/python/tests/cindex/test_cursor.py

Modified: cfe/trunk/bindings/python/clang/cindex.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/cindex.py?rev=330557&r1=330556&r2=330557&view=diff
==
--- cfe/trunk/bindings/python/clang/cindex.py (original)
+++ cfe/trunk/bindings/python/clang/cindex.py Sun Apr 22 13:51:05 2018
@@ -1644,7 +1644,7 @@ class Cursor(Structure):
 def result_type(self):
 """Retrieve the Type of the result for this Cursor."""
 if not hasattr(self, '_result_type'):
-self._result_type = conf.lib.clang_getResultType(self.type)
+self._result_type = conf.lib.clang_getCursorResultType(self)
 
 return self._result_type
 
@@ -3568,6 +3568,11 @@ functionList = [
[Cursor, c_uint, c_uint],
SourceRange),
 
+  ("clang_getCursorResultType",
+   [Cursor],
+   Type,
+   Type.from_result),
+
   ("clang_getCursorSemanticParent",
[Cursor],
Cursor,

Modified: cfe/trunk/bindings/python/tests/cindex/test_cursor.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/tests/cindex/test_cursor.py?rev=330557&r1=330556&r2=330557&view=diff
==
--- cfe/trunk/bindings/python/tests/cindex/test_cursor.py (original)
+++ cfe/trunk/bindings/python/tests/cindex/test_cursor.py Sun Apr 22 13:51:05 
2018
@@ -429,6 +429,18 @@ class TestCursor(unittest.TestCase):
 t = foo.result_type
 self.assertEqual(t.kind, TypeKind.INT)
 
+def test_result_type_objc_method_decl(self):
+code = """\
+@interface Interface : NSObject
+-(void)voidMethod;
+@end
+"""
+tu = get_tu(code, lang='objc')
+cursor = get_cursor(tu, 'voidMethod')
+result_type = cursor.result_type
+self.assertEqual(cursor.kind, CursorKind.OBJC_INSTANCE_METHOD_DECL)
+self.assertEqual(result_type.kind, TypeKind.VOID)
+
 def test_availability(self):
 tu = get_tu('class A { A(A const&) = delete; };', lang='cpp')
 


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r330772 - [clang-tidy] Improve bugprone-unused-return-value check

2018-04-24 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Tue Apr 24 14:25:16 2018
New Revision: 330772

URL: http://llvm.org/viewvc/llvm-project?rev=330772&view=rev
Log:
[clang-tidy] Improve bugprone-unused-return-value check

Summary:
Add support for checking class template member functions.

Also add the following functions to be checked by default:

- std::unique_ptr::release
- std::basic_string::empty
- std::vector::empty

Reviewers: alexfh, hokein, aaron.ballman, ilya-biryukov

Reviewed By: aaron.ballman

Subscribers: jbcoe, xazax.hun, cfe-commits

Tags: #clang-tools-extra

Differential Revision: https://reviews.llvm.org/D45891

Patch by khuttun (Kalle Huttunen)

Modified:
clang-tools-extra/trunk/clang-tidy/bugprone/UnusedReturnValueCheck.cpp

clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-unused-return-value.rst

clang-tools-extra/trunk/test/clang-tidy/bugprone-unused-return-value-custom.cpp
clang-tools-extra/trunk/test/clang-tidy/bugprone-unused-return-value.cpp

Modified: clang-tools-extra/trunk/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/bugprone/UnusedReturnValueCheck.cpp?rev=330772&r1=330771&r2=330772&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/bugprone/UnusedReturnValueCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/bugprone/UnusedReturnValueCheck.cpp Tue 
Apr 24 14:25:16 2018
@@ -19,14 +19,32 @@ namespace clang {
 namespace tidy {
 namespace bugprone {
 
+namespace {
+
+// Matches functions that are instantiated from a class template member 
function
+// matching InnerMatcher. Functions not instantiated from a class template
+// member function are matched directly with InnerMatcher.
+AST_MATCHER_P(FunctionDecl, isInstantiatedFrom, Matcher,
+  InnerMatcher) {
+  FunctionDecl *InstantiatedFrom = Node.getInstantiatedFromMemberFunction();
+  return InnerMatcher.matches(InstantiatedFrom ? *InstantiatedFrom : Node,
+  Finder, Builder);
+}
+
+} // namespace
+
 UnusedReturnValueCheck::UnusedReturnValueCheck(llvm::StringRef Name,
ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
-  CheckedFunctions(Options.get("CheckedFunctions", "::std::async;"
-   "::std::launder;"
-   "::std::remove;"
-   "::std::remove_if;"
-   "::std::unique")) {}
+  CheckedFunctions(Options.get("CheckedFunctions",
+   "::std::async;"
+   "::std::launder;"
+   "::std::remove;"
+   "::std::remove_if;"
+   "::std::unique;"
+   "::std::unique_ptr::release;"
+   "::std::basic_string::empty;"
+   "::std::vector::empty")) {}
 
 void UnusedReturnValueCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
   Options.store(Opts, "CheckedFunctions", CheckedFunctions);
@@ -35,11 +53,11 @@ void UnusedReturnValueCheck::storeOption
 void UnusedReturnValueCheck::registerMatchers(MatchFinder *Finder) {
   auto FunVec = utils::options::parseStringList(CheckedFunctions);
   auto MatchedCallExpr = expr(ignoringImplicit(ignoringParenImpCasts(
-  callExpr(
-  callee(functionDecl(
-  // Don't match void overloads of checked functions.
-  unless(returns(voidType())), hasAnyName(std::vector(
-   FunVec.begin(), 
FunVec.end())
+  callExpr(callee(functionDecl(
+   // Don't match void overloads of checked functions.
+   unless(returns(voidType())),
+   isInstantiatedFrom(hasAnyName(
+   std::vector(FunVec.begin(), 
FunVec.end()))
   .bind("match";
 
   auto UnusedInCompoundStmt =

Modified: 
clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-unused-return-value.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-unused-return-value.rst?rev=330772&r1=330771&r2=330772&view=diff
==
--- 
clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-unused-return-value.rst 
(original)
+++ 
clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-unused-return-value.rst 
Tue Apr 24 14:25:16 2018
@@ -11,7 +11,7 @@ Options
 .. option:: CheckedFunctions
 
Semicolon-separated list of functions to check. Defaults to
-   
``::std::async;::std::launder;::std::remove;::std::remove_if;::std::unique``.
+   
``::std::async;::std::launder;::std::remove

Re: clang_getIncudedFile python binding fix

2018-05-03 Thread Jonathan Coe via cfe-commits
This patch looks good to me - great work!

If you can upload it to https://reviews.llvm.org

then I can review and merge it for you once it's approved.

regards,

Jon

On 3 May 2018 at 08:55, József LÁZ via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Hi all,
>
> I made fix in clang’s python bindings. The binding for C api’s
> clang_getIncludedFile was not implemented. The patch was made on trunk.
>
> I believe this bugticket is related: https://bugs.llvm.org/show_
> bug.cgi?id=15223
>
> Any thoughts?
>
>
>
> József Láz
> --
> This message, including its attachments, is confidential and the property
> of NNG Llc. For more information please read NNG's email policy here:
> https://www.nng.com/email-policy/
> By responding to this email you accept the email policy.
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 9520bf1 - [clang-format] Update GoogleStyle for C# code to match Google's internal C# style guide

2020-06-04 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-06-04T15:48:00+01:00
New Revision: 9520bf146dd3baae8608755d7de0855db4664c77

URL: 
https://github.com/llvm/llvm-project/commit/9520bf146dd3baae8608755d7de0855db4664c77
DIFF: 
https://github.com/llvm/llvm-project/commit/9520bf146dd3baae8608755d7de0855db4664c77.diff

LOG: [clang-format] Update GoogleStyle for C# code to match Google's internal 
C# style guide

Summary: Google's C# style guide is at 
https://google.github.io/styleguide/csharp-style.html

Reviewers: krasimir, MyDeveloperDay, sammccall

Reviewed By: MyDeveloperDay

Subscribers: cfe-commits, klimek

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D79715

Added: 


Modified: 
clang/lib/Format/Format.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index f3743921d52e..1f7a8029bac0 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -14,6 +14,7 @@
 
 #include "clang/Format/Format.h"
 #include "AffectedRangeManager.h"
+#include "BreakableToken.h"
 #include "ContinuationIndenter.h"
 #include "FormatInternal.h"
 #include "FormatTokenLexer.h"
@@ -1068,6 +1069,12 @@ FormatStyle getGoogleStyle(FormatStyle::LanguageKind 
Language) {
 // #imports, etc.)
 GoogleStyle.IncludeStyle.IncludeBlocks =
 tooling::IncludeStyle::IBS_Preserve;
+  } else if (Language == FormatStyle::LK_CSharp) {
+GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
+GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
+GoogleStyle.BreakStringLiterals = false;
+GoogleStyle.ColumnLimit = 100;
+GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
   }
 
   return GoogleStyle;

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 5567e19e5bdd..dd2ed292ccd8 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -583,8 +583,7 @@ TEST_F(FormatTestCSharp, CSharpNamedArguments) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
 
   verifyFormat(R"(//
-PrintOrderDetails(orderNum: 31, productName: "Red Mug",
-  sellerName: "Gift Shop");)",
+PrintOrderDetails(orderNum: 31, productName: "Red Mug", sellerName: "Gift 
Shop");)",
Style);
 
   // Ensure that trailing comments do not cause problems.
@@ -641,8 +640,7 @@ class TimePeriod {
 get { return _seconds / 3600; }
 set {
   if (value < 0 || value > 24)
-throw new ArgumentOutOfRangeException(
-$"{nameof(value)} must be between 0 and 24.");
+throw new ArgumentOutOfRangeException($"{nameof(value)} must be 
between 0 and 24.");
   _seconds = value * 3600;
 }
   }
@@ -755,7 +753,9 @@ TEST_F(FormatTestCSharp, CSharpNullableTypes) {
 
   verifyFormat(R"(//
 public class A {
-  void foo() { int? value = some.bar(); }
+  void foo() {
+int? value = some.bar();
+  }
 })",
Style); // int? is nullable not a conditional expression.
 
@@ -800,16 +800,15 @@ class Dictionary
 where TKey : IComparable
 where TVal : IMyInterface {
   public void MyMethod(T t)
-  where T : IMyInterface { doThing(); }
+  where T : IMyInterface {
+doThing();
+  }
 })",
Style);
 
   verifyFormat(R"(//
 class ItemFactory
-where T : new(),
-  IAnInterface,
-  IAnotherInterface,
-  IAnotherInterfaceStill {})",
+where T : new(), IAnInterface, IAnotherInterface, 
IAnotherInterfaceStill {})",
Style);
 
   Style.ColumnLimit = 50; // Force lines to be wrapped.



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] a679499 - [clang-format] treat 'lock' as a keyword for C# code

2020-06-08 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-06-08T13:31:22+01:00
New Revision: a67949913a6b19860fdc616da2fad00bf7beb3f8

URL: 
https://github.com/llvm/llvm-project/commit/a67949913a6b19860fdc616da2fad00bf7beb3f8
DIFF: 
https://github.com/llvm/llvm-project/commit/a67949913a6b19860fdc616da2fad00bf7beb3f8.diff

LOG: [clang-format] treat 'lock' as a keyword for C# code

Summary: This will put a space in `lock (process)` when spaces are required 
after keywords.

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D81255

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 9f2580367d0f..6e8dc690eeb9 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3080,7 +3080,8 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
 
 // space between keywords and paren e.g. "using ("
 if (Right.is(tok::l_paren))
-  if (Left.isOneOf(tok::kw_using, Keywords.kw_async, Keywords.kw_when))
+  if (Left.isOneOf(tok::kw_using, Keywords.kw_async, Keywords.kw_when,
+   Keywords.kw_lock))
 return Style.SpaceBeforeParens == FormatStyle::SBPO_ControlStatements 
||
spaceRequiredBeforeParens(Right);
   } else if (Style.Language == FormatStyle::LK_JavaScript) {

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index dd2ed292ccd8..584b8aea383f 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -741,6 +741,9 @@ foreach ((A a, B b) in someList) {
 })",
Style);
 
+  // space after lock in `lock (processes)`.
+  verifyFormat("lock (process)", Style);
+
   Style.SpacesInSquareBrackets = true;
   verifyFormat(R"(private float[ , ] Values;)", Style);
   verifyFormat(R"(string dirPath = args?[ 0 ];)", Style);



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 7117066 - [clang-format] Brace breaking for C# lambdas

2020-06-09 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-06-09T10:20:01+01:00
New Revision: 7117066bd6182f53ec9f97d2e5e81de27c2e0db0

URL: 
https://github.com/llvm/llvm-project/commit/7117066bd6182f53ec9f97d2e5e81de27c2e0db0
DIFF: 
https://github.com/llvm/llvm-project/commit/7117066bd6182f53ec9f97d2e5e81de27c2e0db0.diff

LOG: [clang-format] Brace breaking for C# lambdas

Reviewers: krasimir, MyDeveloperDay

Reviewed By: krasimir

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D81394

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index b8da2c23b55a..0d488d1dda52 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1459,8 +1459,14 @@ void UnwrappedLineParser::parseStructuralElement() {
   // followed by a curly.
   if (FormatTok->is(TT_JsFatArrow)) {
 nextToken();
-if (FormatTok->is(tok::l_brace))
+if (FormatTok->is(tok::l_brace)) {
+  // C# may break after => if the next character is a newline.
+  if (Style.isCSharp() && Style.BraceWrapping.AfterFunction == true) {
+// calling `addUnwrappedLine()` here causes odd parsing errors.
+FormatTok->MustBreakBefore = true;
+  }
   parseChildBlock();
+}
 break;
   }
 

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 584b8aea383f..bcf2c7a52141 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -525,6 +525,33 @@ var x = foo(className, $@"some code:
   EXPECT_EQ(Code, format(Code, Style));
 }
 
+TEST_F(FormatTestCSharp, CSharpLambdas) {
+  FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_CSharp);
+  FormatStyle MicrosoftStyle = getMicrosoftStyle(FormatStyle::LK_CSharp);
+
+  verifyFormat(R"(//
+class MyClass {
+  Action greet = name => {
+string greeting = $"Hello {name}!";
+Console.WriteLine(greeting);
+  };
+})",
+   GoogleStyle);
+
+  // Microsoft Style:
+  // 
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions#statement-lambdas
+  verifyFormat(R"(//
+class MyClass
+{
+Action greet = name =>
+{
+string greeting = $"Hello {name}!";
+Console.WriteLine(greeting);
+};
+})",
+   MicrosoftStyle);
+}
+
 TEST_F(FormatTestCSharp, CSharpObjectInitializers) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
 



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f22b072 - [clang-format] Microsoft style fixes for C# properties

2020-06-09 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-06-09T14:50:34+01:00
New Revision: f22b0727fe767cc8da5e0c59f4e957a05472ffa7

URL: 
https://github.com/llvm/llvm-project/commit/f22b0727fe767cc8da5e0c59f4e957a05472ffa7
DIFF: 
https://github.com/llvm/llvm-project/commit/f22b0727fe767cc8da5e0c59f4e957a05472ffa7.diff

LOG: [clang-format] Microsoft style fixes for C# properties

Summary:
There should be no line break before the opening brace for Microsoft style 
property accessors when the accessor is a simple `{ get; set }`.

https://docs.microsoft.com/en-us/dotnet/csharp/properties

Reviewers: krasimir, MyDeveloperDay

Reviewed By: krasimir

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D81467

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 0d488d1dda52..cf9673d51617 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1542,7 +1542,7 @@ bool UnwrappedLineParser::tryToParsePropertyAccessor() {
   // Try to parse the property accessor:
   // 
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
   Tokens->setPosition(StoredPosition);
-  if (Style.BraceWrapping.AfterFunction == true)
+  if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction == true)
 addUnwrappedLine();
   nextToken();
   do {

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index bcf2c7a52141..a2c551e5c25e 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -245,13 +245,11 @@ TEST_F(FormatTestCSharp, Attributes) {
"}");
 
   verifyFormat("[TestMethod]\n"
-   "public string Host\n"
-   "{ set; get; }");
+   "public string Host { set; get; }");
 
   verifyFormat("[TestMethod(\"start\", HelpText = \"Starts the server "
"listening on provided host\")]\n"
-   "public string Host\n"
-   "{ set; get; }");
+   "public string Host { set; get; }");
 
   verifyFormat(
   "[DllImport(\"Hello\", EntryPoint = \"hello_world\")]\n"
@@ -710,13 +708,6 @@ class MyClass {
   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
   Style.BraceWrapping.AfterFunction = true;
 
-  verifyFormat(R"(//
-public class SaleItem {
-  public decimal Price
-  { get; set; }
-})",
-   Style);
-
   verifyFormat(R"(//
 class TimePeriod {
   public double Hours
@@ -730,6 +721,17 @@ class TimePeriod {
   }
 })",
Style);
+ 
+  // Microsoft style trivial property accessors have no line break before the
+  // opening brace.
+  auto MicrosoftStyle = getMicrosoftStyle(FormatStyle::LK_CSharp);
+  verifyFormat(R"(//
+public class SaleItem
+{
+public decimal Price { get; set; }
+})",
+   MicrosoftStyle);
+
 }
 
 TEST_F(FormatTestCSharp, CSharpSpaces) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 07c1978 - [clang-format] Do not interpret C# deconstruction in a foreach as a cast

2020-04-16 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-04-16T14:22:34+01:00
New Revision: 07c1978b15b4e9daefbf358e6fd185b5aa269f98

URL: 
https://github.com/llvm/llvm-project/commit/07c1978b15b4e9daefbf358e6fd185b5aa269f98
DIFF: 
https://github.com/llvm/llvm-project/commit/07c1978b15b4e9daefbf358e6fd185b5aa269f98.diff

LOG: [clang-format] Do not interpret C# deconstruction in a foreach as a cast

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits, MyDeveloperDay

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D78295

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 8204623645a4..6532f8108f08 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1775,6 +1775,10 @@ class AnnotatingParser {
 if (Tok.Next->is(tok::question))
   return false;
 
+// `foreach((A a, B b) in someList)` should not be seen as a cast.
+if (Tok.Next->is(Keywords.kw_in) && Style.isCSharp())
+  return false;
+
 // Functions which end with decorations like volatile, noexcept are 
unlikely
 // to be casts.
 if (Tok.Next->isOneOf(tok::kw_noexcept, tok::kw_volatile, tok::kw_const,

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index b0e4e76cefe7..67571d3909bf 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -624,6 +624,7 @@ TEST_F(FormatTestCSharp, CSharpSpaces) {
   Style.SpaceBeforeCpp11BracedList = true;
   Style.Cpp11BracedListStyle = false;
   Style.SpacesInContainerLiterals = false;
+  Style.SpaceAfterCStyleCast = false;
 
   verifyFormat(R"(new Car { "Door", 0.1 })", Style);
   verifyFormat(R"(new Car { 0.1, "Door" })", Style);
@@ -642,6 +643,12 @@ TEST_F(FormatTestCSharp, CSharpSpaces) {
 
   verifyFormat(R"(char[,,] rawCharArray = MakeCharacterGrid();)", Style);
 
+  // Not seen as a C-style cast.
+  verifyFormat(R"(//
+foreach ((A a, B b) in someList) {
+})",
+   Style);
+
   Style.SpacesInSquareBrackets = true;
   verifyFormat(R"(private float[ , ] Values;)", Style);
   verifyFormat(R"(string dirPath = args?[ 0 ];)", Style);



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 2f9fc8d - [clang-format] Handle C# property accessors when parsing lines

2020-04-23 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-04-23T13:25:10+01:00
New Revision: 2f9fc8d9718fb19c04e169f7ba7ae26ea6a05085

URL: 
https://github.com/llvm/llvm-project/commit/2f9fc8d9718fb19c04e169f7ba7ae26ea6a05085
DIFF: 
https://github.com/llvm/llvm-project/commit/2f9fc8d9718fb19c04e169f7ba7ae26ea6a05085.diff

LOG: [clang-format] Handle C# property accessors when parsing lines

Summary:
Improve C# `{ get; set; } = default;` formatting by handling it in the 
UnwrappedLineParser rather than trying to merge lines later.

Remove old logic to merge lines.

Update tests as formatting output has changed (as intended).

Reviewers: krasimir, MyDeveloperDay

Reviewed By: krasimir

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D78642

Added: 


Modified: 
clang/lib/Format/UnwrappedLineFormatter.cpp
clang/lib/Format/UnwrappedLineParser.cpp
clang/lib/Format/UnwrappedLineParser.h
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index c16c16c4f26a..e86f9ecb4b90 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -294,13 +294,6 @@ class LineJoiner {
   }
 }
 
-// Try to merge a CSharp property declaration like `{ get; private set }`.
-if (Style.isCSharp()) {
-  unsigned CSPA = tryMergeCSharpPropertyAccessor(I, E, Limit);
-  if (CSPA > 0)
-return CSPA;
-}
-
 // Try to merge a function block with left brace unwrapped
 if (TheLine->Last->is(TT_FunctionLBrace) &&
 TheLine->First != TheLine->Last) {
@@ -430,64 +423,6 @@ class LineJoiner {
 return 0;
   }
 
-  // true for lines of the form [access-modifier] {get,set} [;]
-  bool isMergeablePropertyAccessor(const AnnotatedLine *Line) {
-auto *Tok = Line->First;
-if (!Tok)
-  return false;
-
-if (Tok->isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private,
- Keywords.kw_internal))
-  Tok = Tok->Next;
-
-if (!Tok || (Tok->TokenText != "get" && Tok->TokenText != "set"))
-  return false;
-
-if (!Tok->Next || Tok->Next->is(tok::semi))
-  return true;
-
-return false;
-  }
-
-  unsigned tryMergeCSharpPropertyAccessor(
-  SmallVectorImpl::const_iterator I,
-  SmallVectorImpl::const_iterator E, unsigned /*Limit*/) {
-
-auto CurrentLine = I;
-// Does line start with `{`
-if (!(*CurrentLine)->Last || 
(*CurrentLine)->Last->isNot(TT_FunctionLBrace))
-  return 0;
-++CurrentLine;
-
-unsigned MergedLines = 0;
-bool HasGetOrSet = false;
-while (CurrentLine != E) {
-  bool LineIsGetOrSet = isMergeablePropertyAccessor(*CurrentLine);
-  HasGetOrSet = HasGetOrSet || LineIsGetOrSet;
-  if (LineIsGetOrSet) {
-++CurrentLine;
-++MergedLines;
-continue;
-  }
-  auto *Tok = (*CurrentLine)->First;
-  if (Tok && Tok->is(tok::r_brace)) {
-++CurrentLine;
-++MergedLines;
-// See if the next line is a default value so that we can merge `{ get;
-// set } = 0`
-if (CurrentLine != E && (*CurrentLine)->First &&
-(*CurrentLine)->First->is(tok::equal)) {
-  ++MergedLines;
-}
-break;
-  }
-  // Not a '}' or a get/set line so do not merege lines.
-  return 0;
-}
-
-return HasGetOrSet ? MergedLines : 0;
-  }
-
   unsigned
   tryMergeSimplePPDirective(SmallVectorImpl::const_iterator I,
 SmallVectorImpl::const_iterator E,

diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 18899314512e..c84c951fcaa8 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1334,7 +1334,7 @@ void UnwrappedLineParser::parseStructuralElement() {
 parseChildBlock();
   break;
 case tok::l_brace:
-  if (!tryToParseBracedList()) {
+  if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) {
 // A block outside of parentheses must be the last part of a
 // structural element.
 // FIXME: Figure out cases where this is not true, and add projections
@@ -1487,6 +1487,75 @@ void UnwrappedLineParser::parseStructuralElement() {
   } while (!eof());
 }
 
+bool UnwrappedLineParser::tryToParsePropertyAccessor() {
+  assert(FormatTok->is(tok::l_brace));
+  if (!Style.isCSharp())
+return false;
+  // See if it's a property accessor.
+  if (FormatTok->Previous->isNot(tok::identifier))
+return false;
+
+  // Try to parse the property accessor braces and contents:
+  // `{ get; set; } = new MyType(defaultValue);`
+  //  ^
+  //
+  // Record the current tokenPosition so that we can advance and
+  // reset the current token. `Next` is not set yet s

[clang] 44ad58b - [clang-format] Improved parser for C# properties

2020-04-28 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-04-28T14:11:09+01:00
New Revision: 44ad58b9915d29eb48be4f89368be6d30d174825

URL: 
https://github.com/llvm/llvm-project/commit/44ad58b9915d29eb48be4f89368be6d30d174825
DIFF: 
https://github.com/llvm/llvm-project/commit/44ad58b9915d29eb48be4f89368be6d30d174825.diff

LOG: [clang-format] Improved parser for C# properties

Summary:
Added some examples of properties from Microsoft documentation as test cases.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties

Configuration support will be added in a follow up patch to address whether 
automatic properties are formatted as

```
Type MyType { get; set }
```

or

```
Type MyType
{ get; set }
```

Reviewers: krasimir, MyDeveloperDay

Reviewed By: krasimir

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D78915

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index fdae725d625b..4734ff16921b 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -13,6 +13,7 @@
 
//===--===//
 
 #include "UnwrappedLineParser.h"
+#include "FormatToken.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
@@ -1495,9 +1496,7 @@ bool UnwrappedLineParser::tryToParsePropertyAccessor() {
   if (FormatTok->Previous->isNot(tok::identifier))
 return false;
 
-  // Try to parse the property accessor braces and contents:
-  // `{ get; set; } = new MyType(defaultValue);`
-  //  ^
+  // See if we are inside a property accessor.
   //
   // Record the current tokenPosition so that we can advance and
   // reset the current token. `Next` is not set yet so we need
@@ -1505,7 +1504,11 @@ bool UnwrappedLineParser::tryToParsePropertyAccessor() {
   unsigned int StoredPosition = Tokens->getPosition();
   FormatToken *Tok = Tokens->getNextToken();
 
+  // A trivial property accessor is of the form:
+  // { [ACCESS_SPECIFIER] [get]; [ACCESS_SPECIFIER] [set] }
+  // Track these as they do not require line breaks to be introduced.
   bool HasGetOrSet = false;
+  bool IsTrivialPropertyAccessor = true;
   while (!eof()) {
 if (Tok->isOneOf(tok::semi, tok::kw_public, tok::kw_private,
  tok::kw_protected, Keywords.kw_internal, Keywords.kw_get,
@@ -1515,10 +1518,9 @@ bool UnwrappedLineParser::tryToParsePropertyAccessor() {
   Tok = Tokens->getNextToken();
   continue;
 }
-if (Tok->is(tok::r_brace))
-  break;
-Tokens->setPosition(StoredPosition);
-return false;
+if (Tok->isNot(tok::r_brace))
+  IsTrivialPropertyAccessor = false;
+break;
   }
 
   if (!HasGetOrSet) {
@@ -1526,33 +1528,51 @@ bool UnwrappedLineParser::tryToParsePropertyAccessor() {
 return false;
   }
 
+  // Try to parse the property accessor:
+  // 
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
   Tokens->setPosition(StoredPosition);
-  while (FormatTok->isNot(tok::r_brace)) {
-nextToken();
-  }
-
-  // Try to parse (optional) assignment to default value:
-  // `{ get; set; } = new MyType(defaultValue);`
-  //^^^
-  // There may be some very complicated expressions inside default value
-  // assignment, the simple parse block below will not handle them.
-  // The parse block below would need extending to handle opening parens etc.
-  StoredPosition = Tokens->getPosition();
-  Tok = Tokens->getNextToken();
-  bool NextTokenIsEqual = Tok->is(tok::equal);
-  Tokens->setPosition(StoredPosition);
-
-  if (NextTokenIsEqual) {
-do {
+  nextToken();
+  do {
+switch (FormatTok->Tok.getKind()) {
+case tok::r_brace:
   nextToken();
-  if (FormatTok->is(tok::semi))
+  if (FormatTok->is(tok::equal)) {
+while (!eof() && FormatTok->isNot(tok::semi))
+  nextToken();
+nextToken();
+  }
+  addUnwrappedLine();
+  return true;
+case tok::l_brace:
+  ++Line->Level;
+  parseBlock(/*MustBeDeclaration=*/true);
+  addUnwrappedLine();
+  --Line->Level;
+  break;
+case tok::equal:
+  if (FormatTok->is(TT_JsFatArrow)) {
+++Line->Level;
+do {
+  nextToken();
+} while (!eof() && FormatTok->isNot(tok::semi));
+nextToken();
+addUnwrappedLine();
+--Line->Level;
 break;
-} while (!eof());
-  }
+  }
+  nextToken();
+  break;
+default:
+  if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_set) &&
+  !IsTrivialPropertyAccessor) {
+// Non-trivial get/set 

[clang] 7443f86 - [clang-format] insert space after C# keyword var in var (key, value)

2020-04-28 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-04-28T17:31:40+01:00
New Revision: 7443f86eabbae0fdef90fe796c3956ed65238e99

URL: 
https://github.com/llvm/llvm-project/commit/7443f86eabbae0fdef90fe796c3956ed65238e99
DIFF: 
https://github.com/llvm/llvm-project/commit/7443f86eabbae0fdef90fe796c3956ed65238e99.diff

LOG: [clang-format] insert space after C# keyword var in var (key, value)

Reviewers: krasimir, MyDeveloperDay

Reviewed By: MyDeveloperDay

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D79008

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 3e441100a2f0..61386cef990a 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3053,6 +3053,10 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
 if (Left.is(TT_CSharpNullConditionalLSquare))
   return Style.SpacesInSquareBrackets;
 
+// space after var in `var (key, value)`
+if (Left.is(Keywords.kw_var) && Right.is(tok::l_paren))
+  return true;
+
 // space between keywords and paren e.g. "using ("
 if (Right.is(tok::l_paren))
   if (Left.isOneOf(tok::kw_using, Keywords.kw_async, Keywords.kw_when))

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 75112a786867..91962ef12631 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -698,6 +698,7 @@ TEST_F(FormatTestCSharp, CSharpSpaces) {
   verifyFormat(R"(Result this[Index x] => Foo(x);)", Style);
 
   verifyFormat(R"(char[,,] rawCharArray = MakeCharacterGrid();)", Style);
+  verifyFormat(R"(var (key, value))", Style);
 
   // Not seen as a C-style cast.
   verifyFormat(R"(//



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 015bca3 - [clang-format] C# property formatting can be controlled by config options

2020-04-28 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-04-28T17:35:33+01:00
New Revision: 015bca3e67cbb88f74f01fb5ae4e46392bec6416

URL: 
https://github.com/llvm/llvm-project/commit/015bca3e67cbb88f74f01fb5ae4e46392bec6416
DIFF: 
https://github.com/llvm/llvm-project/commit/015bca3e67cbb88f74f01fb5ae4e46392bec6416.diff

LOG: [clang-format] C# property formatting can be controlled by config options

Summary:
Allow brace wrapping in C# property accessors to be controlled by configuration 
options.

Add new tests and revert old test results for MS style to their old state (as 
intended).

`FormatStyle.BraceWrapping.AfterFunction = true;` will change automatic 
property formatting from

```
Type MyType { get; set }
```

to

```
Type MyType
{ get; set }
```

Reviewers: krasimir, MyDeveloperDay

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D79000

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 4734ff16921b..e9e56e80814c 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1531,6 +1531,8 @@ bool UnwrappedLineParser::tryToParsePropertyAccessor() {
   // Try to parse the property accessor:
   // 
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
   Tokens->setPosition(StoredPosition);
+  if (Style.BraceWrapping.AfterFunction == true)
+addUnwrappedLine();
   nextToken();
   do {
 switch (FormatTok->Tok.getKind()) {

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 91962ef12631..550f5b493992 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -245,11 +245,13 @@ TEST_F(FormatTestCSharp, Attributes) {
"}");
 
   verifyFormat("[TestMethod]\n"
-   "public string Host { set; get; }");
+   "public string Host\n"
+   "{ set; get; }");
 
   verifyFormat("[TestMethod(\"start\", HelpText = \"Starts the server "
"listening on provided host\")]\n"
-   "public string Host { set; get; }");
+   "public string Host\n"
+   "{ set; get; }");
 
   verifyFormat(
   "[DllImport(\"Hello\", EntryPoint = \"hello_world\")]\n"
@@ -669,6 +671,32 @@ class MyClass {
 set => veryLongNamedField = value;
   } = VeryLongNamedTypeIndeed.Create(DefaultFirstArgument, 
DefaultSecondArgument,
  DefaultThirdArgument);
+})",
+   Style);
+
+  // Brace wrapping and single-lining of accessor can be controlled by config.
+  Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterFunction = true;
+
+  verifyFormat(R"(//
+public class SaleItem {
+  public decimal Price
+  { get; set; }
+})",
+   Style);
+
+  verifyFormat(R"(//
+class TimePeriod {
+  public double Hours
+  {
+get {
+  return _seconds / 3600;
+}
+set {
+  _seconds = value * 3600;
+}
+  }
 })",
Style);
 }



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 85ee97f - Revert "[clang-format] C# property formatting can be controlled by config options"

2020-04-28 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-04-28T17:41:17+01:00
New Revision: 85ee97fd894b2d0432dfaf20347e73f3e154ae97

URL: 
https://github.com/llvm/llvm-project/commit/85ee97fd894b2d0432dfaf20347e73f3e154ae97
DIFF: 
https://github.com/llvm/llvm-project/commit/85ee97fd894b2d0432dfaf20347e73f3e154ae97.diff

LOG: Revert "[clang-format] C# property formatting can be controlled by config 
options"

Committed in error without approval https://reviews.llvm.org/D79000

This reverts commit 015bca3e67cbb88f74f01fb5ae4e46392bec6416.

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index e9e56e80814c..4734ff16921b 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1531,8 +1531,6 @@ bool UnwrappedLineParser::tryToParsePropertyAccessor() {
   // Try to parse the property accessor:
   // 
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
   Tokens->setPosition(StoredPosition);
-  if (Style.BraceWrapping.AfterFunction == true)
-addUnwrappedLine();
   nextToken();
   do {
 switch (FormatTok->Tok.getKind()) {

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 550f5b493992..91962ef12631 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -245,13 +245,11 @@ TEST_F(FormatTestCSharp, Attributes) {
"}");
 
   verifyFormat("[TestMethod]\n"
-   "public string Host\n"
-   "{ set; get; }");
+   "public string Host { set; get; }");
 
   verifyFormat("[TestMethod(\"start\", HelpText = \"Starts the server "
"listening on provided host\")]\n"
-   "public string Host\n"
-   "{ set; get; }");
+   "public string Host { set; get; }");
 
   verifyFormat(
   "[DllImport(\"Hello\", EntryPoint = \"hello_world\")]\n"
@@ -671,32 +669,6 @@ class MyClass {
 set => veryLongNamedField = value;
   } = VeryLongNamedTypeIndeed.Create(DefaultFirstArgument, 
DefaultSecondArgument,
  DefaultThirdArgument);
-})",
-   Style);
-
-  // Brace wrapping and single-lining of accessor can be controlled by config.
-  Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
-  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
-  Style.BraceWrapping.AfterFunction = true;
-
-  verifyFormat(R"(//
-public class SaleItem {
-  public decimal Price
-  { get; set; }
-})",
-   Style);
-
-  verifyFormat(R"(//
-class TimePeriod {
-  public double Hours
-  {
-get {
-  return _seconds / 3600;
-}
-set {
-  _seconds = value * 3600;
-}
-  }
 })",
Style);
 }



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 5f104a8 - [clang-format] Add space between method modifier and a tuple return type in C#

2020-08-10 Thread Jonathan Coe via cfe-commits

Author: Łukasz Krawczyk
Date: 2020-08-10T14:00:33+01:00
New Revision: 5f104a809983aa3b90f75fb411a9c8472545d270

URL: 
https://github.com/llvm/llvm-project/commit/5f104a809983aa3b90f75fb411a9c8472545d270
DIFF: 
https://github.com/llvm/llvm-project/commit/5f104a809983aa3b90f75fb411a9c8472545d270.diff

LOG: [clang-format] Add space between method modifier and a tuple return type 
in C#

"public (string name, int age) methodTuple() {}" is now properly spaced

Patch by lukaszkrawc...@google.com

Reviewed By: jbcoe, krasimir

Differential Revision: https://reviews.llvm.org/D85016

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 6cbaf8a30812..11acb597aa40 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3115,6 +3115,16 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
Keywords.kw_lock))
 return Style.SpaceBeforeParens == FormatStyle::SBPO_ControlStatements 
||
spaceRequiredBeforeParens(Right);
+
+// space between method modifier and opening parenthesis of a tuple return
+// type
+if (Left.isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected,
+ tok::kw_virtual, tok::kw_extern, tok::kw_static,
+ Keywords.kw_internal, Keywords.kw_abstract,
+ Keywords.kw_sealed, Keywords.kw_override,
+ Keywords.kw_async, Keywords.kw_unsafe) &&
+Right.is(tok::l_paren))
+  return true;
   } else if (Style.Language == FormatStyle::LK_JavaScript) {
 if (Left.is(TT_JsFatArrow))
   return true;

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index a2c551e5c25e..ae4cdda1c845 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -777,6 +777,20 @@ foreach ((A a, B b) in someList) {
   verifyFormat(R"(private float[ , ] Values;)", Style);
   verifyFormat(R"(string dirPath = args?[ 0 ];)", Style);
   verifyFormat(R"(char[ ,, ] rawCharArray = MakeCharacterGrid();)", Style);
+
+  // Method returning tuple
+  verifyFormat(R"(public (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(private (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(protected (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(virtual (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(extern (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(static (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(internal (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(abstract (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(sealed (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(override (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(async (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(unsafe (string name, int age) methodTuple() {})", Style);
 }
 
 TEST_F(FormatTestCSharp, CSharpNullableTypes) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 047898c - [clang-format] C# always regards && as a binary operator

2020-05-05 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-05-05T14:05:00+01:00
New Revision: 047898c9aa1d8858fa0d87f7e349749222cabf22

URL: 
https://github.com/llvm/llvm-project/commit/047898c9aa1d8858fa0d87f7e349749222cabf22
DIFF: 
https://github.com/llvm/llvm-project/commit/047898c9aa1d8858fa0d87f7e349749222cabf22.diff

LOG: [clang-format] C# always regards && as a binary operator

Reviewers: krasimir, MyDeveloperDay

Reviewed By: MyDeveloperDay

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D79414

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 6671284a4734..734dbdc1b6f3 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1852,6 +1852,10 @@ class AnnotatingParser {
 if (Style.Language == FormatStyle::LK_JavaScript)
   return TT_BinaryOperator;
 
+// && in C# must be a binary operator.
+if (Style.isCSharp() && Tok.is(tok::ampamp))
+  return TT_BinaryOperator;
+
 const FormatToken *PrevToken = Tok.getPreviousNonComment();
 if (!PrevToken)
   return TT_UnaryOperator;

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index d8d992e091d9..6f0b1966767d 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -706,6 +706,9 @@ TEST_F(FormatTestCSharp, CSharpSpaces) {
   verifyFormat(R"(char[,,] rawCharArray = MakeCharacterGrid();)", Style);
   verifyFormat(R"(var (key, value))", Style);
 
+  // `&&` is not seen as a reference.
+  verifyFormat(R"(A == typeof(X) && someBool)", Style);
+
   // Not seen as a C-style cast.
   verifyFormat(R"(//
 foreach ((A a, B b) in someList) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 8fa743a - [clang-format] C# property formatting can be controlled by config options

2020-05-15 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-05-15T14:08:40+01:00
New Revision: 8fa743ab82027da443bac050e86b70bcdb78cbee

URL: 
https://github.com/llvm/llvm-project/commit/8fa743ab82027da443bac050e86b70bcdb78cbee
DIFF: 
https://github.com/llvm/llvm-project/commit/8fa743ab82027da443bac050e86b70bcdb78cbee.diff

LOG: [clang-format] C# property formatting can be controlled by config options

Summary:
Allow brace wrapping in C# property accessors to be controlled by configuration 
options.

Add new tests and revert old test results for Microsoft style to their previous 
state (as intended).

`FormatStyle.BraceWrapping.AfterFunction = true;` will change automatic 
property formatting from

```
Type MyType { get; set }
```

to

```
Type MyType
{ get; set }
```

Reviewers: krasimir, MyDeveloperDay

Reviewed By: krasimir, MyDeveloperDay

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D79000

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index b303758f1cb8..58206a06ea1a 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1531,6 +1531,8 @@ bool UnwrappedLineParser::tryToParsePropertyAccessor() {
   // Try to parse the property accessor:
   // 
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
   Tokens->setPosition(StoredPosition);
+  if (Style.BraceWrapping.AfterFunction == true)
+addUnwrappedLine();
   nextToken();
   do {
 switch (FormatTok->Tok.getKind()) {

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 6f0b1966767d..5567e19e5bdd 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -245,11 +245,13 @@ TEST_F(FormatTestCSharp, Attributes) {
"}");
 
   verifyFormat("[TestMethod]\n"
-   "public string Host { set; get; }");
+   "public string Host\n"
+   "{ set; get; }");
 
   verifyFormat("[TestMethod(\"start\", HelpText = \"Starts the server "
"listening on provided host\")]\n"
-   "public string Host { set; get; }");
+   "public string Host\n"
+   "{ set; get; }");
 
   verifyFormat(
   "[DllImport(\"Hello\", EntryPoint = \"hello_world\")]\n"
@@ -675,6 +677,32 @@ class MyClass {
 set => veryLongNamedField = value;
   } = VeryLongNamedTypeIndeed.Create(DefaultFirstArgument, 
DefaultSecondArgument,
  DefaultThirdArgument);
+})",
+   Style);
+
+  // Brace wrapping and single-lining of accessor can be controlled by config.
+  Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterFunction = true;
+
+  verifyFormat(R"(//
+public class SaleItem {
+  public decimal Price
+  { get; set; }
+})",
+   Style);
+
+  verifyFormat(R"(//
+class TimePeriod {
+  public double Hours
+  {
+get {
+  return _seconds / 3600;
+}
+set {
+  _seconds = value * 3600;
+}
+  }
 })",
Style);
 }



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 78e2a3c - [clang-format] Reflow long C# generic type constraints correctly

2020-03-23 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-23T13:38:21Z
New Revision: 78e2a3c678463caeec1524baa96cdeb6fcdb48be

URL: 
https://github.com/llvm/llvm-project/commit/78e2a3c678463caeec1524baa96cdeb6fcdb48be
DIFF: 
https://github.com/llvm/llvm-project/commit/78e2a3c678463caeec1524baa96cdeb6fcdb48be.diff

LOG: [clang-format] Reflow long C# generic type constraints correctly

Summary:
Align sequential generic type constraints on a type.

Indent sequential generic type constraints on different types as continuations.

Do not allow '(' and '<' within a generic type constraint to open new scopes.

Reviewers: krasimir

Subscribers: cfe-commits, MyDeveloperDay

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D76597

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/lib/Format/ContinuationIndenter.h
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 9a6d7877efaa..d2397dbfeb87 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -634,6 +634,7 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
 State.Stack.back().NoLineBreak = true;
 
   if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign &&
+  !State.Stack.back().IsCSharpGenericTypeConstraint &&
   Previous.opensScope() && Previous.isNot(TT_ObjCMethodExpr) &&
   (Current.isNot(TT_LineComment) || Previous.BlockKind == BK_BracedInit))
 State.Stack.back().Indent = State.Column + Spaces;
@@ -715,6 +716,8 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
   } else if (Previous.is(TT_InheritanceColon)) {
 State.Stack.back().Indent = State.Column;
 State.Stack.back().LastSpace = State.Column;
+  } else if (Current.is(TT_CSharpGenericTypeConstraintColon)) {
+State.Stack.back().ColonPos = State.Column;
   } else if (Previous.opensScope()) {
 // If a function has a trailing call, indent all parameters from the
 // opening parenthesis. This avoids confusing indents like:
@@ -924,7 +927,13 @@ unsigned ContinuationIndenter::addTokenOnNewLine(LineState 
&State,
 unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
   if (!State.NextToken || !State.NextToken->Previous)
 return 0;
+
   FormatToken &Current = *State.NextToken;
+
+  if (State.Stack.back().IsCSharpGenericTypeConstraint &&
+  Current.isNot(TT_CSharpGenericTypeConstraint))
+return State.Stack.back().ColonPos + 2;
+
   const FormatToken &Previous = *Current.Previous;
   // If we are continuing an expression, we want to use the continuation 
indent.
   unsigned ContinuationIndent =
@@ -1106,9 +1115,11 @@ unsigned 
ContinuationIndenter::moveStateToNextToken(LineState &State,
   assert(State.Stack.size());
   const FormatToken &Current = *State.NextToken;
 
+  if (Current.is(TT_CSharpGenericTypeConstraint))
+State.Stack.back().IsCSharpGenericTypeConstraint = true;
   if (Current.isOneOf(tok::comma, TT_BinaryOperator))
 State.Stack.back().NoLineBreakInOperand = false;
-  if (Current.is(TT_InheritanceColon))
+  if (Current.isOneOf(TT_InheritanceColon, 
TT_CSharpGenericTypeConstraintColon))
 State.Stack.back().AvoidBinPacking = true;
   if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
 if (State.Stack.back().FirstLessLess == 0)
@@ -1329,6 +1340,11 @@ void 
ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
   if (!Current.opensScope())
 return;
 
+  // Don't allow '<' or '(' in C# generic type constraints to start new scopes.
+  if (Current.isOneOf(tok::less, tok::l_paren) &&
+  State.Stack.back().IsCSharpGenericTypeConstraint)
+return;
+
   if (Current.MatchingParen && Current.BlockKind == BK_Block) {
 moveStateToNewBlock(State);
 return;
@@ -1393,6 +1409,7 @@ void 
ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
 (State.Line->Type == LT_ObjCDecl && ObjCBinPackProtocolList);
 
 AvoidBinPacking =
+(State.Stack.back().IsCSharpGenericTypeConstraint) ||
 (Style.Language == FormatStyle::LK_JavaScript && EndsInComma) ||
 (State.Line->MustBeDeclaration && !BinPackDeclaration) ||
 (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||

diff  --git a/clang/lib/Format/ContinuationIndenter.h 
b/clang/lib/Format/ContinuationIndenter.h
index 11df619e0f40..ab116d5468e8 100644
--- a/clang/lib/Format/ContinuationIndenter.h
+++ b/clang/lib/Format/ContinuationIndenter.h
@@ -208,7 +208,8 @@ struct ParenState {
 LastOperatorWrapped(true), ContainsLineBreak(false),
 ContainsUnwrappedBuilder(false), AlignColons(true),
 ObjCSelectorNameFound(false), HasMultipleNestedBlocks(false),
-NestedBlo

[clang] 5e1a026 - [clang-format] Do not indent C# array initialisers as continuations

2020-03-23 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-23T14:33:10Z
New Revision: 5e1a026c2d81e83e2b88cc6b6f27fbefbfe0de16

URL: 
https://github.com/llvm/llvm-project/commit/5e1a026c2d81e83e2b88cc6b6f27fbefbfe0de16
DIFF: 
https://github.com/llvm/llvm-project/commit/5e1a026c2d81e83e2b88cc6b6f27fbefbfe0de16.diff

LOG: [clang-format] Do not indent C# array initialisers as continuations

Summary: Flag '= {' as a braced init list when parsing C# code.

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits, MyDeveloperDay

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75760

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index e2a6389cb26d..d8202bd61458 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1460,6 +1460,11 @@ void UnwrappedLineParser::parseStructuralElement() {
 
   nextToken();
   if (FormatTok->Tok.is(tok::l_brace)) {
+// Block kind should probably be set to BK_BracedInit for any language.
+// C# needs this change to ensure that array initialisers and object
+// initialisers are indented the same way.
+if (Style.isCSharp())
+  FormatTok->BlockKind = BK_BracedInit;
 nextToken();
 parseBracedList();
   } else if (Style.Language == FormatStyle::LK_Proto &&
@@ -1652,7 +1657,7 @@ bool UnwrappedLineParser::tryToParseBracedList() {
 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
   tok::TokenKind ClosingBraceKind) {
   bool HasError = false;
-
+  
   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
   // replace this by using parseAssigmentExpression() inside.
   do {

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index a0f60ce799d2..0b770b4dfd3c 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -562,6 +562,17 @@ var myDict = new Dictionary {
Style);
 }
 
+TEST_F(FormatTestCSharp, CSharpArrayInitializers) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
+  
+  verifyFormat(R"(//
+private MySet[] setPoints = {
+  new Point(),
+  new Point(),
+};)",
+   Style);
+}
+
 TEST_F(FormatTestCSharp, CSharpNamedArguments) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
 



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 04336ad - [clang-format] No space inserted between commas in C#

2020-03-23 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-23T17:17:27Z
New Revision: 04336ada1756fea6ae0a6d86bd2d6bd35cdd19ad

URL: 
https://github.com/llvm/llvm-project/commit/04336ada1756fea6ae0a6d86bd2d6bd35cdd19ad
DIFF: 
https://github.com/llvm/llvm-project/commit/04336ada1756fea6ae0a6d86bd2d6bd35cdd19ad.diff

LOG: [clang-format] No space inserted between commas in C#

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits, MyDeveloperDay

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D76621

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 685749fc31ab..f2666a8bd171 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3015,6 +3015,10 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
 if (Right.is(TT_CSharpNullConditionalLSquare))
   return false;
 
+// No space between consecutive commas '[,,]'.
+if (Left.is(tok::comma) && Right.is(tok::comma))
+  return false;
+
 // Possible space inside `?[ 0 ]`.
 if (Left.is(TT_CSharpNullConditionalLSquare))
   return Style.SpacesInSquareBrackets;

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 0b770b4dfd3c..17b8e070c36a 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -640,9 +640,12 @@ TEST_F(FormatTestCSharp, CSharpSpaces) {
   verifyFormat(R"(private float[,] Values;)", Style);
   verifyFormat(R"(Result this[Index x] => Foo(x);)", Style);
 
+  verifyFormat(R"(char[,,] rawCharArray = MakeCharacterGrid();)", Style);
+
   Style.SpacesInSquareBrackets = true;
   verifyFormat(R"(private float[ , ] Values;)", Style);
   verifyFormat(R"(string dirPath = args?[ 0 ];)", Style);
+  verifyFormat(R"(char[ ,, ] rawCharArray = MakeCharacterGrid();)", Style);
 }
 
 TEST_F(FormatTestCSharp, CSharpNullableTypes) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] d1b412a - [clang-format] Correct line breaks in C# generic type constraints

2020-03-31 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-31T19:27:01+01:00
New Revision: d1b412ae389e4e30706c326ddec192ffb2e272cf

URL: 
https://github.com/llvm/llvm-project/commit/d1b412ae389e4e30706c326ddec192ffb2e272cf
DIFF: 
https://github.com/llvm/llvm-project/commit/d1b412ae389e4e30706c326ddec192ffb2e272cf.diff

LOG: [clang-format] Correct line breaks in C# generic type constraints

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D77064

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index d2397dbfeb87..ba42ba0ca050 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -346,6 +346,11 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
   Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) {
 return true;
   }
+  // Avoid producing inconsistent states by requiring breaks where they are not
+  // permitted for C# generic type constraints.
+  if (State.Stack.back().IsCSharpGenericTypeConstraint &&
+  Previous.isNot(TT_CSharpGenericTypeConstraintComma))
+return false;
   if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
(Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
 Style.isCpp() &&

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 8f40fc7bdcb6..a3cd4f42f8f8 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1060,15 +1060,20 @@ class AnnotatingParser {
   }
 
   void parseCSharpGenericTypeConstraint() {
+int OpenAngleBracketsCount = 0;
 while (CurrentToken) {
   if (CurrentToken->is(tok::less)) {
 // parseAngle is too greedy and will consume the whole line.
 CurrentToken->Type = TT_TemplateOpener;
+++OpenAngleBracketsCount;
 next();
   } else if (CurrentToken->is(tok::greater)) {
 CurrentToken->Type = TT_TemplateCloser;
+--OpenAngleBracketsCount;
 next();
-  } else if (CurrentToken->is(tok::comma)) {
+  } else if (CurrentToken->is(tok::comma) && OpenAngleBracketsCount == 0) {
+// We allow line breaks after GenericTypeConstraintComma's
+// so do not flag commas in Generics as GenericTypeConstraintComma's.
 CurrentToken->Type = TT_CSharpGenericTypeConstraintComma;
 next();
   } else if (CurrentToken->is(Keywords.kw_where)) {

diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index d8202bd61458..18899314512e 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2340,6 +2340,12 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   }
   if (FormatTok->Tok.is(tok::semi))
 return;
+  if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
+addUnwrappedLine();
+nextToken();
+parseCSharpGenericTypeConstraint();
+break;
+  }
   nextToken();
 }
   }

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index f5e0bab1cb31..b0e4e76cefe7 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -564,7 +564,7 @@ var myDict = new Dictionary {
 
 TEST_F(FormatTestCSharp, CSharpArrayInitializers) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
-  
+
   verifyFormat(R"(//
 private MySet[] setPoints = {
   new Point(),
@@ -710,6 +710,15 @@ class ItemFactory
   IAnotherInterfaceStill {})",
Style);
 
+  Style.ColumnLimit = 50; // Force lines to be wrapped.
+  verifyFormat(R"(//
+class ItemFactory
+where T : new(),
+  IAnInterface,
+  IAnotherInterface,
+  IAnotherInterfaceStill {})",
+   Style);
+
   // In other languages `where` can be used as a normal identifier.
   // This example is in C++!
   verifyFormat(R"(//



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] a11ff39 - [clang-format] Merge name and colon into a single token for C# named arguments

2020-02-20 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-02-20T19:23:38Z
New Revision: a11ff39ba2ad3975a40e2684948a4dd2ada89bd3

URL: 
https://github.com/llvm/llvm-project/commit/a11ff39ba2ad3975a40e2684948a4dd2ada89bd3
DIFF: 
https://github.com/llvm/llvm-project/commit/a11ff39ba2ad3975a40e2684948a4dd2ada89bd3.diff

LOG: [clang-format] Merge name and colon into a single token for C# named 
arguments

Summary:
Merge 'argumentName' and ':' into a single token in foo(argumentName: bar).

Add C# named argument as a token type.

Reviewers: krasimir, MyDeveloperDay

Reviewed By: krasimir

Tags: #clang-format

Differential Revision: https://reviews.llvm.org/D74894

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/FormatTokenLexer.cpp
clang/lib/Format/FormatTokenLexer.h
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index e9cd327754ef..dc68cbc79734 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -103,6 +103,7 @@ namespace format {
   TYPE(UnaryOperator)  
\
   TYPE(CSharpStringLiteral)
\
   TYPE(CSharpNullCoalescing)   
\
+  TYPE(CSharpNamedArgument)
\
   TYPE(Unknown)
 
 enum TokenType {

diff  --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index e76d74571ebc..8acae56e2232 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -76,6 +76,8 @@ void FormatTokenLexer::tryMergePreviousTokens() {
 return;
 
   if (Style.isCSharp()) {
+if (tryMergeCSharpNamedArgument())
+  return;
 if (tryMergeCSharpAttributeAndTarget())
   return;
 if (tryMergeCSharpKeywordVariables())
@@ -184,6 +186,39 @@ bool FormatTokenLexer::tryMergeJSPrivateIdentifier() {
   return true;
 }
 
+// Merge 'argName' and ':' into a single token in `foo(argName: bar)`.
+bool FormatTokenLexer::tryMergeCSharpNamedArgument() {
+  if (Tokens.size() < 2)
+return false;
+  auto &Colon = *(Tokens.end() - 1);
+  if (!Colon->is(tok::colon))
+return false;
+
+  auto &Name = *(Tokens.end() - 2);
+  if (!Name->is(tok::identifier))
+return false;
+
+  const FormatToken *CommaOrLeftParen = nullptr;
+  for (auto I = Tokens.rbegin() + 2, E = Tokens.rend(); I != E; ++I) {
+// NB: Because previous pointers are not initialized yet, this cannot use
+// Token.getPreviousNonComment.
+if ((*I)->isNot(tok::comment)) {
+  CommaOrLeftParen = *I;
+  break;
+}
+  }
+
+  if (!CommaOrLeftParen || !CommaOrLeftParen->isOneOf(tok::l_paren, 
tok::comma))
+return false;
+
+  Name->TokenText = StringRef(Name->TokenText.begin(),
+  Colon->TokenText.end() - 
Name->TokenText.begin());
+  Name->ColumnWidth += Colon->ColumnWidth;
+  Name->Type = TT_CSharpNamedArgument;
+  Tokens.erase(Tokens.end() - 1);
+  return true;
+}
+
 // Search for verbatim or interpolated string literals @"ABC" or
 // $"a{abc}a" i and mark the token as TT_CSharpStringLiteral, and to
 // prevent splitting of @, $ and ".

diff  --git a/clang/lib/Format/FormatTokenLexer.h 
b/clang/lib/Format/FormatTokenLexer.h
index 4fffb36272f7..1f930d75e805 100644
--- a/clang/lib/Format/FormatTokenLexer.h
+++ b/clang/lib/Format/FormatTokenLexer.h
@@ -56,6 +56,7 @@ class FormatTokenLexer {
   bool tryMergeCSharpDoubleQuestion();
   bool tryTransformCSharpForEach();
   bool tryMergeCSharpAttributeAndTarget();
+  bool tryMergeCSharpNamedArgument();
 
   bool tryMergeTokens(ArrayRef Kinds, TokenType NewType);
 

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index e859aeb0d22d..1800768d6771 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -513,7 +513,7 @@ var x = foo(className, $@"some code:
 TEST_F(FormatTestCSharp, CSharpObjectInitializers) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
 
-  // Start code fragemnts with a comment line so that C++ raw string literals
+  // Start code fragments with a comment line so that C++ raw string literals
   // as seen are identical to expected formatted code.
 
   verifyFormat(R"(//
@@ -539,5 +539,20 @@ Shape[] shapes = new[] {new Circle {Radius = 2.7281, 
Colour = Colours.Red},
Style);
 }
 
+TEST_F(FormatTestCSharp, CSharpNamedArguments) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
+
+  verifyFormat(R"(//
+PrintOrderDetails(orderNum: 31, productName: "Red Mug",
+  sellerName: "Gift Shop");)",
+   Style);
+
+  // Ensure that trailing comments do not cause problems.
+  verifyFormat(R"(//
+Print

[clang] 2bd6974 - [clang-format] Wrap lines for C# property accessors

2020-02-25 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-02-25T14:23:47Z
New Revision: 2bd6974aaa664f01e8822514295425fee380b131

URL: 
https://github.com/llvm/llvm-project/commit/2bd6974aaa664f01e8822514295425fee380b131
DIFF: 
https://github.com/llvm/llvm-project/commit/2bd6974aaa664f01e8822514295425fee380b131.diff

LOG: [clang-format]  Wrap lines for C# property accessors

Summary: Ensure that auto-implemented properties `{ get; private set }` are 
wrapped on to one line for C# code.

Reviewers: MyDeveloperDay, krasimir

Reviewed By: MyDeveloperDay, krasimir

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75006

Added: 


Modified: 
clang/lib/Format/UnwrappedLineFormatter.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 0e1b5e95e9dd..da9ee41da71b 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -292,6 +292,13 @@ class LineJoiner {
   }
 }
 
+// Try to merge a CSharp property declaration like `{ get; private set }`.
+if (Style.isCSharp()) {
+  unsigned CSPA = tryMergeCSharpPropertyAccessor(I, E, Limit);
+  if (CSPA > 0)
+return CSPA;
+}
+
 // Try to merge a function block with left brace unwrapped
 if (TheLine->Last->is(TT_FunctionLBrace) &&
 TheLine->First != TheLine->Last) {
@@ -421,6 +428,64 @@ class LineJoiner {
 return 0;
   }
 
+  // true for lines of the form [access-modifier] {get,set} [;]
+  bool isMergeablePropertyAccessor(const AnnotatedLine *Line) {
+auto *Tok = Line->First;
+if (!Tok)
+  return false;
+
+if (Tok->isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private,
+ Keywords.kw_internal))
+  Tok = Tok->Next;
+
+if (!Tok || (Tok->TokenText != "get" && Tok->TokenText != "set"))
+  return false;
+
+if (!Tok->Next || Tok->Next->is(tok::semi))
+  return true;
+
+return false;
+  }
+
+  unsigned tryMergeCSharpPropertyAccessor(
+  SmallVectorImpl::const_iterator I,
+  SmallVectorImpl::const_iterator E, unsigned /*Limit*/) {
+
+auto CurrentLine = I;
+// Does line start with `{`
+if (!(*CurrentLine)->Last || 
(*CurrentLine)->Last->isNot(TT_FunctionLBrace))
+  return 0;
+++CurrentLine;
+
+unsigned MergedLines = 0;
+bool HasGetOrSet = false;
+while (CurrentLine != E) {
+  bool LineIsGetOrSet = isMergeablePropertyAccessor(*CurrentLine);
+  HasGetOrSet = HasGetOrSet || LineIsGetOrSet;
+  if (LineIsGetOrSet) {
+++CurrentLine;
+++MergedLines;
+continue;
+  }
+  auto *Tok = (*CurrentLine)->First;
+  if (Tok && Tok->is(tok::r_brace)) {
+++CurrentLine;
+++MergedLines;
+// See if the next line is a default value so that we can merge `{ get;
+// set } = 0`
+if (CurrentLine != E && (*CurrentLine)->First &&
+(*CurrentLine)->First->is(tok::equal)) {
+  ++MergedLines;
+}
+break;
+  }
+  // Not a '}' or a get/set line so do not merege lines.
+  return 0;
+}
+
+return HasGetOrSet ? MergedLines : 0;
+  }
+
   unsigned
   tryMergeSimplePPDirective(SmallVectorImpl::const_iterator I,
 SmallVectorImpl::const_iterator E,

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 1800768d6771..68a8e9fefe2d 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -240,18 +240,12 @@ TEST_F(FormatTestCSharp, Attributes) {
 
   verifyFormat("[TestMethod]\n"
"public string Host\n"
-   "{\n"
-   "set;\n"
-   "get;\n"
-   "}");
+   "{ set; get; }");
 
   verifyFormat("[TestMethod(\"start\", HelpText = \"Starts the server "
"listening on provided host\")]\n"
"public string Host\n"
-   "{\n"
-   "set;\n"
-   "get;\n"
-   "}");
+   "{ set; get; }");
 
   verifyFormat(
   "[DllImport(\"Hello\", EntryPoint = \"hello_world\")]\n"
@@ -554,5 +548,32 @@ PrintOrderDetails(orderNum: 31, productName: "Red Mug",  
// comment
Style);
 }
 
+TEST_F(FormatTestCSharp, CSharpPropertyAccessors) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
+
+  verifyFormat("int Value { get }", Style);
+  verifyFormat("int Value { get; }", Style);
+  verifyFormat("int Value { internal get; }", Style);
+  verifyFormat("int Value { get; } = 0", Style);
+  verifyFormat("int Value { set }", Style);
+  verifyFormat("int Value { set; }", Style);
+  verifyFormat("int Value { internal set; }", Style);
+  verifyForma

[clang] e8c5fea - [clang-format] Special handling of spaces for C# code

2020-02-26 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-02-26T15:27:03Z
New Revision: e8c5fea243ce30640ec9707fabdb635a49b3153c

URL: 
https://github.com/llvm/llvm-project/commit/e8c5fea243ce30640ec9707fabdb635a49b3153c
DIFF: 
https://github.com/llvm/llvm-project/commit/e8c5fea243ce30640ec9707fabdb635a49b3153c.diff

LOG: [clang-format] Special handling of spaces for C# code

Summary:
Ensure that there are spaces around braces '{', '}'.

Ensure that there is a space before and after '=>'.

Ensure that 'async' and 'when' are considered as keywords when inserting spaces.

Reviewers: krasimir, MyDeveloperDay

Reviewed By: krasimir

Tags: #clang-format

Differential Revision: https://reviews.llvm.org/D75129

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index dc68cbc79734..6bbfdcf37f93 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -771,6 +771,7 @@ struct AdditionalKeywords {
 kw_unchecked = &IdentTable.get("unchecked");
 kw_unsafe = &IdentTable.get("unsafe");
 kw_ushort = &IdentTable.get("ushort");
+kw_when = &IdentTable.get("when");
 
 // Keep this at the end of the constructor to make sure everything here
 // is
@@ -787,7 +788,7 @@ struct AdditionalKeywords {
  kw_fixed, kw_foreach, kw_implicit, kw_in, kw_interface, kw_internal,
  kw_is, kw_lock, kw_null, kw_object, kw_out, kw_override, kw_params,
  kw_readonly, kw_ref, kw_string, kw_stackalloc, kw_sbyte, kw_sealed,
- kw_uint, kw_ulong, kw_unchecked, kw_unsafe, kw_ushort,
+ kw_uint, kw_ulong, kw_unchecked, kw_unsafe, kw_ushort, kw_when,
  // Keywords from the JavaScript section.
  kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from,
  kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_readonly,
@@ -891,6 +892,7 @@ struct AdditionalKeywords {
   IdentifierInfo *kw_unchecked;
   IdentifierInfo *kw_unsafe;
   IdentifierInfo *kw_ushort;
+  IdentifierInfo *kw_when;
 
   /// Returns \c true if \p Tok is a true JavaScript identifier, returns
   /// \c false if it is a keyword or a pseudo keyword.

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index d71c4f470378..04b20599638d 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2870,21 +2870,34 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
 if (Left.is(tok::numeric_constant) && Right.is(tok::percent))
   return Right.WhitespaceRange.getEnd() != 
Right.WhitespaceRange.getBegin();
   } else if (Style.isCSharp()) {
+// Require spaces around '{' and  before '}' unless they appear in
+// interpolated strings. Interpolated strings are merged into a single 
token
+// so cannot have spaces inserted by this function.
+
+// Space before { (including space within '{ {').
+if (Right.is(tok::l_brace))
+  return true;
+
+// Spaces inside braces.
+if (Left.is(tok::l_brace) && Right.isNot(tok::r_brace))
+  return true;
+
+if (Left.isNot(tok::l_brace) && Right.is(tok::r_brace))
+  return true;
+
+// Spaces around '=>'.
+if (Left.is(TT_JsFatArrow) || Right.is(TT_JsFatArrow))
+  return true;
+
 // space between type and variable e.g. Dictionary foo;
 if (Left.is(TT_TemplateCloser) && Right.is(TT_StartOfName))
   return true;
+
 // space between keywords and paren e.g. "using ("
 if (Right.is(tok::l_paren))
-  if (Left.is(tok::kw_using))
+  if (Left.isOneOf(tok::kw_using, Keywords.kw_async, Keywords.kw_when))
 return Style.SpaceBeforeParens == FormatStyle::SBPO_ControlStatements 
||
spaceRequiredBeforeParens(Right);
-// space between ']' and '{'
-if (Left.is(tok::r_square) && Right.is(tok::l_brace))
-  return true;
-// space before '{' in "new MyType {"
-if (Right.is(tok::l_brace) && Left.Previous &&
-Left.Previous->is(tok::kw_new))
-  return true;
   } else if (Style.Language == FormatStyle::LK_JavaScript) {
 if (Left.is(TT_JsFatArrow))
   return true;

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 68a8e9fefe2d..3bdaf3d5a9f3 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -525,11 +525,11 @@ Shape[] shapes = new[] {
 
   // Omitted final `,`s will change the formatting.
   verifyFormat(R"(//
-Shape[] shapes = new[] {new Circle {Radius = 2.7281, Colour = Colours.Red},
-new Square {
-Side = 101.1,
-Colour = Colours.Yellow,
-}};)",
+Shape[] shapes = new[] { new

[clang] 548e540 - [clang-format] Handle commas in [] in C#

2020-02-27 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-02-27T11:49:30Z
New Revision: 548e540d2ced9f5a596e0433f544c560a842a6a7

URL: 
https://github.com/llvm/llvm-project/commit/548e540d2ced9f5a596e0433f544c560a842a6a7
DIFF: 
https://github.com/llvm/llvm-project/commit/548e540d2ced9f5a596e0433f544c560a842a6a7.diff

LOG: [clang-format] Handle commas in [] in C#

Summary:
Respect setting `SpacesInSquareBrackets` for commas in square brackets in C# 
code.

Reviewers: krasimir, MyDeveloperDay

Reviewed By: krasimir

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75182

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 04b20599638d..ff5827c8c4d4 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2893,6 +2893,10 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
 if (Left.is(TT_TemplateCloser) && Right.is(TT_StartOfName))
   return true;
 
+// space after comma in '[,]'.
+if (Left.is(tok::comma) && Right.is(tok::r_square))
+  return Style.SpacesInSquareBrackets;
+
 // space between keywords and paren e.g. "using ("
 if (Right.is(tok::l_paren))
   if (Left.isOneOf(tok::kw_using, Keywords.kw_async, Keywords.kw_when))

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 3bdaf3d5a9f3..0428de34728a 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -595,6 +595,10 @@ TEST_F(FormatTestCSharp, CSharpSpaces) {
   verifyFormat(R"(bool[] xs = { true, true };)", Style);
   verifyFormat(R"(taskContext.Factory.Run(async () => doThing(args);)", Style);
   verifyFormat(R"(catch (TestException) when (innerFinallyExecuted))", Style);
+  verifyFormat(R"(private float[,] Values;)", Style);
+
+  Style.SpacesInSquareBrackets = true;
+  verifyFormat(R"(private float[, ] Values;)", Style);
 }
 
 } // namespace format



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 7dfe0cc - [clang-format] Recognize C# named argument colons as a token type

2020-02-27 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-02-27T13:47:29Z
New Revision: 7dfe0cc7f5765dc729685a0aa468cdf54a265a11

URL: 
https://github.com/llvm/llvm-project/commit/7dfe0cc7f5765dc729685a0aa468cdf54a265a11
DIFF: 
https://github.com/llvm/llvm-project/commit/7dfe0cc7f5765dc729685a0aa468cdf54a265a11.diff

LOG: [clang-format] Recognize C# named argument colons as a token type

Summary:
No longer merge 'name' and ':' into a single token.

Ensure that line breaks cannot be placed before or after a named-argument colon.

Ensure that no space is inserted before a named-argument colon.

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits, MyDeveloperDay

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75244

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/FormatTokenLexer.cpp
clang/lib/Format/FormatTokenLexer.h
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 6bbfdcf37f93..bab513a03a33 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -103,7 +103,7 @@ namespace format {
   TYPE(UnaryOperator)  
\
   TYPE(CSharpStringLiteral)
\
   TYPE(CSharpNullCoalescing)   
\
-  TYPE(CSharpNamedArgument)
\
+  TYPE(CSharpNamedArgumentColon)   
\
   TYPE(Unknown)
 
 enum TokenType {

diff  --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index 8acae56e2232..aa8cf427d468 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -76,8 +76,6 @@ void FormatTokenLexer::tryMergePreviousTokens() {
 return;
 
   if (Style.isCSharp()) {
-if (tryMergeCSharpNamedArgument())
-  return;
 if (tryMergeCSharpAttributeAndTarget())
   return;
 if (tryMergeCSharpKeywordVariables())
@@ -186,39 +184,6 @@ bool FormatTokenLexer::tryMergeJSPrivateIdentifier() {
   return true;
 }
 
-// Merge 'argName' and ':' into a single token in `foo(argName: bar)`.
-bool FormatTokenLexer::tryMergeCSharpNamedArgument() {
-  if (Tokens.size() < 2)
-return false;
-  auto &Colon = *(Tokens.end() - 1);
-  if (!Colon->is(tok::colon))
-return false;
-
-  auto &Name = *(Tokens.end() - 2);
-  if (!Name->is(tok::identifier))
-return false;
-
-  const FormatToken *CommaOrLeftParen = nullptr;
-  for (auto I = Tokens.rbegin() + 2, E = Tokens.rend(); I != E; ++I) {
-// NB: Because previous pointers are not initialized yet, this cannot use
-// Token.getPreviousNonComment.
-if ((*I)->isNot(tok::comment)) {
-  CommaOrLeftParen = *I;
-  break;
-}
-  }
-
-  if (!CommaOrLeftParen || !CommaOrLeftParen->isOneOf(tok::l_paren, 
tok::comma))
-return false;
-
-  Name->TokenText = StringRef(Name->TokenText.begin(),
-  Colon->TokenText.end() - 
Name->TokenText.begin());
-  Name->ColumnWidth += Colon->ColumnWidth;
-  Name->Type = TT_CSharpNamedArgument;
-  Tokens.erase(Tokens.end() - 1);
-  return true;
-}
-
 // Search for verbatim or interpolated string literals @"ABC" or
 // $"a{abc}a" i and mark the token as TT_CSharpStringLiteral, and to
 // prevent splitting of @, $ and ".
@@ -609,7 +574,7 @@ void 
FormatTokenLexer::handleCSharpVerbatimAndInterpolatedStrings() {
   size_t LastBreak = LiteralText.rfind('\n');
   if (LastBreak != StringRef::npos) {
 CSharpStringLiteral->IsMultiline = true;
-unsigned StartColumn = 0; // The template tail spans the entire line.
+unsigned StartColumn = 0;
 CSharpStringLiteral->LastLineColumnWidth = encoding::columnWidthWithTabs(
 LiteralText.substr(LastBreak + 1, LiteralText.size()), StartColumn,
 Style.TabWidth, Encoding);

diff  --git a/clang/lib/Format/FormatTokenLexer.h 
b/clang/lib/Format/FormatTokenLexer.h
index 1f930d75e805..4fffb36272f7 100644
--- a/clang/lib/Format/FormatTokenLexer.h
+++ b/clang/lib/Format/FormatTokenLexer.h
@@ -56,7 +56,6 @@ class FormatTokenLexer {
   bool tryMergeCSharpDoubleQuestion();
   bool tryTransformCSharpForEach();
   bool tryMergeCSharpAttributeAndTarget();
-  bool tryMergeCSharpNamedArgument();
 
   bool tryMergeTokens(ArrayRef Kinds, TokenType NewType);
 

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index ff5827c8c4d4..fb60b8fb7b58 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -776,6 +776,11 @@ class AnnotatingParser {
   Tok->Type = TT_JsTypeColon;
   break;
 }
+  } else if (Style.isCSharp()) {
+if (Contexts.back().

[clang] 5f52a93 - [clang-format] Recognize C# nullable types

2020-02-28 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-02-28T11:09:55Z
New Revision: 5f52a93b698bab3f7083a6d97d3e3a2e303866e0

URL: 
https://github.com/llvm/llvm-project/commit/5f52a93b698bab3f7083a6d97d3e3a2e303866e0
DIFF: 
https://github.com/llvm/llvm-project/commit/5f52a93b698bab3f7083a6d97d3e3a2e303866e0.diff

LOG: [clang-format] Recognize C# nullable types

Summary:
Do not confuse C# nullable types with conditional expressions.

Do not put a space before the `?` in `[access-modifier] Type? variableName;`

Reviewers: krasimir, MyDeveloperDay

Reviewed By: krasimir, MyDeveloperDay

Subscribers: cfe-commits, MyDeveloperDay

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75261

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index bab513a03a33..61c3cda89cdc 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -104,6 +104,7 @@ namespace format {
   TYPE(CSharpStringLiteral)
\
   TYPE(CSharpNullCoalescing)   
\
   TYPE(CSharpNamedArgumentColon)   
\
+  TYPE(CSharpNullableTypeQuestionMark) 
\
   TYPE(Unknown)
 
 enum TokenType {

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index fb60b8fb7b58..0185dadb15af 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -987,6 +987,10 @@ class AnnotatingParser {
   if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
   Style.Language == FormatStyle::LK_JavaScript)
 break;
+  if (Style.isCSharp() && Line.MustBeDeclaration) {
+Tok->Type = TT_CSharpNullableTypeQuestionMark;
+break;
+  }
   parseConditional();
   break;
 case tok::kw_template:
@@ -2902,6 +2906,10 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
 if (Left.is(tok::comma) && Right.is(tok::r_square))
   return Style.SpacesInSquareBrackets;
 
+// No space before ? in nullable types.
+if (Right.is(TT_CSharpNullableTypeQuestionMark))
+  return false;
+
 // space between keywords and paren e.g. "using ("
 if (Right.is(tok::l_paren))
   if (Left.isOneOf(tok::kw_using, Keywords.kw_async, Keywords.kw_when))

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index ec8dfff94a2b..b91a380456c9 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -175,7 +175,7 @@ TEST_F(FormatTestCSharp, CSharpNullConditional) {
   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
 
   verifyFormat(
-  "public Person(string firstName, string lastName, int? age=null)");
+  "public Person(string firstName, string lastName, int? age = null)");
 
   verifyFormat("foo () {\n"
"  switch (args?.Length) {}\n"
@@ -603,5 +603,18 @@ TEST_F(FormatTestCSharp, CSharpSpaces) {
   verifyFormat(R"(private float[, ] Values;)", Style);
 }
 
+TEST_F(FormatTestCSharp, CSharpNullableTypes) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
+  Style.SpacesInSquareBrackets = false;
+
+  verifyFormat(R"(public float? Value;)", Style); // no space before `?`.
+
+  // Erroneous spaces in square brackets here will be tackled in a follow-up
+  // patch and are not addressed by setting
+  // `Style.SpacesInSquareBrackets = false;`
+  verifyFormat(R"(int?[] arr = new int?[ 10 ];)",
+   Style); // An array of a nullable type.
+}
+
 } // namespace format
 } // end namespace clang



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f829615 - [clang-format] Improve C# handling of spaces in square brackets

2020-02-28 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-02-28T12:44:15Z
New Revision: f829615205f0f671c9b6e1e89d9af78f0d40fe9d

URL: 
https://github.com/llvm/llvm-project/commit/f829615205f0f671c9b6e1e89d9af78f0d40fe9d
DIFF: 
https://github.com/llvm/llvm-project/commit/f829615205f0f671c9b6e1e89d9af78f0d40fe9d.diff

LOG: [clang-format] Improve C# handling of spaces in square brackets

Reviewers: MyDeveloperDay, krasimir

Reviewed By: krasimir

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75336

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 0185dadb15af..86a84afafb8f 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2902,8 +2902,8 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
 if (Left.is(TT_TemplateCloser) && Right.is(TT_StartOfName))
   return true;
 
-// space after comma in '[,]'.
-if (Left.is(tok::comma) && Right.is(tok::r_square))
+// spaces inside square brackets.
+if (Left.is(tok::l_square) || Right.is(tok::r_square))
   return Style.SpacesInSquareBrackets;
 
 // No space before ? in nullable types.

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index b91a380456c9..390993881fda 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -600,7 +600,7 @@ TEST_F(FormatTestCSharp, CSharpSpaces) {
   verifyFormat(R"(private float[,] Values;)", Style);
 
   Style.SpacesInSquareBrackets = true;
-  verifyFormat(R"(private float[, ] Values;)", Style);
+  verifyFormat(R"(private float[ , ] Values;)", Style);
 }
 
 TEST_F(FormatTestCSharp, CSharpNullableTypes) {
@@ -608,11 +608,7 @@ TEST_F(FormatTestCSharp, CSharpNullableTypes) {
   Style.SpacesInSquareBrackets = false;
 
   verifyFormat(R"(public float? Value;)", Style); // no space before `?`.
-
-  // Erroneous spaces in square brackets here will be tackled in a follow-up
-  // patch and are not addressed by setting
-  // `Style.SpacesInSquareBrackets = false;`
-  verifyFormat(R"(int?[] arr = new int?[ 10 ];)",
+  verifyFormat(R"(int?[] arr = new int?[10];)",
Style); // An array of a nullable type.
 }
 



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] c3af063 - [clang-format] Handle NullCoalescing and NullConditional operators in C#

2020-03-02 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-02T13:55:54Z
New Revision: c3af063c2bbfe5408d565ee4350c36fc1d0b2758

URL: 
https://github.com/llvm/llvm-project/commit/c3af063c2bbfe5408d565ee4350c36fc1d0b2758
DIFF: 
https://github.com/llvm/llvm-project/commit/c3af063c2bbfe5408d565ee4350c36fc1d0b2758.diff

LOG: [clang-format] Handle NullCoalescing and NullConditional operators in C#

Summary:
Disable merging of Type? into a single token.

Merge ?? ?. and ?[ into a single token.

Reviewers: krasimir, MyDeveloperDay

Reviewed By: krasimir

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75368

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/FormatTokenLexer.cpp
clang/lib/Format/FormatTokenLexer.h
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 61c3cda89cdc..ac117840ea33 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -102,9 +102,11 @@ namespace format {
   TYPE(TypenameMacro)  
\
   TYPE(UnaryOperator)  
\
   TYPE(CSharpStringLiteral)
\
-  TYPE(CSharpNullCoalescing)   
\
   TYPE(CSharpNamedArgumentColon)   
\
-  TYPE(CSharpNullableTypeQuestionMark) 
\
+  TYPE(CSharpNullable) 
\
+  TYPE(CSharpNullCoalescing)   
\
+  TYPE(CSharpNullConditional)  
\
+  TYPE(CSharpNullConditionalSq)
\
   TYPE(Unknown)
 
 enum TokenType {

diff  --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index aa8cf427d468..da73361ee3d5 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -84,7 +84,7 @@ void FormatTokenLexer::tryMergePreviousTokens() {
   return;
 if (tryMergeCSharpDoubleQuestion())
   return;
-if (tryMergeCSharpNullConditionals())
+if (tryMergeCSharpNullConditional())
   return;
 if (tryTransformCSharpForEach())
   return;
@@ -319,7 +319,7 @@ bool FormatTokenLexer::tryMergeCSharpDoubleQuestion() {
   auto &SecondQuestion = *(Tokens.end() - 1);
   if (!FirstQuestion->is(tok::question) || !SecondQuestion->is(tok::question))
 return false;
-  FirstQuestion->Tok.setKind(tok::question);
+  FirstQuestion->Tok.setKind(tok::question); // no '??' in clang tokens.
   FirstQuestion->TokenText = StringRef(FirstQuestion->TokenText.begin(),
SecondQuestion->TokenText.end() -
FirstQuestion->TokenText.begin());
@@ -329,6 +329,32 @@ bool FormatTokenLexer::tryMergeCSharpDoubleQuestion() {
   return true;
 }
 
+// Merge '?[' and '?.' pairs into single tokens.
+bool FormatTokenLexer::tryMergeCSharpNullConditional() {
+  if (Tokens.size() < 2)
+return false;
+  auto &Question = *(Tokens.end() - 2);
+  auto &PeriodOrLSquare = *(Tokens.end() - 1);
+  if (!Question->is(tok::question) ||
+  !PeriodOrLSquare->isOneOf(tok::l_square, tok::period))
+return false;
+  Question->TokenText =
+  StringRef(Question->TokenText.begin(),
+PeriodOrLSquare->TokenText.end() - 
Question->TokenText.begin());
+  Question->ColumnWidth += PeriodOrLSquare->ColumnWidth;
+
+  if (PeriodOrLSquare->is(tok::l_square)) {
+Question->Tok.setKind(tok::question); // no '?[' in clang tokens.
+Question->Type = TT_CSharpNullConditionalSq;
+  } else {
+Question->Tok.setKind(tok::question); // no '?.' in clang tokens.
+Question->Type = TT_CSharpNullConditional;
+  }
+
+  Tokens.erase(Tokens.end() - 1);
+  return true;
+}
+
 bool FormatTokenLexer::tryMergeCSharpKeywordVariables() {
   if (Tokens.size() < 2)
 return false;
@@ -348,23 +374,6 @@ bool FormatTokenLexer::tryMergeCSharpKeywordVariables() {
   return true;
 }
 
-// In C# merge the Identifier and the ? together e.g. arg?.
-bool FormatTokenLexer::tryMergeCSharpNullConditionals() {
-  if (Tokens.size() < 2)
-return false;
-  auto &Identifier = *(Tokens.end() - 2);
-  auto &Question = *(Tokens.end() - 1);
-  if (!Identifier->isOneOf(tok::r_square, tok::identifier) ||
-  !Question->is(tok::question))
-return false;
-  Identifier->TokenText =
-  StringRef(Identifier->TokenText.begin(),
-Question->TokenText.end() - Identifier->TokenText.begin());
-  Identifier->ColumnWidth += Question->ColumnWidth;
-  Tokens.erase(Tokens.end() - 1);
-

[clang] 9c4afce - [clang-format] Rename CSharpNullConditionalSq and add missing test

2020-03-02 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-02T15:46:33Z
New Revision: 9c4afce7024aa1fe4efe2631240d1d766b4ea257

URL: 
https://github.com/llvm/llvm-project/commit/9c4afce7024aa1fe4efe2631240d1d766b4ea257
DIFF: 
https://github.com/llvm/llvm-project/commit/9c4afce7024aa1fe4efe2631240d1d766b4ea257.diff

LOG: [clang-format] Rename CSharpNullConditionalSq and add missing test

Summary:
Rename CSharpNullConditionalSq to CSharpNullConditionalLSquare.

Add test for spaces inside [] with C# Null conditionals.

Address comments missed from https://reviews.llvm.org/D75368.

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75456

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/FormatTokenLexer.cpp
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index ac117840ea33..d0d08e470e6c 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -106,7 +106,7 @@ namespace format {
   TYPE(CSharpNullable) 
\
   TYPE(CSharpNullCoalescing)   
\
   TYPE(CSharpNullConditional)  
\
-  TYPE(CSharpNullConditionalSq)
\
+  TYPE(CSharpNullConditionalLSquare)   
\
   TYPE(Unknown)
 
 enum TokenType {

diff  --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index da73361ee3d5..8fa78b773e5e 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -345,7 +345,7 @@ bool FormatTokenLexer::tryMergeCSharpNullConditional() {
 
   if (PeriodOrLSquare->is(tok::l_square)) {
 Question->Tok.setKind(tok::question); // no '?[' in clang tokens.
-Question->Type = TT_CSharpNullConditionalSq;
+Question->Type = TT_CSharpNullConditionalLSquare;
   } else {
 Question->Tok.setKind(tok::question); // no '?.' in clang tokens.
 Question->Type = TT_CSharpNullConditional;

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index e1e08686ac44..35e0b423cfc4 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -972,7 +972,7 @@ class AnnotatingParser {
   }
   break;
 case tok::question:
-  if (Tok->is(TT_CSharpNullConditionalSq)) {
+  if (Tok->is(TT_CSharpNullConditionalLSquare)) {
 if (!parseSquare())
   return false;
 break;
@@ -1456,7 +1456,7 @@ class AnnotatingParser {
 return;
   }
   if (CurrentToken->TokenText == "?[") {
-Current.Type = TT_CSharpNullConditionalSq;
+Current.Type = TT_CSharpNullConditionalLSquare;
 return;
   }
 }
@@ -2947,11 +2947,11 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
   return true;
 
 // No space before '?['.
-if (Right.is(TT_CSharpNullConditionalSq))
+if (Right.is(TT_CSharpNullConditionalLSquare))
   return false;
 
 // Possible space inside `?[ 0 ]`.
-if (Left.is(TT_CSharpNullConditionalSq))
+if (Left.is(TT_CSharpNullConditionalLSquare))
   return Style.SpacesInSquareBrackets;
 
 // space between keywords and paren e.g. "using ("

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 0bc49856375b..d22e0da82321 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -607,6 +607,7 @@ TEST_F(FormatTestCSharp, CSharpSpaces) {
 
   Style.SpacesInSquareBrackets = true;
   verifyFormat(R"(private float[ , ] Values;)", Style);
+  verifyFormat(R"(string dirPath = args?[ 0 ];)", Style);
 }
 
 TEST_F(FormatTestCSharp, CSharpNullableTypes) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 9f8a7e8 - [clang-format] Allow nested [] in C# attributes

2020-03-03 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-03T17:35:09Z
New Revision: 9f8a7e82b85078b5afbbc44429355f156e044205

URL: 
https://github.com/llvm/llvm-project/commit/9f8a7e82b85078b5afbbc44429355f156e044205
DIFF: 
https://github.com/llvm/llvm-project/commit/9f8a7e82b85078b5afbbc44429355f156e044205.diff

LOG: [clang-format] Allow nested [] in C# attributes

Summary: Keep track of unpaired [] when identifying C# attribute lines

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75455

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 802bb514a38f..06c740048176 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -324,12 +324,21 @@ void UnwrappedLineParser::parseFile() {
 }
 
 void UnwrappedLineParser::parseCSharpAttribute() {
+  int UnpairedSquareBrackets = 1;
   do {
 switch (FormatTok->Tok.getKind()) {
 case tok::r_square:
   nextToken();
-  addUnwrappedLine();
-  return;
+  --UnpairedSquareBrackets;
+  if (UnpairedSquareBrackets == 0) {
+addUnwrappedLine();
+return;
+  }
+  break;
+case tok::l_square:
+  ++UnpairedSquareBrackets;
+  nextToken();
+  break;
 default:
   nextToken();
   break;

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index d22e0da82321..6251f97b8e0b 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -273,6 +273,15 @@ TEST_F(FormatTestCSharp, Attributes) {
"{\n"
"}");
 
+  // [] in an attribute do not cause premature line wrapping or indenting.
+  verifyFormat(R"(//
+public class A
+{
+[SomeAttribute(new[] { RED, GREEN, BLUE }, -1.0f, 1.0f)]
+[DoNotSerialize]
+public Data MemberVariable;
+})");
+
   //  Unwrappable lines go on a line of their own.
   // 'target:' is not treated as a label.
   // Modify Style to enforce a column limit.



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 900dee8 - [clang-format] Do not merge target-name and : for C# attributes

2020-03-03 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-03T22:17:25Z
New Revision: 900dee8c8e03abc5a566e22b4f5499ecdc960803

URL: 
https://github.com/llvm/llvm-project/commit/900dee8c8e03abc5a566e22b4f5499ecdc960803
DIFF: 
https://github.com/llvm/llvm-project/commit/900dee8c8e03abc5a566e22b4f5499ecdc960803.diff

LOG: [clang-format] Do not merge target-name and : for C# attributes

Summary:
Re-use token type `TT_AttributeColon` for C# attribute target colons.

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: MyDeveloperDay, cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75465

Added: 


Modified: 
clang/lib/Format/FormatTokenLexer.cpp
clang/lib/Format/FormatTokenLexer.h
clang/lib/Format/TokenAnnotator.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index 8fa78b773e5e..9e081e1495d0 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -76,8 +76,6 @@ void FormatTokenLexer::tryMergePreviousTokens() {
 return;
 
   if (Style.isCSharp()) {
-if (tryMergeCSharpAttributeAndTarget())
-  return;
 if (tryMergeCSharpKeywordVariables())
   return;
 if (tryMergeCSharpStringLiteral())
@@ -284,34 +282,6 @@ const llvm::StringSet<> 
FormatTokenLexer::CSharpAttributeTargets = {
 "param","property", "return", "type",
 };
 
-bool FormatTokenLexer::tryMergeCSharpAttributeAndTarget() {
-  // Treat '[assembly:' and '[field:' as tokens in their own right.
-  if (Tokens.size() < 3)
-return false;
-
-  auto &SquareBracket = *(Tokens.end() - 3);
-  auto &Target = *(Tokens.end() - 2);
-  auto &Colon = *(Tokens.end() - 1);
-
-  if (!SquareBracket->Tok.is(tok::l_square))
-return false;
-
-  if (CSharpAttributeTargets.find(Target->TokenText) ==
-  CSharpAttributeTargets.end())
-return false;
-
-  if (!Colon->Tok.is(tok::colon))
-return false;
-
-  SquareBracket->TokenText =
-  StringRef(SquareBracket->TokenText.begin(),
-Colon->TokenText.end() - SquareBracket->TokenText.begin());
-  SquareBracket->ColumnWidth += (Target->ColumnWidth + Colon->ColumnWidth);
-  Tokens.erase(Tokens.end() - 2);
-  Tokens.erase(Tokens.end() - 1);
-  return true;
-}
-
 bool FormatTokenLexer::tryMergeCSharpDoubleQuestion() {
   if (Tokens.size() < 2)
 return false;

diff  --git a/clang/lib/Format/FormatTokenLexer.h 
b/clang/lib/Format/FormatTokenLexer.h
index e5726fe18111..192e26a10d4a 100644
--- a/clang/lib/Format/FormatTokenLexer.h
+++ b/clang/lib/Format/FormatTokenLexer.h
@@ -55,7 +55,6 @@ class FormatTokenLexer {
   bool tryMergeCSharpDoubleQuestion();
   bool tryMergeCSharpNullConditional();
   bool tryTransformCSharpForEach();
-  bool tryMergeCSharpAttributeAndTarget();
 
   bool tryMergeTokens(ArrayRef Kinds, TokenType NewType);
 

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 35e0b423cfc4..a074d54fd44c 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -384,11 +384,11 @@ class AnnotatingParser {
 
 if (!AttrTok)
   return false;
-
-// Move past the end of ']'.
+
+// Allow an attribute to be the only content of a file.
 AttrTok = AttrTok->Next;
 if (!AttrTok)
-  return false;
+  return true;
 
 // Limit this to being an access modifier that follows.
 if (AttrTok->isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected,
@@ -460,7 +460,7 @@ class AnnotatingParser {
  Contexts.back().InCpp11AttributeSpecifier;
 
 // Treat C# Attributes [STAThread] much like C++ attributes [[...]].
-bool IsCSharp11AttributeSpecifier =
+bool IsCSharpAttributeSpecifier =
 isCSharpAttributeSpecifier(*Left) ||
 Contexts.back().InCSharpAttributeSpecifier;
 
@@ -469,7 +469,8 @@ class AnnotatingParser {
 bool StartsObjCMethodExpr =
 !IsCppStructuredBinding && !InsideInlineASM && !CppArrayTemplates &&
 Style.isCpp() && !IsCpp11AttributeSpecifier &&
-Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
+!IsCSharpAttributeSpecifier && Contexts.back().CanBeExpression &&
+Left->isNot(TT_LambdaLSquare) &&
 !CurrentToken->isOneOf(tok::l_brace, tok::r_square) &&
 (!Parent ||
  Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
@@ -496,7 +497,7 @@ class AnnotatingParser {
   } else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace 
&&
  Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
 Left->Type = TT_DesignatedInitializerLSquare;
-  } else if (IsCSharp11AttributeSpecifier) {
+  } else if (IsCSharpAttributeSpecifier) {
 Left->Type = TT_AttributeSquare;
   } else if (CurrentToken->is(tok::r_square) && Parent &&
  

[clang] 736fef9 - [clang-format] Do not format C# array subscript operators as attributes

2020-03-03 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-03T22:21:33Z
New Revision: 736fef97c7ac4113388fc56db10c599fb4d2f074

URL: 
https://github.com/llvm/llvm-project/commit/736fef97c7ac4113388fc56db10c599fb4d2f074
DIFF: 
https://github.com/llvm/llvm-project/commit/736fef97c7ac4113388fc56db10c599fb4d2f074.diff

LOG: [clang-format] Do not format C# array subscript operators as attributes

Summary:
Fix misidentification of C# array subscript operators.

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits, MyDeveloperDay

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75517

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index a074d54fd44c..493454eb2239 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -369,6 +369,17 @@ class AnnotatingParser {
 if (!Style.isCSharp())
   return false;
 
+// `identifier[i]` is not an attribute.
+if (Tok.Previous && Tok.Previous->is(tok::identifier))
+  return false;
+
+// Chains [] in of `identifier[i][j][k]` are not attributes.
+if (Tok.Previous && Tok.Previous->is(tok::r_square)) {
+  auto *MatchingParen = Tok.Previous->MatchingParen;
+  if (!MatchingParen || MatchingParen->is(TT_ArraySubscriptLSquare))
+return false;
+}
+
 const FormatToken *AttrTok = Tok.Next;
 if (!AttrTok)
   return false;

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 6251f97b8e0b..ad849f2dbdf7 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -628,5 +628,13 @@ TEST_F(FormatTestCSharp, CSharpNullableTypes) {
Style); // An array of a nullable type.
 }
 
+TEST_F(FormatTestCSharp, CSharpArraySubscripts) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
+
+  // Do not format array subscript operators as attributes.
+  verifyFormat(R"(if (someThings[index].Contains(myThing)) {)", Style);
+  verifyFormat(R"(if (someThings[i][j][k].Contains(myThing)) {)", Style);
+}
+
 } // namespace format
 } // end namespace clang



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 7d2fdd3 - [clang-format] parse C# object initialisers

2020-03-04 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-04T12:14:00Z
New Revision: 7d2fdd3f6639731284dd8b6b274f01f04fd19215

URL: 
https://github.com/llvm/llvm-project/commit/7d2fdd3f6639731284dd8b6b274f01f04fd19215
DIFF: 
https://github.com/llvm/llvm-project/commit/7d2fdd3f6639731284dd8b6b274f01f04fd19215.diff

LOG: [clang-format] parse C# object initialisers

Summary:
Treat C# object initializers as braced lists.

Allow lambdas inside C# braced lists.

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits, MyDeveloperDay

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75473

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 06c740048176..58cc679af9e1 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1632,6 +1632,17 @@ bool UnwrappedLineParser::parseBracedList(bool 
ContinueOnSemicolons,
   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
   // replace this by using parseAssigmentExpression() inside.
   do {
+if (Style.isCSharp()) {
+  if (FormatTok->is(TT_JsFatArrow)) {
+nextToken();
+// Fat arrows can be followed by simple expressions or by child blocks
+// in curly braces.
+if (FormatTok->is(tok::l_brace)) {
+  parseChildBlock();
+  continue;
+}
+  }
+}
 if (Style.Language == FormatStyle::LK_JavaScript) {
   if (FormatTok->is(Keywords.kw_function) ||
   FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) {
@@ -1955,7 +1966,7 @@ void UnwrappedLineParser::parseNamespace() {
  DeclarationScopeStack.size() > 1);
 parseBlock(/*MustBeDeclaration=*/true, AddLevel);
 // Munch the semicolon after a namespace. This is more common than one 
would
-// think. Puttin the semicolon into its own line is very ugly.
+// think. Putting the semicolon into its own line is very ugly.
 if (FormatTok->Tok.is(tok::semi))
   nextToken();
 addUnwrappedLine();
@@ -1966,6 +1977,19 @@ void UnwrappedLineParser::parseNamespace() {
 void UnwrappedLineParser::parseNew() {
   assert(FormatTok->is(tok::kw_new) && "'new' expected");
   nextToken();
+
+  if (Style.isCSharp()) {
+do {
+  if (FormatTok->is(tok::l_brace))
+parseBracedList();
+
+  if (FormatTok->isOneOf(tok::semi, tok::comma))
+return;
+
+  nextToken();
+} while (!eof());
+  }
+
   if (Style.Language != FormatStyle::LK_Java)
 return;
 

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index ad849f2dbdf7..3f14de9b75da 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -546,6 +546,14 @@ Shape[] shapes = new[] { new Circle { Radius = 2.7281, 
Colour = Colours.Red },
  Colour = Colours.Yellow,
  } };)",
Style);
+
+  // Lambdas can be supplied as initialiser arguments.
+  verifyFormat(R"(//
+private Transformer _transformer = new X.Y {
+Filler = (Shape shape) => { return new Transform.Fill(shape, RED); },
+Scaler = (Shape shape) => { return new Transform.Resize(shape, 0.1); },
+};)",
+   Style);
 }
 
 TEST_F(FormatTestCSharp, CSharpNamedArguments) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] fe61bc1 - [clang-format] Improve identification of C# nullables

2020-03-04 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-04T18:10:27Z
New Revision: fe61bc1a0b5a00badae9334e01e103769af4fa6c

URL: 
https://github.com/llvm/llvm-project/commit/fe61bc1a0b5a00badae9334e01e103769af4fa6c
DIFF: 
https://github.com/llvm/llvm-project/commit/fe61bc1a0b5a00badae9334e01e103769af4fa6c.diff

LOG: [clang-format] Improve identification of C# nullables

Summary: Consider `? identifier =` and `? identifier;` to be nullable within 
function bodies.

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits, MyDeveloperDay

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75606

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 493454eb2239..e491de85babd 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1011,7 +1011,12 @@ class AnnotatingParser {
   Style.Language == FormatStyle::LK_JavaScript)
 break;
   if (Style.isCSharp()) {
-if (Line.MustBeDeclaration && !Contexts.back().IsExpression) {
+// `Type? name;` and `Type? name =` can only be nullable types.
+// Line.MustBeDeclaration will be true for `Type? name;`.
+if (!Contexts.back().IsExpression &&
+(Line.MustBeDeclaration ||
+ (Tok->Next && Tok->Next->is(tok::identifier) && Tok->Next->Next &&
+  Tok->Next->Next->is(tok::equal {
   Tok->Type = TT_CSharpNullable;
   break;
 }

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 3f14de9b75da..7e60fdbdba26 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -631,7 +631,17 @@ TEST_F(FormatTestCSharp, CSharpNullableTypes) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
   Style.SpacesInSquareBrackets = false;
 
+  verifyFormat(R"(//
+public class A {
+  void foo() { int? value = some.bar(); }
+})",
+   Style); // int? is nullable not a conditional expression.
+
+  verifyFormat(R"(void foo(int? x, int? y, int? z) {})",
+   Style); // Nullables in function definitions.
+
   verifyFormat(R"(public float? Value;)", Style); // no space before `?`.
+
   verifyFormat(R"(int?[] arr = new int?[10];)",
Style); // An array of a nullable type.
 }



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] b28ed9c - [clang-format] cleanup from D75517

2020-03-09 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-09T17:31:36Z
New Revision: b28ed9cec8dd7225164eb8c0884aa463654ef3fc

URL: 
https://github.com/llvm/llvm-project/commit/b28ed9cec8dd7225164eb8c0884aa463654ef3fc
DIFF: 
https://github.com/llvm/llvm-project/commit/b28ed9cec8dd7225164eb8c0884aa463654ef3fc.diff

LOG: [clang-format] cleanup from D75517

Summary:
Fix typo in comment.

Add closing brace to test text.

Reviewers: krasimir

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75856

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 2673dacfff13..db230583b6c9 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -373,7 +373,7 @@ class AnnotatingParser {
 if (Tok.Previous && Tok.Previous->is(tok::identifier))
   return false;
 
-// Chains [] in of `identifier[i][j][k]` are not attributes.
+// Chains of [] in `identifier[i][j][k]` are not attributes.
 if (Tok.Previous && Tok.Previous->is(tok::r_square)) {
   auto *MatchingParen = Tok.Previous->MatchingParen;
   if (!MatchingParen || MatchingParen->is(TT_ArraySubscriptLSquare))

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 7e60fdbdba26..e3038898dcdd 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -650,8 +650,15 @@ TEST_F(FormatTestCSharp, CSharpArraySubscripts) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
 
   // Do not format array subscript operators as attributes.
-  verifyFormat(R"(if (someThings[index].Contains(myThing)) {)", Style);
-  verifyFormat(R"(if (someThings[i][j][k].Contains(myThing)) {)", Style);
+  verifyFormat(R"(//
+if (someThings[index].Contains(myThing)) {
+})",
+   Style);
+
+  verifyFormat(R"(//
+if (someThings[i][j][k].Contains(myThing)) {
+})",
+   Style);
 }
 
 } // namespace format



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] eb682b8 - [clang-format] C# does not indent braced initializers as continuations

2020-03-09 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-09T17:36:21Z
New Revision: eb682b80274d5486d062e3f53040969f592277e4

URL: 
https://github.com/llvm/llvm-project/commit/eb682b80274d5486d062e3f53040969f592277e4
DIFF: 
https://github.com/llvm/llvm-project/commit/eb682b80274d5486d062e3f53040969f592277e4.diff

LOG: [clang-format] C# does not indent braced initializers as continuations

Summary: C# treats object initializers as braced init blocks. Braced init 
blocks are no longer indented as continuations.

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75731

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 072e1ad565c2..1b885b518f0d 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -509,6 +509,9 @@ struct FormatToken {
   /// Returns \c true if this tokens starts a block-type list, i.e. a
   /// list that should be indented with a block indent.
   bool opensBlockOrBlockTypeList(const FormatStyle &Style) const {
+// C# Does not indent object initialisers as continuations.
+if (is(tok::l_brace) && BlockKind == BK_BracedInit && Style.isCSharp())
+  return true;
 if (is(TT_TemplateString) && opensScope())
   return true;
 return is(TT_ArrayInitializerLSquare) || is(TT_ProtoExtensionLSquare) ||

diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 58cc679af9e1..00447ebdf5a9 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1677,7 +1677,10 @@ bool UnwrappedLineParser::parseBracedList(bool 
ContinueOnSemicolons,
   }
   break;
 case tok::l_square:
-  tryToParseLambda();
+  if (Style.isCSharp())
+parseSquare();
+  else
+tryToParseLambda();
   break;
 case tok::l_paren:
   parseParens();

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index e3038898dcdd..a22f48676065 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -527,31 +527,28 @@ TEST_F(FormatTestCSharp, CSharpObjectInitializers) {
 
   verifyFormat(R"(//
 Shape[] shapes = new[] {
-new Circle {
-Radius = 2.7281,
-Colour = Colours.Red,
-},
-new Square {
-Side = 101.1,
-Colour = Colours.Yellow,
-},
+  new Circle {
+Radius = 2.7281,
+Colour = Colours.Red,
+  },
+  new Square {
+Side = 101.1,
+Colour = Colours.Yellow,
+  },
 };)",
Style);
 
   // Omitted final `,`s will change the formatting.
   verifyFormat(R"(//
 Shape[] shapes = new[] { new Circle { Radius = 2.7281, Colour = Colours.Red },
- new Square {
- Side = 101.1,
- Colour = Colours.Yellow,
- } };)",
+ new Square { Side = 101.1, Colour = Colours.Yellow } 
};)",
Style);
 
   // Lambdas can be supplied as initialiser arguments.
   verifyFormat(R"(//
 private Transformer _transformer = new X.Y {
-Filler = (Shape shape) => { return new Transform.Fill(shape, RED); },
-Scaler = (Shape shape) => { return new Transform.Resize(shape, 0.1); },
+  Filler = (Shape shape) => { return new Transform.Fill(shape, RED); },
+  Scaler = (Shape shape) => { return new Transform.Resize(shape, 0.1); },
 };)",
Style);
 }



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] cb3f20d - [clang-format] Correct indentation for `[key] = value,` entries in C++ object initialisers

2020-03-09 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-09T18:04:34Z
New Revision: cb3f20d27c9e91cb9f997f0401f388e62c4ba993

URL: 
https://github.com/llvm/llvm-project/commit/cb3f20d27c9e91cb9f997f0401f388e62c4ba993
DIFF: 
https://github.com/llvm/llvm-project/commit/cb3f20d27c9e91cb9f997f0401f388e62c4ba993.diff

LOG: [clang-format] Correct indentation for `[key] = value,` entries in C++ 
object initialisers

Summary: Do not use continuation indent for '[' in blocks in C# code.

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75747

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index a08f5a3df864..9a6d7877efaa 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -1047,6 +1047,9 @@ unsigned ContinuationIndenter::getNewLineColumn(const 
LineState &State) {
   if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
 if (State.Stack.back().StartOfArraySubscripts != 0)
   return State.Stack.back().StartOfArraySubscripts;
+else if (Style.isCSharp()) // C# allows `["key"] = value` inside object
+   // initializers.
+  return State.Stack.back().Indent;
 return ContinuationIndent;
   }
 

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index a22f48676065..7f819a61c70e 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -549,6 +549,15 @@ Shape[] shapes = new[] { new Circle { Radius = 2.7281, 
Colour = Colours.Red },
 private Transformer _transformer = new X.Y {
   Filler = (Shape shape) => { return new Transform.Fill(shape, RED); },
   Scaler = (Shape shape) => { return new Transform.Resize(shape, 0.1); },
+};)",
+   Style);
+
+  // Dictionary initialisation.
+  verifyFormat(R"(//
+var myDict = new Dictionary {
+  ["name"] = _donald,
+  ["age"] = Convert.ToString(DateTime.Today.Year - 1934),
+  ["type"] = _duck,
 };)",
Style);
 }



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 5a101f3 - Revert "[clang-format] Correct indentation for `[key] = value,` entries in C++ object initialisers"

2020-03-10 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-10T09:30:34Z
New Revision: 5a101f377315c0c0c58e8df842fe5eb5d8c7611d

URL: 
https://github.com/llvm/llvm-project/commit/5a101f377315c0c0c58e8df842fe5eb5d8c7611d
DIFF: 
https://github.com/llvm/llvm-project/commit/5a101f377315c0c0c58e8df842fe5eb5d8c7611d.diff

LOG: Revert "[clang-format] Correct indentation for `[key] = value,` entries in 
C++ object initialisers"

Commit message says "C++" where it should say "C#".

This reverts commit cb3f20d27c9e91cb9f997f0401f388e62c4ba993.

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 9a6d7877efaa..a08f5a3df864 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -1047,9 +1047,6 @@ unsigned ContinuationIndenter::getNewLineColumn(const 
LineState &State) {
   if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
 if (State.Stack.back().StartOfArraySubscripts != 0)
   return State.Stack.back().StartOfArraySubscripts;
-else if (Style.isCSharp()) // C# allows `["key"] = value` inside object
-   // initializers.
-  return State.Stack.back().Indent;
 return ContinuationIndent;
   }
 

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 7f819a61c70e..a22f48676065 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -549,15 +549,6 @@ Shape[] shapes = new[] { new Circle { Radius = 2.7281, 
Colour = Colours.Red },
 private Transformer _transformer = new X.Y {
   Filler = (Shape shape) => { return new Transform.Fill(shape, RED); },
   Scaler = (Shape shape) => { return new Transform.Resize(shape, 0.1); },
-};)",
-   Style);
-
-  // Dictionary initialisation.
-  verifyFormat(R"(//
-var myDict = new Dictionary {
-  ["name"] = _donald,
-  ["age"] = Convert.ToString(DateTime.Today.Year - 1934),
-  ["type"] = _duck,
 };)",
Style);
 }



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 0c28a09 - [clang-format] Correct indentation for `[key] = value,` entries in C# object initialisers

2020-03-10 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-10T09:36:52Z
New Revision: 0c28a0938c55ad34587fe88ac54ff2c85e79fa70

URL: 
https://github.com/llvm/llvm-project/commit/0c28a0938c55ad34587fe88ac54ff2c85e79fa70
DIFF: 
https://github.com/llvm/llvm-project/commit/0c28a0938c55ad34587fe88ac54ff2c85e79fa70.diff

LOG: [clang-format] Correct indentation for `[key] = value,` entries in C# 
object initialisers

Restores content of commit cb3f20d27c9e91cb9f997f0401f388e62c4ba993
reverted in commit 5a101f377315c0c0c58e8df842fe5eb5d8c7611d
with a corrected commit message.

Summary: Do not use continuation indent for '[' in blocks in C# code.

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75747

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index a08f5a3df864..9a6d7877efaa 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -1047,6 +1047,9 @@ unsigned ContinuationIndenter::getNewLineColumn(const 
LineState &State) {
   if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
 if (State.Stack.back().StartOfArraySubscripts != 0)
   return State.Stack.back().StartOfArraySubscripts;
+else if (Style.isCSharp()) // C# allows `["key"] = value` inside object
+   // initializers.
+  return State.Stack.back().Indent;
 return ContinuationIndent;
   }
 

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index a22f48676065..7f819a61c70e 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -549,6 +549,15 @@ Shape[] shapes = new[] { new Circle { Radius = 2.7281, 
Colour = Colours.Red },
 private Transformer _transformer = new X.Y {
   Filler = (Shape shape) => { return new Transform.Fill(shape, RED); },
   Scaler = (Shape shape) => { return new Transform.Resize(shape, 0.1); },
+};)",
+   Style);
+
+  // Dictionary initialisation.
+  verifyFormat(R"(//
+var myDict = new Dictionary {
+  ["name"] = _donald,
+  ["age"] = Convert.ToString(DateTime.Today.Year - 1934),
+  ["type"] = _duck,
 };)",
Style);
 }



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 5c917bd - [clang-format] No space in `new()` and `this[Type x]` in C#

2020-03-11 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-11T12:53:53Z
New Revision: 5c917bd9a7de8fc45401da00cd27661b429887e9

URL: 
https://github.com/llvm/llvm-project/commit/5c917bd9a7de8fc45401da00cd27661b429887e9
DIFF: 
https://github.com/llvm/llvm-project/commit/5c917bd9a7de8fc45401da00cd27661b429887e9.diff

LOG: [clang-format] No space in `new()` and `this[Type x]` in C#

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits, MyDeveloperDay

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75984

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index db230583b6c9..cf481a1dcb62 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2930,6 +2930,14 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
 // interpolated strings. Interpolated strings are merged into a single 
token
 // so cannot have spaces inserted by this function.
 
+// No space between 'this' and '['
+if (Left.is(tok::kw_this) && Right.is(tok::l_square))
+  return false;
+
+// No space between 'new' and '('
+if (Left.is(tok::kw_new) && Right.is(tok::l_paren))
+  return false;
+
 // Space before { (including space within '{ {').
 if (Right.is(tok::l_brace))
   return true;

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 7f819a61c70e..824eb51bd693 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -627,6 +627,8 @@ TEST_F(FormatTestCSharp, CSharpSpaces) {
   verifyFormat(R"(taskContext.Factory.Run(async () => doThing(args);)", Style);
   verifyFormat(R"(catch (TestException) when (innerFinallyExecuted))", Style);
   verifyFormat(R"(private float[,] Values;)", Style);
+  verifyFormat(R"(Result this[Index x] => Foo(x);)", Style);
+  verifyFormat(R"(class ItemFactory where T : new() {})", Style);
 
   Style.SpacesInSquareBrackets = true;
   verifyFormat(R"(private float[ , ] Values;)", Style);



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 1fb9c29 - [clang-format] Improved identification of C# nullables

2020-03-11 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-11T12:58:52Z
New Revision: 1fb9c29833ab88c4a3d6fda997839754d998

URL: 
https://github.com/llvm/llvm-project/commit/1fb9c29833ab88c4a3d6fda997839754d998
DIFF: 
https://github.com/llvm/llvm-project/commit/1fb9c29833ab88c4a3d6fda997839754d998.diff

LOG: [clang-format] Improved identification of C# nullables

Summary:
Allow `?` inside C# generics.

Do not mistake casts like `(Type?)` as conditional operators.

Reviewers: krasimir

Subscribers: cfe-commits, MyDeveloperDay

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D75983

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index cf481a1dcb62..d546a9f7c606 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -131,7 +131,7 @@ class AnnotatingParser {
   }
   if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) ||
   (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext &&
-   Style.Language != FormatStyle::LK_Proto &&
+   !Style.isCSharp() && Style.Language != FormatStyle::LK_Proto &&
Style.Language != FormatStyle::LK_TextProto))
 return false;
   // If a && or || is found and interpreted as a binary operator, this set
@@ -1013,12 +1013,13 @@ class AnnotatingParser {
   Style.Language == FormatStyle::LK_JavaScript)
 break;
   if (Style.isCSharp()) {
-// `Type? name;` and `Type? name =` can only be nullable types.
+// `Type?)`, `Type?>`, `Type? name;` and `Type? name =` can only be
+// nullable types.
 // Line.MustBeDeclaration will be true for `Type? name;`.
-if (!Contexts.back().IsExpression &&
-(Line.MustBeDeclaration ||
- (Tok->Next && Tok->Next->is(tok::identifier) && Tok->Next->Next &&
-  Tok->Next->Next->is(tok::equal {
+if ((!Contexts.back().IsExpression && Line.MustBeDeclaration) ||
+(Tok->Next && Tok->Next->isOneOf(tok::r_paren, tok::greater)) ||
+(Tok->Next && Tok->Next->is(tok::identifier) && Tok->Next->Next &&
+ Tok->Next->Next->is(tok::equal))) {
   Tok->Type = TT_CSharpNullable;
   break;
 }
@@ -2969,9 +2970,9 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
 if (Right.is(TT_CSharpNullable))
   return false;
 
-// Require space after ? in nullable types.
+// Require space after ? in nullable types except in generics and casts.
 if (Left.is(TT_CSharpNullable))
-  return true;
+  return !Right.isOneOf(TT_TemplateCloser, tok::r_paren);
 
 // No space before or after '?.'.
 if (Left.is(TT_CSharpNullConditional) || 
Right.is(TT_CSharpNullConditional))

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 824eb51bd693..03ebe337e76c 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -652,6 +652,10 @@ public class A {
 
   verifyFormat(R"(int?[] arr = new int?[10];)",
Style); // An array of a nullable type.
+
+  verifyFormat(R"(var x = (int?)y;)", Style); // Cast to a nullable type.
+
+  verifyFormat(R"(var x = new MyContainer();)", Style); // Generics.
 }
 
 TEST_F(FormatTestCSharp, CSharpArraySubscripts) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] dcbcec4 - [clang-format] Handle C# generic type constraints

2020-03-19 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-19T12:56:08Z
New Revision: dcbcec4822f47ec5b638dd9c20dcebd464569dae

URL: 
https://github.com/llvm/llvm-project/commit/dcbcec4822f47ec5b638dd9c20dcebd464569dae
DIFF: 
https://github.com/llvm/llvm-project/commit/dcbcec4822f47ec5b638dd9c20dcebd464569dae.diff

LOG: [clang-format] Handle C# generic type constraints

Summary:
Treat each C# generic type constraint, `where T: ...`, as a line.

Add C# keyword: where

Add Token Types: CSharpGenericTypeConstraint, CSharpGenericTypeConstraintColon, 
CSharpGenericTypeConstraintComma.

This patch does not wrap generic type constraints well, that will be addressed 
in a follow up patch.

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits, MyDeveloperDay

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D76367

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/UnwrappedLineFormatter.cpp
clang/lib/Format/UnwrappedLineParser.cpp
clang/lib/Format/UnwrappedLineParser.h
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 1b885b518f0d..10a5f0e96f96 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -108,6 +108,9 @@ namespace format {
   TYPE(CSharpNullCoalescing)   
\
   TYPE(CSharpNullConditional)  
\
   TYPE(CSharpNullConditionalLSquare)   
\
+  TYPE(CSharpGenericTypeConstraint)
\
+  TYPE(CSharpGenericTypeConstraintColon)   
\
+  TYPE(CSharpGenericTypeConstraintComma)   
\
   TYPE(Unknown)
 
 enum TokenType {
@@ -779,6 +782,7 @@ struct AdditionalKeywords {
 kw_unsafe = &IdentTable.get("unsafe");
 kw_ushort = &IdentTable.get("ushort");
 kw_when = &IdentTable.get("when");
+kw_where = &IdentTable.get("where");
 
 // Keep this at the end of the constructor to make sure everything here
 // is
@@ -796,6 +800,7 @@ struct AdditionalKeywords {
  kw_is, kw_lock, kw_null, kw_object, kw_out, kw_override, kw_params,
  kw_readonly, kw_ref, kw_string, kw_stackalloc, kw_sbyte, kw_sealed,
  kw_uint, kw_ulong, kw_unchecked, kw_unsafe, kw_ushort, kw_when,
+ kw_where,
  // Keywords from the JavaScript section.
  kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from,
  kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_readonly,
@@ -900,6 +905,7 @@ struct AdditionalKeywords {
   IdentifierInfo *kw_unsafe;
   IdentifierInfo *kw_ushort;
   IdentifierInfo *kw_when;
+  IdentifierInfo *kw_where;
 
   /// Returns \c true if \p Tok is a true JavaScript identifier, returns
   /// \c false if it is a keyword or a pseudo keyword.

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index d546a9f7c606..7193c8e6de44 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1047,6 +1047,11 @@ class AnnotatingParser {
Keywords.kw___has_include_next)) {
 parseHasInclude();
   }
+  if (Tok->is(Keywords.kw_where) && Tok->Next &&
+  Tok->Next->isNot(tok::l_paren)) {
+Tok->Type = TT_CSharpGenericTypeConstraint;
+parseCSharpGenericTypeConstraint();
+  }
   break;
 default:
   break;
@@ -1054,6 +1059,30 @@ class AnnotatingParser {
 return true;
   }
 
+  void parseCSharpGenericTypeConstraint() {
+while (CurrentToken) {
+  if (CurrentToken->is(tok::less)) {
+// parseAngle is too greedy and will consume the whole line.
+CurrentToken->Type = TT_TemplateOpener;
+next();
+  } else if (CurrentToken->is(tok::greater)) {
+CurrentToken->Type = TT_TemplateCloser;
+next();
+  } else if (CurrentToken->is(tok::comma)) {
+CurrentToken->Type = TT_CSharpGenericTypeConstraintComma;
+next();
+  } else if (CurrentToken->is(Keywords.kw_where)) {
+CurrentToken->Type = TT_CSharpGenericTypeConstraint;
+next();
+  } else if (CurrentToken->is(tok::colon)) {
+CurrentToken->Type = TT_CSharpGenericTypeConstraintColon;
+next();
+  } else {
+next();
+  }
+}
+  }
+
   void parseIncludeDirective() {
 if (CurrentToken && CurrentToken->is(tok::less)) {
   next();
@@ -3299,6 +3328,8 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine 
&Line,
 if (Right.is(TT_CSharpNamedArgumentColon) ||
 Left.is(TT_CSharpNamedArgumentColon))
   return false;
+if (Right.is(TT_CSharpGenericTypeConstraint))
+  return true;
   } else if (Sty

[clang] 50d8977 - [clang-format] Allow a comment to follow a C# attribute specifier

2020-02-04 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-02-04T19:00:54Z
New Revision: 50d8977c459de302fcef7a2578b0e8f8862a2fe0

URL: 
https://github.com/llvm/llvm-project/commit/50d8977c459de302fcef7a2578b0e8f8862a2fe0
DIFF: 
https://github.com/llvm/llvm-project/commit/50d8977c459de302fcef7a2578b0e8f8862a2fe0.diff

LOG: [clang-format] Allow a comment to follow a C# attribute specifier

Summary: Add comments to the list of tokens that can follow the ']' at the end 
of a C# attribute specifier to prevent comments after attribute specifiers from 
being formatted as continuations.

Reviewers: MyDeveloperDay, krasimir

Reviewed By: MyDeveloperDay

Tags: #clang-format

Differential Revision: https://reviews.llvm.org/D73977

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index f6df58dac2d6..7538b03f4f7c 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -392,8 +392,8 @@ class AnnotatingParser {
 
 // Limit this to being an access modifier that follows.
 if (AttrTok->isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected,
- tok::kw_class, tok::kw_static, tok::l_square,
- Keywords.kw_internal)) {
+ tok::comment, tok::kw_class, tok::kw_static,
+ tok::l_square, Keywords.kw_internal)) {
   return true;
 }
 

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 5d1131aa0c3a..86a44d0f9eb3 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -228,6 +228,11 @@ TEST_F(FormatTestCSharp, Attributes) {
"set;\n"
"get;\n"
"}");
+
+  verifyFormat(
+  "[DllImport(\"Hello\", EntryPoint = \"hello_world\")]\n"
+  "// The const char* returned by hello_world must not be deleted.\n"
+  "private static extern IntPtr HelloFromCpp();)");
 }
 
 TEST_F(FormatTestCSharp, CSharpUsing) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] ca1fd46 - [clang-format] Do not treat C# attribute targets as labels

2020-02-05 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-02-05T17:30:24Z
New Revision: ca1fd460f1f5bc4c200f557b63d69a93e3722175

URL: 
https://github.com/llvm/llvm-project/commit/ca1fd460f1f5bc4c200f557b63d69a93e3722175
DIFF: 
https://github.com/llvm/llvm-project/commit/ca1fd460f1f5bc4c200f557b63d69a93e3722175.diff

LOG: [clang-format] Do not treat C# attribute targets as labels

Summary: Merge '[', 'target' , ':' into a single token for C# attributes to
prevent the target from being seen as a label.

Reviewers: MyDeveloperDay, krasimir

Reviewed By: krasimir

Tags: #clang-format

Differential Revision: https://reviews.llvm.org/D74043

Added: 


Modified: 
clang/lib/Format/FormatTokenLexer.cpp
clang/lib/Format/FormatTokenLexer.h
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index 98650951c7d0..e76d74571ebc 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -76,6 +76,8 @@ void FormatTokenLexer::tryMergePreviousTokens() {
 return;
 
   if (Style.isCSharp()) {
+if (tryMergeCSharpAttributeAndTarget())
+  return;
 if (tryMergeCSharpKeywordVariables())
   return;
 if (tryMergeCSharpStringLiteral())
@@ -275,6 +277,41 @@ bool FormatTokenLexer::tryMergeCSharpStringLiteral() {
   return true;
 }
 
+// Valid C# attribute targets:
+// 
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/#attribute-targets
+const llvm::StringSet<> FormatTokenLexer::CSharpAttributeTargets = {
+"assembly", "module",   "field",  "event", "method",
+"param","property", "return", "type",
+};
+
+bool FormatTokenLexer::tryMergeCSharpAttributeAndTarget() {
+  // Treat '[assembly:' and '[field:' as tokens in their own right.
+  if (Tokens.size() < 3)
+return false;
+
+  auto &SquareBracket = *(Tokens.end() - 3);
+  auto &Target = *(Tokens.end() - 2);
+  auto &Colon = *(Tokens.end() - 1);
+
+  if (!SquareBracket->Tok.is(tok::l_square))
+return false;
+
+  if (CSharpAttributeTargets.find(Target->TokenText) ==
+  CSharpAttributeTargets.end())
+return false;
+
+  if (!Colon->Tok.is(tok::colon))
+return false;
+
+  SquareBracket->TokenText =
+  StringRef(SquareBracket->TokenText.begin(),
+Colon->TokenText.end() - SquareBracket->TokenText.begin());
+  SquareBracket->ColumnWidth += (Target->ColumnWidth + Colon->ColumnWidth);
+  Tokens.erase(Tokens.end() - 2);
+  Tokens.erase(Tokens.end() - 1);
+  return true;
+}
+
 bool FormatTokenLexer::tryMergeCSharpDoubleQuestion() {
   if (Tokens.size() < 2)
 return false;

diff  --git a/clang/lib/Format/FormatTokenLexer.h 
b/clang/lib/Format/FormatTokenLexer.h
index be13ac8f6735..4fffb36272f7 100644
--- a/clang/lib/Format/FormatTokenLexer.h
+++ b/clang/lib/Format/FormatTokenLexer.h
@@ -21,6 +21,7 @@
 #include "clang/Basic/SourceManager.h"
 #include "clang/Format/Format.h"
 #include "llvm/ADT/MapVector.h"
+#include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Regex.h"
 
 #include 
@@ -54,6 +55,7 @@ class FormatTokenLexer {
   bool tryMergeCSharpNullConditionals();
   bool tryMergeCSharpDoubleQuestion();
   bool tryTransformCSharpForEach();
+  bool tryMergeCSharpAttributeAndTarget();
 
   bool tryMergeTokens(ArrayRef Kinds, TokenType NewType);
 
@@ -115,6 +117,9 @@ class FormatTokenLexer {
   llvm::Regex MacroBlockBeginRegex;
   llvm::Regex MacroBlockEndRegex;
 
+  // Targets that may appear inside a C# attribute.
+  static const llvm::StringSet<> CSharpAttributeTargets;
+
   void readRawToken(FormatToken &Tok);
 
   void resetLexer(unsigned Offset);

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 86a44d0f9eb3..dba76b521614 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -233,6 +233,15 @@ TEST_F(FormatTestCSharp, Attributes) {
   "[DllImport(\"Hello\", EntryPoint = \"hello_world\")]\n"
   "// The const char* returned by hello_world must not be deleted.\n"
   "private static extern IntPtr HelloFromCpp();)");
+
+  //  Unwrappable lines go on a line of their own.
+  // 'target:' is not treated as a label.
+  // Modify Style to enforce a column limit.
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
+  Style.ColumnLimit = 10;
+  verifyFormat(R"([assembly:InternalsVisibleTo(
+"SomeAssembly, PublicKey=SomePublicKeyThatExceedsTheColumnLimit")])",
+   Style);
 }
 
 TEST_F(FormatTestCSharp, CSharpUsing) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f40a797 - [clang-format] Do not merge short C# class definitions into one line

2020-02-05 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-02-05T17:38:33Z
New Revision: f40a7972cb42e130c6e954f21acf9b66bf5bcad7

URL: 
https://github.com/llvm/llvm-project/commit/f40a7972cb42e130c6e954f21acf9b66bf5bcad7
DIFF: 
https://github.com/llvm/llvm-project/commit/f40a7972cb42e130c6e954f21acf9b66bf5bcad7.diff

LOG: [clang-format] Do not merge short C# class definitions into one line

Summary: Skip access specifiers before record definitions when deciding whether
or not to wrap lines so that C# class definitions do not get wrapped into a
single line.

Reviewers: krasimir, MyDeveloperDay

Reviewed By: krasimir

Tags: #clang-format

Differential Revision: https://reviews.llvm.org/D74050

Added: 


Modified: 
clang/lib/Format/UnwrappedLineFormatter.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index fec85f1174da..0e1b5e95e9dd 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -593,9 +593,10 @@ class LineJoiner {
 FormatToken *RecordTok = Line.First;
 // Skip record modifiers.
 while (RecordTok->Next &&
-   RecordTok->isOneOf(tok::kw_typedef, tok::kw_export,
-  Keywords.kw_declare, Keywords.kw_abstract,
-  tok::kw_default))
+   RecordTok->isOneOf(
+   tok::kw_typedef, tok::kw_export, Keywords.kw_declare,
+   Keywords.kw_abstract, tok::kw_default, tok::kw_public,
+   tok::kw_private, tok::kw_protected, Keywords.kw_internal))
   RecordTok = RecordTok->Next;
 if (RecordTok &&
 RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index dba76b521614..918f8aed83e9 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -70,6 +70,30 @@ TEST_F(FormatTestCSharp, CSharpClass) {
"f();\n"
"}\n"
"}");
+
+  // Ensure that small and empty classes are handled correctly with condensed
+  // (Google C++-like) brace-breaking style.
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
+  Style.BreakBeforeBraces = FormatStyle::BS_Attach;
+
+  verifyFormat("public class SomeEmptyClass {}", Style);
+
+  verifyFormat("public class SomeTinyClass {\n"
+   "  int X;\n"
+   "}",
+   Style);
+  verifyFormat("private class SomeTinyClass {\n"
+   "  int X;\n"
+   "}",
+   Style);
+  verifyFormat("protected class SomeTinyClass {\n"
+   "  int X;\n"
+   "}",
+   Style);
+  verifyFormat("internal class SomeTinyClass {\n"
+   "  int X;\n"
+   "}",
+   Style);
 }
 
 TEST_F(FormatTestCSharp, AccessModifiers) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] b46f925 - [clang-format] Improve handling of C# attributes

2020-02-11 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-02-11T12:00:17Z
New Revision: b46f925d68d480246e1447f26459bdc894631a88

URL: 
https://github.com/llvm/llvm-project/commit/b46f925d68d480246e1447f26459bdc894631a88
DIFF: 
https://github.com/llvm/llvm-project/commit/b46f925d68d480246e1447f26459bdc894631a88.diff

LOG: [clang-format] Improve handling of C# attributes

Summary:
C# attributes can appear on classes and methods, in which case they should go 
on their own line, or on method parameters in which case
they should be left inline.

Reviewers: krasimir, MyDeveloperDay

Reviewed By: MyDeveloperDay

Subscribers: klimek

Tags: #clang-format

Differential Revision: https://reviews.llvm.org/D74265

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/UnwrappedLineParser.cpp
clang/lib/Format/UnwrappedLineParser.h
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 7538b03f4f7c..1c15859e5786 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3280,13 +3280,6 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine 
&Line,
   return true;
   }
 
-  // Put multiple C# attributes on a new line.
-  if (Style.isCSharp() &&
-  ((Left.is(TT_AttributeSquare) && Left.is(tok::r_square)) ||
-   (Left.is(tok::r_square) && Right.is(TT_AttributeSquare) &&
-Right.is(tok::l_square
-return true;
-
   // Put multiple Java annotation on a new line.
   if ((Style.Language == FormatStyle::LK_Java ||
Style.Language == FormatStyle::LK_JavaScript) &&

diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 321a7405e24a..b455a7f2ebed 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -323,6 +323,20 @@ void UnwrappedLineParser::parseFile() {
   addUnwrappedLine();
 }
 
+void UnwrappedLineParser::parseCSharpAttribute() {
+  do {
+switch (FormatTok->Tok.getKind()) {
+case tok::r_square:
+  nextToken();
+  addUnwrappedLine();
+  return;
+default:
+  nextToken();
+  break;
+}
+  } while (!eof());
+}
+
 void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
   bool SwitchLabelEncountered = false;
   do {
@@ -381,6 +395,13 @@ void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) 
{
   SwitchLabelEncountered = true;
   parseStructuralElement();
   break;
+case tok::l_square:
+  if (Style.isCSharp()) {
+nextToken();
+parseCSharpAttribute();
+break;
+  }
+  LLVM_FALLTHROUGH;
 default:
   parseStructuralElement();
   break;

diff  --git a/clang/lib/Format/UnwrappedLineParser.h 
b/clang/lib/Format/UnwrappedLineParser.h
index 5d9bafc429a7..e184cf5354fd 100644
--- a/clang/lib/Format/UnwrappedLineParser.h
+++ b/clang/lib/Format/UnwrappedLineParser.h
@@ -125,6 +125,7 @@ class UnwrappedLineParser {
   bool parseObjCProtocol();
   void parseJavaScriptEs6ImportExport();
   void parseStatementMacro();
+  void parseCSharpAttribute();
   bool tryToParseLambda();
   bool tryToParseLambdaIntroducer();
   void tryToParseJSFunction();

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 918f8aed83e9..e859aeb0d22d 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -258,6 +258,21 @@ TEST_F(FormatTestCSharp, Attributes) {
   "// The const char* returned by hello_world must not be deleted.\n"
   "private static extern IntPtr HelloFromCpp();)");
 
+  // Class attributes go on their own line and do not affect layout of
+  // interfaces. Line wrapping decisions previously caused each interface to be
+  // on its own line.
+  verifyFormat("[SomeAttribute]\n"
+   "[SomeOtherAttribute]\n"
+   "public class A : IShape, IAnimal, IVehicle\n"
+   "{\n"
+   "int X;\n"
+   "}");
+
+  // Attributes in a method declaration do not cause line wrapping.
+  verifyFormat("void MethodA([In][Out] ref double x)\n"
+   "{\n"
+   "}");
+
   //  Unwrappable lines go on a line of their own.
   // 'target:' is not treated as a label.
   // Modify Style to enforce a column limit.



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 9d212e8 - [clang-format] Handle quotes and escaped braces in C# interpolated strings

2020-01-28 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-01-28T14:46:27Z
New Revision: 9d212e83e920363762eb265293adf0bd6fda5a13

URL: 
https://github.com/llvm/llvm-project/commit/9d212e83e920363762eb265293adf0bd6fda5a13
DIFF: 
https://github.com/llvm/llvm-project/commit/9d212e83e920363762eb265293adf0bd6fda5a13.diff

LOG: [clang-format] Handle quotes and escaped braces in C# interpolated strings

Summary:
This addresses issues raised in https://bugs.llvm.org/show_bug.cgi?id=44454.

There are outstanding issues with multi-line verbatim strings in C# that will 
be addressed in a follow-up PR.

Reviewers: krasimir, MyDeveloperDay

Reviewed By: krasimir, MyDeveloperDay

Subscribers: MyDeveloperDay

Tags: #clang-format

Differential Revision: https://reviews.llvm.org/D73492

Added: 


Modified: 
clang/lib/Format/FormatTokenLexer.cpp
clang/lib/Format/FormatTokenLexer.h
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index d8dfe17fb89c..ba0bbf68f12f 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -74,7 +74,7 @@ void FormatTokenLexer::tryMergePreviousTokens() {
   if (Style.isCSharp()) {
 if (tryMergeCSharpKeywordVariables())
   return;
-if (tryMergeCSharpVerbatimStringLiteral())
+if (tryMergeCSharpStringLiteral())
   return;
 if (tryMergeCSharpDoubleQuestion())
   return;
@@ -181,18 +181,68 @@ bool FormatTokenLexer::tryMergeJSPrivateIdentifier() {
 // Search for verbatim or interpolated string literals @"ABC" or
 // $"a{abc}a" i and mark the token as TT_CSharpStringLiteral, and to
 // prevent splitting of @, $ and ".
-bool FormatTokenLexer::tryMergeCSharpVerbatimStringLiteral() {
+bool FormatTokenLexer::tryMergeCSharpStringLiteral() {
   if (Tokens.size() < 2)
 return false;
 
-  auto &String = *(Tokens.end() - 1);
-  if (!String->is(tok::string_literal))
-return false;
+  auto &CSharpStringLiteral = *(Tokens.end() - 2);
+
+  // Interpolated strings could contain { } with " characters inside.
+  // $"{x ?? "null"}"
+  // should not be split into $"{x ?? ", null, "}" but should treated as a
+  // single string-literal.
+  //
+  // We opt not to try and format expressions inside {} within a C#
+  // interpolated string. Formatting expressions within an interpolated string
+  // would require similar work as that done for JavaScript template strings
+  // in `handleTemplateStrings()`.
+  auto &CSharpInterpolatedString = *(Tokens.end() - 2);
+  if (CSharpInterpolatedString->Type == TT_CSharpStringLiteral &&
+  (CSharpInterpolatedString->TokenText.startswith(R"($")") ||
+   CSharpInterpolatedString->TokenText.startswith(R"($@")"))) {
+int UnmatchedOpeningBraceCount = 0;
+
+auto TokenTextSize = CSharpInterpolatedString->TokenText.size();
+for (size_t Index = 0; Index < TokenTextSize; ++Index) {
+  char C = CSharpInterpolatedString->TokenText[Index];
+  if (C == '{') {
+// "{{"  inside an interpolated string is an escaped '{' so skip it.
+if (Index + 1 < TokenTextSize &&
+CSharpInterpolatedString->TokenText[Index + 1] == '{') {
+  ++Index;
+  continue;
+}
+++UnmatchedOpeningBraceCount;
+  } else if (C == '}') {
+// "}}"  inside an interpolated string is an escaped '}' so skip it.
+if (Index + 1 < TokenTextSize &&
+CSharpInterpolatedString->TokenText[Index + 1] == '}') {
+  ++Index;
+  continue;
+}
+--UnmatchedOpeningBraceCount;
+  }
+}
+
+if (UnmatchedOpeningBraceCount > 0) {
+  auto &NextToken = *(Tokens.end() - 1);
+  CSharpInterpolatedString->TokenText =
+  StringRef(CSharpInterpolatedString->TokenText.begin(),
+NextToken->TokenText.end() -
+CSharpInterpolatedString->TokenText.begin());
+  CSharpInterpolatedString->ColumnWidth += NextToken->ColumnWidth;
+  Tokens.erase(Tokens.end() - 1);
+  return true;
+}
+  }
 
   // verbatim strings could contain "" which C# sees as an escaped ".
   // @"""Hello""" will have been tokenized as @"" "Hello" "" and needs
   // merging into a single string literal.
-  auto &CSharpStringLiteral = *(Tokens.end() - 2);
+  auto &String = *(Tokens.end() - 1);
+  if (!String->is(tok::string_literal))
+return false;
+
   if (CSharpStringLiteral->Type == TT_CSharpStringLiteral &&
   (CSharpStringLiteral->TokenText.startswith(R"(@")") ||
CSharpStringLiteral->TokenText.startswith(R"($@")"))) {

diff  --git a/clang/lib/Format/FormatTokenLexer.h 
b/clang/lib/Format/FormatTokenLexer.h
index 611211be055a..053b759d2440 100644
--- a/clang/lib/Format/FormatTokenLexer.h
+++ b/clang/lib/Format/FormatTokenLexer.h
@@ -49,7 +49,7 @@ class FormatTokenLexer {
   bool tryMergeLessLess();
   

[clang] f9f0919 - [clang-format] Improve support for multiline C# strings

2020-01-30 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-01-30T13:45:48Z
New Revision: f9f0919db7ea033a205c87eb08c81c4baaecd846

URL: 
https://github.com/llvm/llvm-project/commit/f9f0919db7ea033a205c87eb08c81c4baaecd846
DIFF: 
https://github.com/llvm/llvm-project/commit/f9f0919db7ea033a205c87eb08c81c4baaecd846.diff

LOG: [clang-format] Improve support for multiline C# strings

Reviewers: krasimir

Reviewed By: krasimir

Tags: #clang-format

Differential Revision: https://reviews.llvm.org/D73622

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/lib/Format/FormatTokenLexer.cpp
clang/lib/Format/FormatTokenLexer.h
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index ec2de35ca0d2..1ea7eb031d36 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -1760,7 +1760,7 @@ ContinuationIndenter::createBreakableToken(const 
FormatToken &Current,
LineState &State, bool AllowBreak) {
   unsigned StartColumn = State.Column - Current.ColumnWidth;
   if (Current.isStringLiteral()) {
-// FIXME: String literal breaking is currently disabled for C#,Java and
+// FIXME: String literal breaking is currently disabled for C#, Java and
 // JavaScript, as it requires strings to be merged using "+" which we
 // don't support.
 if (Style.Language == FormatStyle::LK_Java ||

diff  --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index ba0bbf68f12f..98650951c7d0 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -57,6 +57,10 @@ ArrayRef FormatTokenLexer::lex() {
 if (Style.Language == FormatStyle::LK_TextProto)
   tryParsePythonComment();
 tryMergePreviousTokens();
+if (Style.isCSharp())
+  // This needs to come after tokens have been merged so that C#
+  // string literals are correctly identified.
+  handleCSharpVerbatimAndInterpolatedStrings();
 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
   FirstInLineIndex = Tokens.size() - 1;
   } while (Tokens.back()->Tok.isNot(tok::eof));
@@ -181,12 +185,12 @@ bool FormatTokenLexer::tryMergeJSPrivateIdentifier() {
 // Search for verbatim or interpolated string literals @"ABC" or
 // $"a{abc}a" i and mark the token as TT_CSharpStringLiteral, and to
 // prevent splitting of @, $ and ".
+// Merging of multiline verbatim strings with embedded '"' is handled in
+// handleCSharpVerbatimAndInterpolatedStrings with lower-level lexing.
 bool FormatTokenLexer::tryMergeCSharpStringLiteral() {
   if (Tokens.size() < 2)
 return false;
 
-  auto &CSharpStringLiteral = *(Tokens.end() - 2);
-
   // Interpolated strings could contain { } with " characters inside.
   // $"{x ?? "null"}"
   // should not be split into $"{x ?? ", null, "}" but should treated as a
@@ -236,27 +240,12 @@ bool FormatTokenLexer::tryMergeCSharpStringLiteral() {
 }
   }
 
-  // verbatim strings could contain "" which C# sees as an escaped ".
-  // @"""Hello""" will have been tokenized as @"" "Hello" "" and needs
-  // merging into a single string literal.
+  // Look for @"aa" or $"aa".
   auto &String = *(Tokens.end() - 1);
   if (!String->is(tok::string_literal))
 return false;
 
-  if (CSharpStringLiteral->Type == TT_CSharpStringLiteral &&
-  (CSharpStringLiteral->TokenText.startswith(R"(@")") ||
-   CSharpStringLiteral->TokenText.startswith(R"($@")"))) {
-CSharpStringLiteral->TokenText = StringRef(
-CSharpStringLiteral->TokenText.begin(),
-String->TokenText.end() - CSharpStringLiteral->TokenText.begin());
-CSharpStringLiteral->ColumnWidth += String->ColumnWidth;
-Tokens.erase(Tokens.end() - 1);
-return true;
-  }
-
   auto &At = *(Tokens.end() - 2);
-
-  // Look for @"aa" or $"aa".
   if (!(At->is(tok::at) || At->TokenText == "$"))
 return false;
 
@@ -498,6 +487,68 @@ void FormatTokenLexer::tryParseJSRegexLiteral() {
   resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
 }
 
+void FormatTokenLexer::handleCSharpVerbatimAndInterpolatedStrings() {
+  FormatToken *CSharpStringLiteral = Tokens.back();
+
+  if (CSharpStringLiteral->Type != TT_CSharpStringLiteral)
+return;
+
+  // Deal with multiline strings.
+  if (!(CSharpStringLiteral->TokenText.startswith(R"(@")") ||
+CSharpStringLiteral->TokenText.startswith(R"($@")")))
+return;
+
+  const char *StrBegin =
+  Lex->getBufferLocation() - CSharpStringLiteral->TokenText.size();
+  const char *Offset = StrBegin;
+  if (CSharpStringLiteral->TokenText.startswith(R"(@")"))
+Offset += 2;
+  else // CSharpStringLiteral->TokenText.startswith(R"($@")")
+Offset += 3;
+
+  // Look for a terminating '"' in the curr

[clang] 0bb60e2 - [clang-format] Fixes for spaces around C# object initializers

2020-01-31 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-01-31T14:22:01Z
New Revision: 0bb60e29f18bd45fc26d5f619150f28fc7541e9b

URL: 
https://github.com/llvm/llvm-project/commit/0bb60e29f18bd45fc26d5f619150f28fc7541e9b
DIFF: 
https://github.com/llvm/llvm-project/commit/0bb60e29f18bd45fc26d5f619150f28fc7541e9b.diff

LOG: [clang-format] Fixes for spaces around C# object initializers

Summary: Fix spaces around typename and [] in C# object initializers.

Reviewers: MyDeveloperDay, klimek, krasimir

Reviewed By: MyDeveloperDay, krasimir

Subscribers: cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D72401

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 3dc88315c352..f6df58dac2d6 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2873,6 +2873,13 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
   if (Left.is(tok::kw_using))
 return Style.SpaceBeforeParens == FormatStyle::SBPO_ControlStatements 
||
spaceRequiredBeforeParens(Right);
+// space between ']' and '{'
+if (Left.is(tok::r_square) && Right.is(tok::l_brace))
+  return true;
+// space before '{' in "new MyType {"
+if (Right.is(tok::l_brace) && Left.Previous &&
+Left.Previous->is(tok::kw_new))
+  return true;
   } else if (Style.Language == FormatStyle::LK_JavaScript) {
 if (Left.is(TT_JsFatArrow))
   return true;

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 3d1b597174d8..5d1131aa0c3a 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -457,5 +457,34 @@ var x = foo(className, $@"some code:
   EXPECT_EQ(Code, format(Code, Style));
 }
 
+TEST_F(FormatTestCSharp, CSharpObjectInitializers) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
+
+  // Start code fragemnts with a comment line so that C++ raw string literals
+  // as seen are identical to expected formatted code.
+
+  verifyFormat(R"(//
+Shape[] shapes = new[] {
+new Circle {
+Radius = 2.7281,
+Colour = Colours.Red,
+},
+new Square {
+Side = 101.1,
+Colour = Colours.Yellow,
+},
+};)",
+   Style);
+
+  // Omitted final `,`s will change the formatting.
+  verifyFormat(R"(//
+Shape[] shapes = new[] {new Circle {Radius = 2.7281, Colour = Colours.Red},
+new Square {
+Side = 101.1,
+Colour = Colours.Yellow,
+}};)",
+   Style);
+}
+
 } // namespace format
 } // end namespace clang



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r328418 - [clang-tidy] Enable Python 3 support for add_new_check.py

2018-03-24 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Sat Mar 24 03:49:17 2018
New Revision: 328418

URL: http://llvm.org/viewvc/llvm-project?rev=328418&view=rev
Log:
[clang-tidy] Enable Python 3 support for add_new_check.py

Summary: In Python 3, filters are lazily evaluated and strings are not bytes.

Reviewers: ilya-biryukov

Reviewed By: ilya-biryukov

Subscribers: xazax.hun, cfe-commits

Differential Revision: https://reviews.llvm.org/D44217

Modified:
clang-tools-extra/trunk/clang-tidy/add_new_check.py

Modified: clang-tools-extra/trunk/clang-tidy/add_new_check.py
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/add_new_check.py?rev=328418&r1=328417&r2=328418&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/add_new_check.py (original)
+++ clang-tools-extra/trunk/clang-tidy/add_new_check.py Sat Mar 24 03:49:17 2018
@@ -9,12 +9,13 @@
 #
 
#======#
 
+from __future__ import print_function
+
 import argparse
 import os
 import re
 import sys
 
-
 # Adapts the module's CMakelist file. Returns 'True' if it could add a new 
entry
 # and 'False' if the entry already existed.
 def adapt_cmake(module_path, check_name_camel):
@@ -30,7 +31,7 @@ def adapt_cmake(module_path, check_name_
   return False
 
   print('Updating %s...' % filename)
-  with open(filename, 'wb') as f:
+  with open(filename, 'w') as f:
 cpp_found = False
 file_added = False
 for line in lines:
@@ -50,7 +51,7 @@ def write_header(module_path, module, ch
   check_name_dashes = module + '-' + check_name
   filename = os.path.join(module_path, check_name_camel) + '.h'
   print('Creating %s...' % filename)
-  with open(filename, 'wb') as f:
+  with open(filename, 'w') as f:
 header_guard = ('LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_' + module.upper() + '_'
 + check_name_camel.upper() + '_H')
 f.write('//===--- ')
@@ -103,7 +104,7 @@ public:
 def write_implementation(module_path, module, check_name_camel):
   filename = os.path.join(module_path, check_name_camel) + '.cpp'
   print('Creating %s...' % filename)
-  with open(filename, 'wb') as f:
+  with open(filename, 'w') as f:
 f.write('//===--- ')
 f.write(os.path.basename(filename))
 f.write(' - clang-tidy')
@@ -152,14 +153,15 @@ void %(check_name)s::check(const MatchFi
 
 # Modifies the module to include the new check.
 def adapt_module(module_path, module, check_name, check_name_camel):
-  modulecpp = filter(lambda p: p.lower() == module.lower() + 'tidymodule.cpp',
- os.listdir(module_path))[0]
+  modulecpp = list(filter(
+  lambda p: p.lower() == module.lower() + 'tidymodule.cpp',
+  os.listdir(module_path)))[0]
   filename = os.path.join(module_path, modulecpp)
   with open(filename, 'r') as f:
 lines = f.readlines()
 
   print('Updating %s...' % filename)
-  with open(filename, 'wb') as f:
+  with open(filename, 'w') as f:
 header_added = False
 header_found = False
 check_added = False
@@ -199,7 +201,7 @@ def add_release_notes(module_path, modul
 lines = f.readlines()
 
   print('Updating %s...' % filename)
-  with open(filename, 'wb') as f:
+  with open(filename, 'w') as f:
 note_added = False
 header_found = False
 
@@ -227,7 +229,7 @@ def write_test(module_path, module, chec
   filename = os.path.normpath(os.path.join(module_path, 
'../../test/clang-tidy',
check_name_dashes + '.' + 
test_extension))
   print('Creating %s...' % filename)
-  with open(filename, 'wb') as f:
+  with open(filename, 'w') as f:
 f.write("""// RUN: %%check_clang_tidy %%s %(check_name_dashes)s %%t
 
 // FIXME: Add something that triggers the check here.
@@ -251,8 +253,8 @@ def update_checks_list(clang_tidy_path):
   filename = os.path.normpath(os.path.join(docs_dir, 'list.rst'))
   with open(filename, 'r') as f:
 lines = f.readlines()
-  doc_files = filter(lambda s: s.endswith('.rst') and s != 'list.rst',
- os.listdir(docs_dir))
+  doc_files = list(filter(lambda s: s.endswith('.rst') and s != 'list.rst',
+ os.listdir(docs_dir)))
   doc_files.sort()
 
   def format_link(doc_file):
@@ -275,7 +277,7 @@ def update_checks_list(clang_tidy_path):
   checks = map(format_link, doc_files)
 
   print('Updating %s...' % filename)
-  with open(filename, 'wb') as f:
+  with open(filename, 'w') as f:
 for line in lines:
   f.write(line)
   if line.startswith('.. toctree::'):
@@ -289,7 +291,7 @@ def write_docs(module_path, module, chec
   filename = os.path.normpath(os.path.join(
   module_path, '../../docs/clang-tidy/checks/', check_name_dashes + 
'.rst'))
   print('Creating %s...' % filename)
-  with open(filename, 'wb') as f:
+  with open(filename, 'w') as f:
 f.write(""".. title:: clang-tidy - %(check_name_dashes)s
 
 %(check_name_dashes)s
@@ -333,7 +335,7 @@ def m

[clang-tools-extra] r299068 - [clang-tidy] add aliases for hicpp module

2017-03-30 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Thu Mar 30 06:57:54 2017
New Revision: 299068

URL: http://llvm.org/viewvc/llvm-project?rev=299068&view=rev
Log:
[clang-tidy] add aliases for hicpp module

Summary: Add some hicpp checks that can be implmented as alises for existing 
clang-tidy checks:
hicpp-explicit-conversions
hicpp-function-size
hicpp-named-parameter
hicpp-invalid-access-moved
hicpp-member-init
hicpp-new-delete-operators
hicpp-noexcept-move
hicpp-special-member-functions
hicpp-undelegated-constructor
hicpp-use-equals-default
hicpp-use-equals-delete
hicpp-use-override

Reviewers: dberlin, jbcoe, aaron.ballman, alexfh

Reviewed By: aaron.ballman

Subscribers: JDevlieghere

Differential Revision: https://reviews.llvm.org/D30383

Patch By: Jonas Toth

Added:

clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-explicit-conversions.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-function-size.rst

clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-invalid-access-moved.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-member-init.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-named-parameter.rst

clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-new-delete-operators.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-noexcept-move.rst

clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-special-member-functions.rst

clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-undelegated-constructor.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-use-equals-default.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-use-equals-delete.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-use-override.rst
Modified:
clang-tools-extra/trunk/clang-tidy/hicpp/HICPPTidyModule.cpp
clang-tools-extra/trunk/docs/ReleaseNotes.rst

Modified: clang-tools-extra/trunk/clang-tidy/hicpp/HICPPTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/hicpp/HICPPTidyModule.cpp?rev=299068&r1=299067&r2=299068&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/hicpp/HICPPTidyModule.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/hicpp/HICPPTidyModule.cpp Thu Mar 30 
06:57:54 2017
@@ -10,6 +10,19 @@
 #include "../ClangTidy.h"
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
+#include "../cppcoreguidelines/ProTypeMemberInitCheck.h"
+#include "../cppcoreguidelines/SpecialMemberFunctionsCheck.h"
+#include "../google/DefaultArgumentsCheck.h"
+#include "../google/ExplicitConstructorCheck.h"
+#include "../misc/NewDeleteOverloadsCheck.h"
+#include "../misc/NoexceptMoveConstructorCheck.h"
+#include "../misc/UndelegatedConstructor.h"
+#include "../misc/UseAfterMoveCheck.h"
+#include "../modernize/UseEqualsDefaultCheck.h"
+#include "../modernize/UseEqualsDeleteCheck.h"
+#include "../modernize/UseOverrideCheck.h"
+#include "../readability/FunctionSizeCheck.h"
+#include "../readability/IdentifierNamingCheck.h"
 #include "NoAssemblerCheck.h"
 
 namespace clang {
@@ -19,8 +32,32 @@ namespace hicpp {
 class HICPPModule : public ClangTidyModule {
 public:
   void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
-CheckFactories.registerCheck(
-"hicpp-no-assembler");
+CheckFactories.registerCheck(
+"hicpp-explicit-conversions");
+CheckFactories.registerCheck(
+"hicpp-function-size");
+CheckFactories.registerCheck(
+"hicpp-named-parameter");
+CheckFactories.registerCheck(
+"hicpp-invalid-access-moved");
+CheckFactories.registerCheck(
+"hicpp-member-init");
+CheckFactories.registerCheck(
+"hicpp-new-delete-operators");
+CheckFactories.registerCheck(
+"hicpp-noexcept-move");
+CheckFactories.registerCheck("hicpp-no-assembler");
+CheckFactories
+.registerCheck(
+"hicpp-special-member-functions");
+CheckFactories.registerCheck(
+"hicpp-undelegated-constructor");
+CheckFactories.registerCheck(
+"hicpp-use-equals-default");
+CheckFactories.registerCheck(
+"hicpp-use-equals-delete");
+CheckFactories.registerCheck(
+"hicpp-use-override");
   }
 };
 

Modified: clang-tools-extra/trunk/docs/ReleaseNotes.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/ReleaseNotes.rst?rev=299068&r1=299067&r2=299068&view=diff
==
--- clang-tools-extra/trunk/docs/ReleaseNotes.rst (original)
+++ clang-tools-extra/trunk/docs/ReleaseNotes.rst Thu Mar 30 06:57:54 2017
@@ -76,10 +76,10 @@ Improvements to clang-tidy
 
   Finds functions that have more then `ParameterThreshold` parameters and 
emits a warning.
 
-- New `safety-no-assembler
-  `_ 
check
+- New `hicpp` module
 
-  Finds uses of inline ass

[clang-tools-extra] r299070 - [clang-tidy] fix for linker errors in hicpp checks

2017-03-30 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Thu Mar 30 07:31:02 2017
New Revision: 299070

URL: http://llvm.org/viewvc/llvm-project?rev=299070&view=rev
Log:
[clang-tidy] fix for linker errors in hicpp checks

Speculative fix for linker errors in r299068.

Modified:
clang-tools-extra/trunk/clang-tidy/hicpp/CMakeLists.txt

Modified: clang-tools-extra/trunk/clang-tidy/hicpp/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/hicpp/CMakeLists.txt?rev=299070&r1=299069&r2=299070&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/hicpp/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/hicpp/CMakeLists.txt Thu Mar 30 07:31:02 
2017
@@ -10,5 +10,10 @@ add_clang_library(clangTidyHICPPModule
   clangBasic
   clangLex
   clangTidy
+  clangTidyCppCoreGuidelinesModule
+  clangTidyGoogleModule
+  clangTidyMiscModule
+  clangTidyModernizeModule
+  clangTidyReadabilityModule
   clangTidyUtils
   )


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r299071 - [clang-tidy] fix docs in hicpp checks

2017-03-30 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Thu Mar 30 07:59:41 2017
New Revision: 299071

URL: http://llvm.org/viewvc/llvm-project?rev=299071&view=rev
Log:
[clang-tidy] fix docs in hicpp checks

Fix for sphinx-doc warnings in r299068.

Modified:
clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-noexcept-move.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-noexcept-move.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-noexcept-move.rst?rev=299071&r1=299070&r2=299071&view=diff
==
--- clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-noexcept-move.rst 
(original)
+++ clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-noexcept-move.rst Thu 
Mar 30 07:59:41 2017
@@ -4,4 +4,4 @@ hicpp-noexcept-move
 ===
 
 This check is an alias for `misc-noexcept-moveconstructor 
`_.
-Checks `rule 12.5.4 
`_
 to mark move assignment and move construction `noexcept`.

Modified: clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst?rev=299071&r1=299070&r2=299071&view=diff
==
--- clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst (original)
+++ clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst Thu Mar 30 07:59:41 
2017
@@ -53,7 +53,19 @@ Clang-Tidy Checks
google-runtime-memset
google-runtime-operator
google-runtime-references
+   hicpp-explicit-conversions
+   hicpp-function-size
+   hicpp-invalid-access-moved
+   hicpp-member-init
+   hicpp-named-parameter
+   hicpp-new-delete-operators
hicpp-no-assembler
+   hicpp-noexcept-move
+   hicpp-special-member-functions
+   hicpp-undelegated-constructor
+   hicpp-use-equals-default
+   hicpp-use-equals-delete
+   hicpp-use-override
llvm-header-guard
llvm-include-order
llvm-namespace-comment


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r291907 - Revert "Support for Python 3 in libclang python bindings"

2017-01-13 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Fri Jan 13 10:06:59 2017
New Revision: 291907

URL: http://llvm.org/viewvc/llvm-project?rev=291907&view=rev
Log:
Revert "Support for Python 3 in libclang python bindings"

This reverts commit 4464581bb63e9789e9ee231a8c8800be5f614743.

Memory access issues on Linux were reported by Mathieu Duponchelle and
discussed here: https://reviews.llvm.org/D26082.

Modified:
cfe/trunk/bindings/python/clang/cindex.py
cfe/trunk/bindings/python/tests/cindex/test_translation_unit.py

Modified: cfe/trunk/bindings/python/clang/cindex.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/cindex.py?rev=291907&r1=291906&r2=291907&view=diff
==
--- cfe/trunk/bindings/python/clang/cindex.py (original)
+++ cfe/trunk/bindings/python/clang/cindex.py Fri Jan 13 10:06:59 2017
@@ -64,7 +64,6 @@ call is efficient.
 
 from ctypes import *
 import collections
-import sys
 
 import clang.enumerations
 
@@ -74,33 +73,6 @@ import clang.enumerations
 # this by marshalling object arguments as void**.
 c_object_p = POINTER(c_void_p)
 
-if sys.version_info[0] > 2:
-# Python 3 strings are unicode, translate them to/from utf8 for C-interop
-# Python 3 replaces xrange with range, we want xrange behaviour
-xrange = range
-
-class c_string_p(c_char_p):
-def __init__(self, p=None):
-if type(p) == str:
-p = p.encode("utf8")
-super(c_char_p, self).__init__(p)
-
-def __str__(self):
-return str(self.value)
-
-@property
-def value(self):
-if super(c_char_p, self).value is None:
-return None
-return super(c_char_p, self).value.decode("utf8")
-
-@classmethod
-def from_param(cls, param):
-return cls(param)
-else:
-c_string_p = c_char_p
-
-
 callbacks = {}
 
 ### Exception Classes ###
@@ -175,7 +147,7 @@ class CachedProperty(object):
 class _CXString(Structure):
 """Helper for transforming CXString results."""
 
-_fields_ = [("spelling", c_string_p), ("free", c_int)]
+_fields_ = [("spelling", c_char_p), ("free", c_int)]
 
 def __del__(self):
 conf.lib.clang_disposeString(self)
@@ -357,7 +329,7 @@ class Diagnostic(object):
 
 @property
 def spelling(self):
-return str(conf.lib.clang_getDiagnosticSpelling(self))
+return conf.lib.clang_getDiagnosticSpelling(self)
 
 @property
 def ranges(self):
@@ -386,8 +358,8 @@ class Diagnostic(object):
 
 def __getitem__(self, key):
 range = SourceRange()
-value = str(conf.lib.clang_getDiagnosticFixIt(self.diag, key,
-byref(range)))
+value = conf.lib.clang_getDiagnosticFixIt(self.diag, key,
+byref(range))
 if len(value) == 0:
 raise IndexError
 
@@ -420,12 +392,12 @@ class Diagnostic(object):
 @property
 def category_name(self):
 """The string name of the category for this diagnostic."""
-return str(conf.lib.clang_getDiagnosticCategoryText(self))
+return conf.lib.clang_getDiagnosticCategoryText(self)
 
 @property
 def option(self):
 """The command-line option that enables this diagnostic."""
-return str(conf.lib.clang_getDiagnosticOption(self, None))
+return conf.lib.clang_getDiagnosticOption(self, None)
 
 @property
 def disable_option(self):
@@ -433,7 +405,7 @@ class Diagnostic(object):
 disable = _CXString()
 conf.lib.clang_getDiagnosticOption(self, byref(disable))
 
-return str(conf.lib.clang_getCString(disable))
+return conf.lib.clang_getCString(disable)
 
 def format(self, options=None):
 """
@@ -582,8 +554,8 @@ class BaseEnumeration(object):
 if value >= len(self.__class__._kinds):
 self.__class__._kinds += [None] * (value - 
len(self.__class__._kinds) + 1)
 if self.__class__._kinds[value] is not None:
-raise ValueError('{0} value {1} already loaded'.format(
-str(self.__class__), value))
+raise ValueError,'{0} value {1} already loaded'.format(
+str(self.__class__), value)
 self.value = value
 self.__class__._kinds[value] = self
 self.__class__._name_map = None
@@ -600,12 +572,12 @@ class BaseEnumeration(object):
 for key, value in self.__class__.__dict__.items():
 if isinstance(value, self.__class__):
 self._name_map[value] = key
-return str(self._name_map[self])
+return self._name_map[self]
 
 @classmethod
 def from_id(cls, id):
 if id >= len(cls._kinds) or cls._kinds[id] is None:
-raise ValueError('Unknown template argument kind %d' % id)
+raise ValueError,'Unknown template argument kind %d' % id
 retu

r292247 - Fix Python 3 language issues and add an explicit check for Python version == 2.

2017-01-17 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Tue Jan 17 14:03:54 2017
New Revision: 292247

URL: http://llvm.org/viewvc/llvm-project?rev=292247&view=rev
Log:
Fix Python 3 language issues and add an explicit check for Python version == 2.

Summary:
Python bindings cannot support Python 3 without work being done to fix Unicode 
c-string conversion.

This was attempted in https://reviews.llvm.org/D26082. That patch was reverted 
due to memory access issues on Linux.

This revision fixes enough language compatibility issues for the clang module 
to be loaded and raise an error if the Python version is not 2.

Reviewers: mgorny, MathieuDuponchelle, rengolin, compnerd

Reviewed By: compnerd

Differential Revision: https://reviews.llvm.org/D28682

Modified:
cfe/trunk/bindings/python/clang/__init__.py
cfe/trunk/bindings/python/clang/cindex.py

Modified: cfe/trunk/bindings/python/clang/__init__.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/__init__.py?rev=292247&r1=292246&r2=292247&view=diff
==
--- cfe/trunk/bindings/python/clang/__init__.py (original)
+++ cfe/trunk/bindings/python/clang/__init__.py Tue Jan 17 14:03:54 2017
@@ -20,5 +20,13 @@ The available modules are:
 Bindings for the Clang indexing library.
 """
 
+
+# Python 3 uses unicode for strings. The bindings, in particular the 
interaction
+# with ctypes, need modifying to handle conversions between unicode and
+# c-strings.
+import sys 
+if sys.version_info[0] != 2: 
+raise Exception("Only Python 2 is supported.")
+
 __all__ = ['cindex']
 

Modified: cfe/trunk/bindings/python/clang/cindex.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/cindex.py?rev=292247&r1=292246&r2=292247&view=diff
==
--- cfe/trunk/bindings/python/clang/cindex.py (original)
+++ cfe/trunk/bindings/python/clang/cindex.py Tue Jan 17 14:03:54 2017
@@ -554,8 +554,8 @@ class BaseEnumeration(object):
 if value >= len(self.__class__._kinds):
 self.__class__._kinds += [None] * (value - 
len(self.__class__._kinds) + 1)
 if self.__class__._kinds[value] is not None:
-raise ValueError,'{0} value {1} already loaded'.format(
-str(self.__class__), value)
+raise ValueError('{0} value {1} already loaded'.format(
+str(self.__class__), value))
 self.value = value
 self.__class__._kinds[value] = self
 self.__class__._name_map = None
@@ -577,7 +577,7 @@ class BaseEnumeration(object):
 @classmethod
 def from_id(cls, id):
 if id >= len(cls._kinds) or cls._kinds[id] is None:
-raise ValueError,'Unknown template argument kind %d' % id
+raise ValueError('Unknown template argument kind %d' % id)
 return cls._kinds[id]
 
 def __repr__(self):
@@ -1777,7 +1777,7 @@ class StorageClass(object):
 if value >= len(StorageClass._kinds):
 StorageClass._kinds += [None] * (value - len(StorageClass._kinds) 
+ 1)
 if StorageClass._kinds[value] is not None:
-raise ValueError,'StorageClass already loaded'
+raise ValueError('StorageClass already loaded')
 self.value = value
 StorageClass._kinds[value] = self
 StorageClass._name_map = None
@@ -1798,7 +1798,7 @@ class StorageClass(object):
 @staticmethod
 def from_id(id):
 if id >= len(StorageClass._kinds) or not StorageClass._kinds[id]:
-raise ValueError,'Unknown storage class %d' % id
+raise ValueError('Unknown storage class %d' % id)
 return StorageClass._kinds[id]
 
 def __repr__(self):
@@ -2729,9 +2729,9 @@ class TranslationUnit(ClangObject):
 # FIXME: It would be great to support an efficient version
 # of this, one day.
 value = value.read()
-print value
+print(value)
 if not isinstance(value, str):
-raise TypeError,'Unexpected unsaved file contents.'
+raise TypeError('Unexpected unsaved file contents.')
 unsaved_files_array[i].name = name
 unsaved_files_array[i].contents = value
 unsaved_files_array[i].length = len(value)
@@ -2793,9 +2793,9 @@ class TranslationUnit(ClangObject):
 # FIXME: It would be great to support an efficient version
 # of this, one day.
 value = value.read()
-print value
+print(value)
 if not isinstance(value, str):
-raise TypeError,'Unexpected unsaved file contents.'
+raise TypeError('Unexpected unsaved file contents.')
 unsaved_files_array[i].name = name
 unsaved_files_array[i].cont

[clang-tools-extra] r294255 - [clang-tidy] safety-no-assembler

2017-02-06 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Mon Feb  6 16:57:14 2017
New Revision: 294255

URL: http://llvm.org/viewvc/llvm-project?rev=294255&view=rev
Log:
[clang-tidy] safety-no-assembler

Summary:
Add a new clang-tidy module for safety-critical checks.

Include a check for inline assembler.

Reviewers: Prazek, dtarditi, malcolm.parsons, alexfh, aaron.ballman, idlecode

Reviewed By: idlecode

Subscribers: idlecode, JonasToth, Eugene.Zelenko, mgorny, JDevlieghere, 
cfe-commits

Tags: #clang-tools-extra

Differential Revision: https://reviews.llvm.org/D29267

Added:
clang-tools-extra/trunk/clang-tidy/safety/
clang-tools-extra/trunk/clang-tidy/safety/CMakeLists.txt
clang-tools-extra/trunk/clang-tidy/safety/NoAssemblerCheck.cpp
clang-tools-extra/trunk/clang-tidy/safety/NoAssemblerCheck.h
clang-tools-extra/trunk/clang-tidy/safety/SafetyTidyModule.cpp
clang-tools-extra/trunk/docs/clang-tidy/checks/safety-no-assembler.rst
clang-tools-extra/trunk/test/clang-tidy/safety-no-assembler.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/CMakeLists.txt
clang-tools-extra/trunk/clang-tidy/tool/CMakeLists.txt
clang-tools-extra/trunk/clang-tidy/tool/ClangTidyMain.cpp
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/clang-tidy/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/CMakeLists.txt?rev=294255&r1=294254&r2=294255&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/CMakeLists.txt Mon Feb  6 16:57:14 2017
@@ -38,4 +38,5 @@ add_subdirectory(modernize)
 add_subdirectory(mpi)
 add_subdirectory(performance)
 add_subdirectory(readability)
+add_subdirectory(safety)
 add_subdirectory(utils)

Added: clang-tools-extra/trunk/clang-tidy/safety/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/safety/CMakeLists.txt?rev=294255&view=auto
==
--- clang-tools-extra/trunk/clang-tidy/safety/CMakeLists.txt (added)
+++ clang-tools-extra/trunk/clang-tidy/safety/CMakeLists.txt Mon Feb  6 
16:57:14 2017
@@ -0,0 +1,14 @@
+set(LLVM_LINK_COMPONENTS support)
+
+add_clang_library(clangTidySafetyModule
+  NoAssemblerCheck.cpp
+  SafetyTidyModule.cpp
+
+  LINK_LIBS
+  clangAST
+  clangASTMatchers
+  clangBasic
+  clangLex
+  clangTidy
+  clangTidyUtils
+  )

Added: clang-tools-extra/trunk/clang-tidy/safety/NoAssemblerCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/safety/NoAssemblerCheck.cpp?rev=294255&view=auto
==
--- clang-tools-extra/trunk/clang-tidy/safety/NoAssemblerCheck.cpp (added)
+++ clang-tools-extra/trunk/clang-tidy/safety/NoAssemblerCheck.cpp Mon Feb  6 
16:57:14 2017
@@ -0,0 +1,52 @@
+//===--- NoAssemblerCheck.cpp - 
clang-tidy-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "NoAssemblerCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace ast_matchers {
+AST_MATCHER(VarDecl, isAsm) { return Node.hasAttr(); }
+const internal::VariadicDynCastAllOfMatcher
+fileScopeAsmDecl;
+}
+}
+
+namespace clang {
+namespace tidy {
+namespace safety {
+
+void NoAssemblerCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(asmStmt().bind("asm-stmt"), this);
+  Finder->addMatcher(fileScopeAsmDecl().bind("asm-file-scope"), this);
+  Finder->addMatcher(varDecl(isAsm()).bind("asm-var"), this);
+}
+
+void NoAssemblerCheck::check(const MatchFinder::MatchResult &Result) {
+  Optional ASMLocation;
+  if (const auto *ASM = Result.Nodes.getNodeAs("asm-stmt"))
+ASMLocation = ASM->getAsmLoc();
+  else if (const auto *ASM =
+   Result.Nodes.getNodeAs("asm-file-scope"))
+ASMLocation = ASM->getAsmLoc();
+  else if (const auto *ASM = Result.Nodes.getNodeAs("asm-var"))
+ASMLocation = ASM->getLocation();
+  else
+llvm_unreachable("Unhandled case in matcher.");
+
+  diag(*ASMLocation, "do not use inline assembler in safety-critical code");
+}
+
+} // namespace safety
+} // namespace tidy
+} // namespace clang

Added: clang-tools-extra/trunk/clang-tidy/safety/NoAssemblerCheck.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/safety/NoAssemblerCheck.h?rev=294255&view=auto
==
--- clang-tools-extra/trunk/cla

[clang-tools-extra] r294283 - [clang-tidy] Cleanup of no-assembler check

2017-02-06 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Tue Feb  7 00:19:38 2017
New Revision: 294283

URL: http://llvm.org/viewvc/llvm-project?rev=294283&view=rev
Log:
[clang-tidy] Cleanup of no-assembler check

Address outstanding comments from https://reviews.llvm.org/D29267

Modified:
clang-tools-extra/trunk/clang-tidy/safety/NoAssemblerCheck.cpp

Modified: clang-tools-extra/trunk/clang-tidy/safety/NoAssemblerCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/safety/NoAssemblerCheck.cpp?rev=294283&r1=294282&r2=294283&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/safety/NoAssemblerCheck.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/safety/NoAssemblerCheck.cpp Tue Feb  7 
00:19:38 2017
@@ -10,7 +10,6 @@
 #include "NoAssemblerCheck.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
-#include "clang/Lex/Lexer.h"
 
 using namespace clang::ast_matchers;
 
@@ -33,7 +32,7 @@ void NoAssemblerCheck::registerMatchers(
 }
 
 void NoAssemblerCheck::check(const MatchFinder::MatchResult &Result) {
-  Optional ASMLocation;
+  SourceLocation ASMLocation;
   if (const auto *ASM = Result.Nodes.getNodeAs("asm-stmt"))
 ASMLocation = ASM->getAsmLoc();
   else if (const auto *ASM =
@@ -44,7 +43,7 @@ void NoAssemblerCheck::check(const Match
   else
 llvm_unreachable("Unhandled case in matcher.");
 
-  diag(*ASMLocation, "do not use inline assembler in safety-critical code");
+  diag(ASMLocation, "do not use inline assembler in safety-critical code");
 }
 
 } // namespace safety


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r306483 - [libclang] Support for querying the exception specification type through libclang

2017-06-27 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Tue Jun 27 15:54:56 2017
New Revision: 306483

URL: http://llvm.org/viewvc/llvm-project?rev=306483&view=rev
Log:
[libclang] Support for querying the exception specification type through 
libclang

Summary: This patch exposes the exception specification type (noexcept,
etc.) of a C++ function through libclang and Python clang.cindex.

Reviewers: rsmith, aaron.ballman

Reviewed By: aaron.ballman

Subscribers: jbcoe, cfe-commits

Differential Revision: https://reviews.llvm.org/D34091

Patch by Andrew Bennieston

Added:
cfe/trunk/bindings/python/tests/test_exception_specification_kind.py
Modified:
cfe/trunk/bindings/python/clang/cindex.py
cfe/trunk/include/clang-c/Index.h
cfe/trunk/test/Index/get-cursor.cpp
cfe/trunk/tools/c-index-test/c-index-test.c
cfe/trunk/tools/libclang/CXType.cpp
cfe/trunk/tools/libclang/libclang.exports

Modified: cfe/trunk/bindings/python/clang/cindex.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/cindex.py?rev=306483&r1=306482&r2=306483&view=diff
==
--- cfe/trunk/bindings/python/clang/cindex.py (original)
+++ cfe/trunk/bindings/python/clang/cindex.py Tue Jun 27 15:54:56 2017
@@ -1367,6 +1367,30 @@ TemplateArgumentKind.DECLARATION = Templ
 TemplateArgumentKind.NULLPTR = TemplateArgumentKind(3)
 TemplateArgumentKind.INTEGRAL = TemplateArgumentKind(4)
 
+### Exception Specification Kinds ###
+class ExceptionSpecificationKind(BaseEnumeration):
+"""
+An ExceptionSpecificationKind describes the kind of exception specification
+that a function has.
+"""
+
+# The required BaseEnumeration declarations.
+_kinds = []
+_name_map = None
+
+def __repr__(self):
+return 'ExceptionSpecificationKind.{}'.format(self.name)
+
+ExceptionSpecificationKind.NONE = ExceptionSpecificationKind(0)
+ExceptionSpecificationKind.DYNAMIC_NONE = ExceptionSpecificationKind(1)
+ExceptionSpecificationKind.DYNAMIC = ExceptionSpecificationKind(2)
+ExceptionSpecificationKind.MS_ANY = ExceptionSpecificationKind(3)
+ExceptionSpecificationKind.BASIC_NOEXCEPT = ExceptionSpecificationKind(4)
+ExceptionSpecificationKind.COMPUTED_NOEXCEPT = ExceptionSpecificationKind(5)
+ExceptionSpecificationKind.UNEVALUATED = ExceptionSpecificationKind(6)
+ExceptionSpecificationKind.UNINSTANTIATED = ExceptionSpecificationKind(7)
+ExceptionSpecificationKind.UNPARSED = ExceptionSpecificationKind(8)
+
 ### Cursors ###
 
 class Cursor(Structure):
@@ -1587,6 +1611,18 @@ class Cursor(Structure):
 return self._result_type
 
 @property
+def exception_specification_kind(self):
+'''
+Retrieve the exception specification kind, which is one of the values
+from the ExceptionSpecificationKind enumeration.
+'''
+if not hasattr(self, '_exception_specification_kind'):
+exc_kind = conf.lib.clang_getCursorExceptionSpecificationType(self)
+self._exception_specification_kind = 
ExceptionSpecificationKind.from_id(exc_kind)
+
+return self._exception_specification_kind
+
+@property
 def underlying_typedef_type(self):
 """Return the underlying type of a typedef declaration.
 
@@ -2254,6 +2290,14 @@ class Type(Structure):
 callbacks['fields_visit'](visitor), fields)
 return iter(fields)
 
+def get_exception_specification_kind(self):
+"""
+Return the kind of the exception specification; a value from
+the ExceptionSpecificationKind enumeration.
+"""
+return ExceptionSpecificationKind.from_id(
+conf.lib.clang.getExceptionSpecificationType(self))
+
 @property
 def spelling(self):
 """Retrieve the spelling of this Type."""

Added: cfe/trunk/bindings/python/tests/test_exception_specification_kind.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/tests/test_exception_specification_kind.py?rev=306483&view=auto
==
--- cfe/trunk/bindings/python/tests/test_exception_specification_kind.py (added)
+++ cfe/trunk/bindings/python/tests/test_exception_specification_kind.py Tue 
Jun 27 15:54:56 2017
@@ -0,0 +1,27 @@
+import clang.cindex
+from clang.cindex import ExceptionSpecificationKind
+from .util import get_tu
+
+
+def find_function_declarations(node, declarations=[]):
+if node.kind == clang.cindex.CursorKind.FUNCTION_DECL:
+declarations.append((node.spelling, node.exception_specification_kind))
+for child in node.get_children():
+declarations = find_function_declarations(child, declarations)
+return declarations
+
+
+def test_exception_specification_kind():
+source = """int square1(int x);
+int square2(int x) noexcept;
+int square3(int x) noexcept(noexcept(x * x));"""
+
+tu = get_tu(source, lang='cpp', flags=['-std=c++14

r322540 - [libclang] Add PrintingPolicy for pretty printing declarations

2018-01-16 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Tue Jan 16 02:19:56 2018
New Revision: 322540

URL: http://llvm.org/viewvc/llvm-project?rev=322540&view=rev
Log:
[libclang] Add PrintingPolicy for pretty printing declarations

Summary:
Introduce clang_getCursorPrettyPrinted() for pretty printing
declarations. Expose also PrintingPolicy, so the user gets more
fine-grained control of the entities being printed.

The already existing clang_getCursorDisplayName() is pretty limited -
for example, it does not handle return types, parameter names or default
arguments for function declarations. Addressing these issues in
clang_getCursorDisplayName() would mean to duplicate existing code
(e.g. clang::DeclPrinter), so rather expose new API to access the
existing functionality.

Reviewed By: jbcoe

Subscribers: cfe-commits

Tags: #clang

Patch by nik (Nikolai Kosjar)

Differential Revision: https://reviews.llvm.org/D39903

Modified:
cfe/trunk/include/clang-c/Index.h
cfe/trunk/test/Index/print-display-names.cpp
cfe/trunk/tools/c-index-test/c-index-test.c
cfe/trunk/tools/libclang/CIndex.cpp
cfe/trunk/tools/libclang/libclang.exports
cfe/trunk/unittests/libclang/LibclangTest.cpp

Modified: cfe/trunk/include/clang-c/Index.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang-c/Index.h?rev=322540&r1=322539&r2=322540&view=diff
==
--- cfe/trunk/include/clang-c/Index.h (original)
+++ cfe/trunk/include/clang-c/Index.h Tue Jan 16 02:19:56 2018
@@ -32,7 +32,7 @@
  * compatible, thus CINDEX_VERSION_MAJOR is expected to remain stable.
  */
 #define CINDEX_VERSION_MAJOR 0
-#define CINDEX_VERSION_MINOR 46
+#define CINDEX_VERSION_MINOR 47
 
 #define CINDEX_VERSION_ENCODE(major, minor) ( \
   ((major) * 1)   \
@@ -4092,6 +4092,89 @@ CINDEX_LINKAGE CXSourceRange clang_Curso
   unsigned options);
 
 /**
+ * \brief Opaque pointer representing a policy that controls pretty printing
+ * for \c clang_getCursorPrettyPrinted.
+ */
+typedef void *CXPrintingPolicy;
+
+/**
+ * \brief Properties for the printing policy.
+ *
+ * See \c clang::PrintingPolicy for more information.
+ */
+enum CXPrintingPolicyProperty {
+  CXPrintingPolicy_Indentation,
+  CXPrintingPolicy_SuppressSpecifiers,
+  CXPrintingPolicy_SuppressTagKeyword,
+  CXPrintingPolicy_IncludeTagDefinition,
+  CXPrintingPolicy_SuppressScope,
+  CXPrintingPolicy_SuppressUnwrittenScope,
+  CXPrintingPolicy_SuppressInitializers,
+  CXPrintingPolicy_ConstantArraySizeAsWritten,
+  CXPrintingPolicy_AnonymousTagLocations,
+  CXPrintingPolicy_SuppressStrongLifetime,
+  CXPrintingPolicy_SuppressLifetimeQualifiers,
+  CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors,
+  CXPrintingPolicy_Bool,
+  CXPrintingPolicy_Restrict,
+  CXPrintingPolicy_Alignof,
+  CXPrintingPolicy_UnderscoreAlignof,
+  CXPrintingPolicy_UseVoidForZeroParams,
+  CXPrintingPolicy_TerseOutput,
+  CXPrintingPolicy_PolishForDeclaration,
+  CXPrintingPolicy_Half,
+  CXPrintingPolicy_MSWChar,
+  CXPrintingPolicy_IncludeNewlines,
+  CXPrintingPolicy_MSVCFormatting,
+  CXPrintingPolicy_ConstantsAsWritten,
+  CXPrintingPolicy_SuppressImplicitBase,
+  CXPrintingPolicy_FullyQualifiedName,
+
+  CXPrintingPolicy_LastProperty = CXPrintingPolicy_FullyQualifiedName
+};
+
+/**
+ * \brief Get a property value for the given printing policy.
+ */
+unsigned
+clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
+ enum CXPrintingPolicyProperty Property);
+
+/**
+ * \brief Set a property value for the given printing policy.
+ */
+void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
+  enum CXPrintingPolicyProperty Property,
+  unsigned Value);
+
+/**
+ * \brief Retrieve the default policy for the cursor.
+ *
+ * The policy should be released after use with \c
+ * clang_PrintingPolicy_dispose.
+ */
+CINDEX_LINKAGE CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor);
+
+/**
+ * \brief Release a printing policy.
+ */
+CINDEX_LINKAGE void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy);
+
+/**
+ * \brief Pretty print declarations.
+ *
+ * \param Cursor The cursor representing a declaration.
+ *
+ * \param Policy The policy to control the entities being printed. If
+ * NULL, a default policy is used.
+ *
+ * \returns The pretty printed declaration or the empty string for
+ * other cursors.
+ */
+CINDEX_LINKAGE CXString clang_getCursorPrettyPrinted(CXCursor Cursor,
+ CXPrintingPolicy Policy);
+
+/**
  * \brief Retrieve the display name for the entity referenced by this cursor.
  *
  * The display name contains extra information that helps identify the cursor,

Modified: cfe/trunk/test/Index/print-display-names.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/print-display-names.cpp?rev=32

r300829 - Add Python 3 support to clang.cindex

2017-04-20 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Thu Apr 20 05:11:01 2017
New Revision: 300829

URL: http://llvm.org/viewvc/llvm-project?rev=300829&view=rev
Log:
Add Python 3 support to clang.cindex

Summary:
Introduce an interop string to convert from unicode to c-strings where needed.
Add missing conversions from _CXString to strings in function registrations.
Explicitly evaluate lists where Python 3's lazy iterators would not otherwise 
do so.

This is an improvement upon the reverted change proposed in 
https://reviews.llvm.org/D26082

Reviewers: compnerd, skalinichev, modocache, MathieuDuponchelle

Reviewed By: compnerd

Subscribers: cfe-commits

Tags: #clang-c

Differential Revision: https://reviews.llvm.org/D31568

Modified:
cfe/trunk/bindings/python/clang/__init__.py
cfe/trunk/bindings/python/clang/cindex.py
cfe/trunk/bindings/python/tests/cindex/test_translation_unit.py

Modified: cfe/trunk/bindings/python/clang/__init__.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/__init__.py?rev=300829&r1=300828&r2=300829&view=diff
==
--- cfe/trunk/bindings/python/clang/__init__.py (original)
+++ cfe/trunk/bindings/python/clang/__init__.py Thu Apr 20 05:11:01 2017
@@ -20,13 +20,5 @@ The available modules are:
 Bindings for the Clang indexing library.
 """
 
-
-# Python 3 uses unicode for strings. The bindings, in particular the 
interaction
-# with ctypes, need modifying to handle conversions between unicode and
-# c-strings.
-import sys 
-if sys.version_info[0] != 2: 
-raise Exception("Only Python 2 is supported.")
-
 __all__ = ['cindex']
 

Modified: cfe/trunk/bindings/python/clang/cindex.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/cindex.py?rev=300829&r1=300828&r2=300829&view=diff
==
--- cfe/trunk/bindings/python/clang/cindex.py (original)
+++ cfe/trunk/bindings/python/clang/cindex.py Thu Apr 20 05:11:01 2017
@@ -67,6 +67,60 @@ import collections
 
 import clang.enumerations
 
+import sys
+if sys.version_info[0] == 3:
+# Python 3 strings are unicode, translate them to/from utf8 for C-interop.
+class c_interop_string(c_char_p):
+
+def __init__(self, p=None):
+if p is None:
+p = ""
+if isinstance(p, str):
+p = p.encode("utf8")
+super(c_char_p, self).__init__(p)
+
+def __str__(self):
+return self.value
+
+@property
+def value(self):
+if super(c_char_p, self).value is None:
+return None
+return super(c_char_p, self).value.decode("utf8")
+
+@classmethod
+def from_param(cls, param):
+if isinstance(param, str):
+return cls(param)
+if isinstance(param, bytes):
+return cls(param)
+raise TypeError("Cannot convert '{}' to 
'{}'".format(type(param).__name__, cls.__name__))
+
+@staticmethod
+def to_python_string(x, *args):
+return x.value
+
+def b(x):
+if isinstance(x, bytes):
+return x
+return x.encode('utf8')
+
+xrange = range
+
+elif sys.version_info[0] == 2:
+# Python 2 strings are utf8 byte strings, no translation is needed for
+# C-interop.
+c_interop_string = c_char_p
+
+def _to_python_string(x, *args):
+return x
+
+c_interop_string.to_python_string = staticmethod(_to_python_string)
+
+def b(x):
+return x
+
+
 # ctypes doesn't implicitly convert c_void_p to the appropriate wrapper
 # object. This is a problem, because it means that from_parameter will see an
 # integer and pass the wrong value on platforms where int != void*. Work around
@@ -157,6 +211,7 @@ class _CXString(Structure):
 assert isinstance(res, _CXString)
 return conf.lib.clang_getCString(res)
 
+
 class SourceLocation(Structure):
 """
 A SourceLocation represents a particular location within a source file.
@@ -596,7 +651,7 @@ class CursorKind(BaseEnumeration):
 @staticmethod
 def get_all_kinds():
 """Return all CursorKind enumeration instances."""
-return filter(None, CursorKind._kinds)
+return [x for x in CursorKind._kinds if not x is None]
 
 def is_declaration(self):
 """Test if this is a declaration kind."""
@@ -2128,7 +2183,7 @@ class Type(Structure):
 """
 Retrieve the offset of a field in the record.
 """
-return conf.lib.clang_Type_getOffsetOf(self, c_char_p(fieldname))
+return conf.lib.clang_Type_getOffsetOf(self, fieldname)
 
 def get_ref_qualifier(self):
 """
@@ -2239,7 +2294,7 @@ class CompletionChunk:
 def spelling(self):
 if self.__kindNumber in SpellingCache:
 return SpellingCache[self.__kindNumber]
-return conf.lib.clang_getCompletionCh

[clang-tools-extra] r285907 - [clang-tidy] Ignore forward declarations without definitions in the same translation unit in readability-identifier-naming

2016-11-03 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Thu Nov  3 08:52:09 2016
New Revision: 285907

URL: http://llvm.org/viewvc/llvm-project?rev=285907&view=rev
Log:
[clang-tidy] Ignore forward declarations without definitions in the same 
translation unit in readability-identifier-naming

Summary: This change ensures that forward declarations of classes are not 
considered for identifier naming checks within a translation unit.

Reviewers: alexfh, aaron.ballman

Subscribers: mgehre

Differential Revision: https://reviews.llvm.org/D22571

Modified:
clang-tools-extra/trunk/clang-tidy/readability/IdentifierNamingCheck.cpp
clang-tools-extra/trunk/test/clang-tidy/readability-identifier-naming.cpp

Modified: 
clang-tools-extra/trunk/clang-tidy/readability/IdentifierNamingCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/IdentifierNamingCheck.cpp?rev=285907&r1=285906&r2=285907&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/readability/IdentifierNamingCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/readability/IdentifierNamingCheck.cpp 
Thu Nov  3 08:52:09 2016
@@ -395,6 +395,9 @@ static StyleKind findStyleKind(
 if (Decl->isAnonymousStructOrUnion())
   return SK_Invalid;
 
+if (!Decl->getCanonicalDecl()->isThisDeclarationADefinition())
+  return SK_Invalid;
+
 if (Decl->hasDefinition() && Decl->isAbstract() &&
 NamingStyles[SK_AbstractClass].isSet())
   return SK_AbstractClass;

Modified: 
clang-tools-extra/trunk/test/clang-tidy/readability-identifier-naming.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/readability-identifier-naming.cpp?rev=285907&r1=285906&r2=285907&view=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/readability-identifier-naming.cpp 
(original)
+++ clang-tools-extra/trunk/test/clang-tidy/readability-identifier-naming.cpp 
Thu Nov  3 08:52:09 2016
@@ -190,6 +190,11 @@ public:
 // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: invalid case style for class 
member 'ClassMember_2'
 // CHECK-FIXES: {{^}}static int ClassMember2;{{$}}
 };
+class my_class;
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for class 
'my_class'
+// CHECK-FIXES: {{^}}class CMyClass;{{$}}
+
+class my_forward_declared_class; // No warning should be triggered.
 
 const int my_class::classConstant = 4;
 // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: invalid case style for class 
constant 'classConstant'


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r285909 - Support for Python 3 in libclang python bindings

2016-11-03 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Thu Nov  3 08:55:34 2016
New Revision: 285909

URL: http://llvm.org/viewvc/llvm-project?rev=285909&view=rev
Log:
Support for Python 3 in libclang python bindings

Summary:
Python bindings tests now pass in Python 3.

`map` in Python 3 is lazily evaluated so the method by which functions are 
registered needed updating.

Strings are unicode in Python 3 not UTF-8, I've tried to create an new 
c_types-like class (c_string_p) to automate the conversion.

String conversions made explicit where required.

Reviewers: eliben, nemanjai, skalinichev, compnerd

Subscribers: mgorny, cfe-commits

Differential Revision: https://reviews.llvm.org/D26082

Modified:
cfe/trunk/bindings/python/clang/cindex.py
cfe/trunk/bindings/python/tests/cindex/test_translation_unit.py

Modified: cfe/trunk/bindings/python/clang/cindex.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/cindex.py?rev=285909&r1=285908&r2=285909&view=diff
==
--- cfe/trunk/bindings/python/clang/cindex.py (original)
+++ cfe/trunk/bindings/python/clang/cindex.py Thu Nov  3 08:55:34 2016
@@ -64,6 +64,7 @@ call is efficient.
 
 from ctypes import *
 import collections
+import sys
 
 import clang.enumerations
 
@@ -73,6 +74,33 @@ import clang.enumerations
 # this by marshalling object arguments as void**.
 c_object_p = POINTER(c_void_p)
 
+if sys.version_info[0] > 2:
+# Python 3 strings are unicode, translate them to/from utf8 for C-interop
+# Python 3 replaces xrange with range, we want xrange behaviour
+xrange = range
+
+class c_string_p(c_char_p):
+def __init__(self, p=None):
+if type(p) == str:
+p = p.encode("utf8")
+super(c_char_p, self).__init__(p)
+
+def __str__(self):
+return str(self.value)
+
+@property
+def value(self):
+if super(c_char_p, self).value is None:
+return None
+return super(c_char_p, self).value.decode("utf8")
+
+@classmethod
+def from_param(cls, param):
+return cls(param)
+else:
+c_string_p = c_char_p
+
+
 callbacks = {}
 
 ### Exception Classes ###
@@ -147,7 +175,7 @@ class CachedProperty(object):
 class _CXString(Structure):
 """Helper for transforming CXString results."""
 
-_fields_ = [("spelling", c_char_p), ("free", c_int)]
+_fields_ = [("spelling", c_string_p), ("free", c_int)]
 
 def __del__(self):
 conf.lib.clang_disposeString(self)
@@ -329,7 +357,7 @@ class Diagnostic(object):
 
 @property
 def spelling(self):
-return conf.lib.clang_getDiagnosticSpelling(self)
+return str(conf.lib.clang_getDiagnosticSpelling(self))
 
 @property
 def ranges(self):
@@ -358,8 +386,8 @@ class Diagnostic(object):
 
 def __getitem__(self, key):
 range = SourceRange()
-value = conf.lib.clang_getDiagnosticFixIt(self.diag, key,
-byref(range))
+value = str(conf.lib.clang_getDiagnosticFixIt(self.diag, key,
+byref(range)))
 if len(value) == 0:
 raise IndexError
 
@@ -392,12 +420,12 @@ class Diagnostic(object):
 @property
 def category_name(self):
 """The string name of the category for this diagnostic."""
-return conf.lib.clang_getDiagnosticCategoryText(self)
+return str(conf.lib.clang_getDiagnosticCategoryText(self))
 
 @property
 def option(self):
 """The command-line option that enables this diagnostic."""
-return conf.lib.clang_getDiagnosticOption(self, None)
+return str(conf.lib.clang_getDiagnosticOption(self, None))
 
 @property
 def disable_option(self):
@@ -405,7 +433,7 @@ class Diagnostic(object):
 disable = _CXString()
 conf.lib.clang_getDiagnosticOption(self, byref(disable))
 
-return conf.lib.clang_getCString(disable)
+return str(conf.lib.clang_getCString(disable))
 
 def format(self, options=None):
 """
@@ -554,8 +582,8 @@ class BaseEnumeration(object):
 if value >= len(self.__class__._kinds):
 self.__class__._kinds += [None] * (value - 
len(self.__class__._kinds) + 1)
 if self.__class__._kinds[value] is not None:
-raise ValueError,'{0} value {1} already loaded'.format(
-str(self.__class__), value)
+raise ValueError('{0} value {1} already loaded'.format(
+str(self.__class__), value))
 self.value = value
 self.__class__._kinds[value] = self
 self.__class__._name_map = None
@@ -572,12 +600,12 @@ class BaseEnumeration(object):
 for key, value in self.__class__.__dict__.items():
 if isinstance(value, self.__class__):
 self._name_map[value] = key
-return self._name_map[self]
+return

[clang-tools-extra] r277262 - [clang-tidy] add check cppcoreguidelines-special-member-functions

2016-07-30 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Sat Jul 30 03:58:54 2016
New Revision: 277262

URL: http://llvm.org/viewvc/llvm-project?rev=277262&view=rev
Log:
[clang-tidy] add check cppcoreguidelines-special-member-functions

Summary:
Check for classes that violate the rule of five and zero as specified in 
CppCoreGuidelines:

"If a class defines or deletes a default operation then it should define or 
delete them all."

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c21-if-you-define-or-delete-any-default-operation-define-or-delete-them-all.

Reviewers: alexfh, sbenza, aaron.ballman

Subscribers: Prazek, Eugene.Zelenko, cfe-commits, ericLemanissier, nemanjai

Projects: #clang-tools-extra

Differential Revision: https://reviews.llvm.org/D22513

Added:

clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp

clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h

clang-tools-extra/trunk/docs/clang-tidy/checks/cppcoreguidelines-special-member-functions.rst

clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-special-member-functions-cxx-03.cpp

clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-special-member-functions.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/CMakeLists.txt

clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/CMakeLists.txt?rev=277262&r1=277261&r2=277262&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/CMakeLists.txt 
(original)
+++ clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/CMakeLists.txt Sat Jul 
30 03:58:54 2016
@@ -13,6 +13,7 @@ add_clang_library(clangTidyCppCoreGuidel
   ProTypeStaticCastDowncastCheck.cpp
   ProTypeUnionAccessCheck.cpp
   ProTypeVarargCheck.cpp
+  SpecialMemberFunctionsCheck.cpp
   SlicingCheck.cpp
 
   LINK_LIBS

Modified: 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp?rev=277262&r1=277261&r2=277262&view=diff
==
--- 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
 (original)
+++ 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
 Sat Jul 30 03:58:54 2016
@@ -22,6 +22,7 @@
 #include "ProTypeStaticCastDowncastCheck.h"
 #include "ProTypeUnionAccessCheck.h"
 #include "ProTypeVarargCheck.h"
+#include "SpecialMemberFunctionsCheck.h"
 #include "SlicingCheck.h"
 
 namespace clang {
@@ -54,6 +55,8 @@ public:
 "cppcoreguidelines-pro-type-union-access");
 CheckFactories.registerCheck(
 "cppcoreguidelines-pro-type-vararg");
+CheckFactories.registerCheck(
+"cppcoreguidelines-special-member-functions");
 CheckFactories.registerCheck(
 "cppcoreguidelines-slicing");
 CheckFactories.registerCheck(

Added: 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp?rev=277262&view=auto
==
--- 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
 (added)
+++ 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
 Sat Jul 30 03:58:54 2016
@@ -0,0 +1,133 @@
+//===--- SpecialMemberFunctionsCheck.cpp - 
clang-tidy--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "SpecialMemberFunctionsCheck.h"
+
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/DenseMapInfo.h"
+#include "llvm/ADT/StringExtras.h"
+
+#define DEBUG_TYPE "clang-tidy"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace cppcoreguidelines {
+
+void SpecialMemberFunctionsCheck::registerMatchers(MatchFinder *Finder) {
+  if (!getLangOpts().CPlusPlus)
+return;
+  Finder->addMatcher(
+  cxxRecordDecl(
+  eachOf(
+  has(cxxDestructorDecl(unless(isImplicit())).bind("dtor")),
+  has(cxxConstructorDecl(isCopyConstructor(), unless(isImplicit()))
+  .bind("

Re: [PATCH] D22513: [clang-tidy] add check cppcoreguidelines-special-member-functions

2016-08-01 Thread Jonathan Coe via cfe-commits
Thanks for reporting this.

I can reproduce the segfault and have a fix. Is it ok to commit and have
review done later?

regards,

Jon

On 1 August 2016 at 11:06, Eric Lemanissier 
wrote:

> ericLemanissier added a comment.
>
> I have an segfault on all the source files of my project when I enable
> this check (it works ok when I disable this check). Sorry I don't have time
> to post a minimal source file producing the segfault. I will maybe
> tomorrow, or in two weeks.
>
>
> Repository:
>   rL LLVM
>
> https://reviews.llvm.org/D22513
>
>
>
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D22513: [clang-tidy] add check cppcoreguidelines-special-member-functions

2016-08-01 Thread Jonathan Coe via cfe-commits
Patch posted to Phabricator as https://reviews.llvm.org/D23008

regards,

Jon

On 1 August 2016 at 11:48, Jonathan Coe  wrote:

> Thanks for reporting this.
>
> I can reproduce the segfault and have a fix. Is it ok to commit and have
> review done later?
>
> regards,
>
> Jon
>
> On 1 August 2016 at 11:06, Eric Lemanissier 
> wrote:
>
>> ericLemanissier added a comment.
>>
>> I have an segfault on all the source files of my project when I enable
>> this check (it works ok when I disable this check). Sorry I don't have time
>> to post a minimal source file producing the segfault. I will maybe
>> tomorrow, or in two weeks.
>>
>>
>> Repository:
>>   rL LLVM
>>
>> https://reviews.llvm.org/D22513
>>
>>
>>
>>
>>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r277523 - [clang-tidy] Fix segfault in cppcore-guidelines-special-member-functions check

2016-08-02 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Tue Aug  2 16:18:37 2016
New Revision: 277523

URL: http://llvm.org/viewvc/llvm-project?rev=277523&view=rev
Log:
[clang-tidy] Fix segfault in cppcore-guidelines-special-member-functions check

Summary:
Use a set rather than a vector of defined special member functions so
that multiple declarations of the same function are only counted once.

Move some private static member functions into the cpp file.

Run clang-format on header.

Reviewers: ericLemanissier, Prazek, aaron.ballman

Subscribers: Prazek, cfe-commits, nemanjai

Projects: #clang-tools-extra

Differential Revision: https://reviews.llvm.org/D23008

Modified:

clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp

clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h

clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-special-member-functions.cpp

Modified: 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp?rev=277523&r1=277522&r2=277523&view=diff
==
--- 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
 (original)
+++ 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
 Tue Aug  2 16:18:37 2016
@@ -43,25 +43,26 @@ void SpecialMemberFunctionsCheck::regist
   this);
 }
 
-llvm::StringRef SpecialMemberFunctionsCheck::toString(
-SpecialMemberFunctionsCheck::SpecialMemberFunctionKind K) {
+static llvm::StringRef
+toString(SpecialMemberFunctionsCheck::SpecialMemberFunctionKind K) {
   switch (K) {
-  case SpecialMemberFunctionKind::Destructor:
+  case SpecialMemberFunctionsCheck::SpecialMemberFunctionKind::Destructor:
 return "a destructor";
-  case SpecialMemberFunctionKind::CopyConstructor:
+  case SpecialMemberFunctionsCheck::SpecialMemberFunctionKind::CopyConstructor:
 return "a copy constructor";
-  case SpecialMemberFunctionKind::CopyAssignment:
+  case SpecialMemberFunctionsCheck::SpecialMemberFunctionKind::CopyAssignment:
 return "a copy assignment operator";
-  case SpecialMemberFunctionKind::MoveConstructor:
+  case SpecialMemberFunctionsCheck::SpecialMemberFunctionKind::MoveConstructor:
 return "a move constructor";
-  case SpecialMemberFunctionKind::MoveAssignment:
+  case SpecialMemberFunctionsCheck::SpecialMemberFunctionKind::MoveAssignment:
 return "a move assignment operator";
   }
   llvm_unreachable("Unhandled SpecialMemberFunctionKind");
 }
 
-std::string SpecialMemberFunctionsCheck::join(
-llvm::ArrayRef SMFS, llvm::StringRef AndOr) {
+static std::string
+join(ArrayRef SMFS,
+ llvm::StringRef AndOr) {
 
   assert(!SMFS.empty() &&
  "List of defined or undefined members should never be empty.");
@@ -97,7 +98,7 @@ void SpecialMemberFunctionsCheck::check(
 
   for (const auto &KV : Matchers)
 if (Result.Nodes.getNodeAs(KV.first))
-  ClassWithSpecialMembers[ID].push_back(KV.second);
+  ClassWithSpecialMembers[ID].insert(KV.second);
 }
 
 void SpecialMemberFunctionsCheck::onEndOfTranslationUnit() {
@@ -112,7 +113,7 @@ void SpecialMemberFunctionsCheck::onEndO
   }
 
   for (const auto &C : ClassWithSpecialMembers) {
-ArrayRef DefinedSpecialMembers = C.second;
+const auto &DefinedSpecialMembers = C.second;
 
 if (DefinedSpecialMembers.size() == AllSpecialMembers.size())
   continue;
@@ -124,7 +125,7 @@ void SpecialMemberFunctionsCheck::onEndO
 std::back_inserter(UndefinedSpecialMembers));
 
 diag(C.first.first, "class '%0' defines %1 but does not define %2")
-<< C.first.second << join(DefinedSpecialMembers, " and ")
+<< C.first.second << join(DefinedSpecialMembers.getArrayRef(), " and ")
 << join(UndefinedSpecialMembers, " or ");
   }
 }

Modified: 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h?rev=277523&r1=277522&r2=277523&view=diff
==
--- 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h
 (original)
+++ 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h
 Tue Aug  2 16:18:37 2016
@@ -1,4 +1,4 @@
-//===--- SpecialMemberFunctionsCheck.h - clang-tidy---*- C++ 
-*-===//
+//===--- SpecialMemberFunctionsCheck.h - clang-tidy--*- C++ 
-*-===//
 //
 // The LLVM Compiler Infrastructure
 //
@@ -41,15 +41,11 @@ public:
 
   using ClassDefId = std::pair;
 
-  using ClassDefiningSpecialMembersMap = llvm::DenseMap>;
+  using ClassDefiningSpecialMembersMap =
+  llvm::DenseMap>;
 
 p

Re: [PATCH] D16376: clang-tidy check: rule-of-five

2016-02-03 Thread Jonathan Coe via cfe-commits
All the C++ compilers I have tried using (GCC,Clang,MSVC) will generate
assignment operators even if the user defines a copy-constructor. This is
the behaviour I set out to write a check for.

The cpp core guide lines recommend defining all or none of the special
functions
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c21-if-you-define-or-delete-any-default-operation-define-or-delete-them-all

If the deprecation warning you mention will turn off the deprecated
generation of special member functions when others are defined (or warn
when deprecated compiler-generated functions are used) then the
rule-of-five check is of reduced value.

Jon

On 3 February 2016 at 17:40, David Blaikie  wrote:

> Is this really that useful of a rule? The language does the right thing
> for the most part already (you don't need to explicitly delete them -
> they're implicitly deleted if you define any others - except for backcompat
> with C++98, but those cases are deprecated & we should probably split out
> the warning for that deprecation so it's easier to turn on separately)
>
> On Wed, Feb 3, 2016 at 5:25 AM, Jonathan B Coe via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> jbcoe retitled this revision from "clang-tidy check: Assignment and
>> Construction" to "clang-tidy check: rule-of-five".
>> jbcoe removed rL LLVM as the repository for this revision.
>> jbcoe updated this revision to Diff 46775.
>> jbcoe added a comment.
>>
>> I've responded to review comments (thanks for those) and renamed the
>> check to 'rule-of-five'.
>>
>> I think it needs moving to cppcoreguidelines and needs destructor
>> handling adding to it. As suggested, I'll address that in a later patch if
>> everything else looks ok.
>>
>>
>> http://reviews.llvm.org/D16376
>>
>> Files:
>>   clang-tidy/misc/CMakeLists.txt
>>   clang-tidy/misc/MiscTidyModule.cpp
>>   clang-tidy/misc/RuleOfFiveCheck.cpp
>>   clang-tidy/misc/RuleOfFiveCheck.h
>>   docs/clang-tidy/checks/list.rst
>>   docs/clang-tidy/checks/misc-rule-of-five.rst
>>   test/clang-tidy/misc-rule-of-five.cpp
>>
>>
>> ___
>> cfe-commits mailing list
>> cfe-commits@lists.llvm.org
>> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>>
>>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D16376: clang-tidy check: rule-of-five

2016-02-03 Thread Jonathan Coe via cfe-commits
On 3 February 2016 at 18:44, David Blaikie  wrote:

>
>
> On Wed, Feb 3, 2016 at 10:23 AM, Jonathan Coe  wrote:
>
>> All the C++ compilers I have tried using (GCC,Clang,MSVC) will generate
>> assignment operators even if the user defines a copy-constructor. This is
>> the behaviour I set out to write a check for.
>>
>> The cpp core guide lines recommend defining all or none of the special
>> functions
>> https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c21-if-you-define-or-delete-any-default-operation-define-or-delete-them-all
>>
>> If the deprecation warning you mention will turn off the deprecated
>> generation of special member functions when others are defined (or warn
>> when deprecated compiler-generated functions are used) then the
>> rule-of-five check is of reduced value.
>>
>
> It can't stop them being generated, because that's required behavior -
> warnings don't change the program behavior.
>
>
That's true but promoting them to errors will stop compilation and prevent
the sort of bug I'm trying to stop.


> Wording like this is in the C++11 standard:
>
> "If the class definition does not explicitly declare a copy constructor,
> one is declared implicitly. If the class definition declares a move
> constructor or move assignment operator, the implicitly declared copy
> constructor is defined as deleted; otherwise, it is defined as defaulted
> (8.4). The latter case is deprecated if the class has a user-declared copy
> assignment operator or a user-declared destructor."
>
>
The 'deprecated' part is my target. I've seen code with user-defined copy
constructors behave badly when compiler-generated assignment operators are
unwittingly used. The rule of five lets me locally reason about code
without having to worry (needlessly or not) about whether some functions
are potentially being compiler-generated.

I don't advocate putting this in 'misc'. It belongs in 'cppcoreguidelines',
I'll move it if the approach taken thus far is sound (as discussed in the
review).


> (similar wording for the copy assignment operator, the dtor has a
> different/special case if I recall correctly)
>
>
>>
>> Jon
>>
>> On 3 February 2016 at 17:40, David Blaikie  wrote:
>>
>>> Is this really that useful of a rule? The language does the right thing
>>> for the most part already (you don't need to explicitly delete them -
>>> they're implicitly deleted if you define any others - except for backcompat
>>> with C++98, but those cases are deprecated & we should probably split out
>>> the warning for that deprecation so it's easier to turn on separately)
>>>
>>> On Wed, Feb 3, 2016 at 5:25 AM, Jonathan B Coe via cfe-commits <
>>> cfe-commits@lists.llvm.org> wrote:
>>>
 jbcoe retitled this revision from "clang-tidy check: Assignment and
 Construction" to "clang-tidy check: rule-of-five".
 jbcoe removed rL LLVM as the repository for this revision.
 jbcoe updated this revision to Diff 46775.
 jbcoe added a comment.

 I've responded to review comments (thanks for those) and renamed the
 check to 'rule-of-five'.

 I think it needs moving to cppcoreguidelines and needs destructor
 handling adding to it. As suggested, I'll address that in a later patch if
 everything else looks ok.


 http://reviews.llvm.org/D16376

 Files:
   clang-tidy/misc/CMakeLists.txt
   clang-tidy/misc/MiscTidyModule.cpp
   clang-tidy/misc/RuleOfFiveCheck.cpp
   clang-tidy/misc/RuleOfFiveCheck.h
   docs/clang-tidy/checks/list.rst
   docs/clang-tidy/checks/misc-rule-of-five.rst
   test/clang-tidy/misc-rule-of-five.cpp


 ___
 cfe-commits mailing list
 cfe-commits@lists.llvm.org
 http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


>>>
>>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r267706 - Expose cxx constructor and method properties through libclang and python bindings.

2016-04-27 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Wed Apr 27 07:48:25 2016
New Revision: 267706

URL: http://llvm.org/viewvc/llvm-project?rev=267706&view=rev
Log:
Expose cxx constructor and method properties through libclang and python 
bindings.

Summary:
I have exposed the following function through libclang and the clang.cindex 
python bindings:

clang_CXXConstructor_isConvertingConstructor,
clang_CXXConstructor_isCopyConstructor,
clang_CXXConstructor_isDefaultConstructor,
clang_CXXConstructor_isMoveConstructor,
clang_CXXMethod_isDefaulted

I need (some of) these methods for a C++ code model I am building in Python to 
drive a code generator.

Reviewers: compnerd, skalinichev

Subscribers: cfe-commits

Differential Revision: http://reviews.llvm.org/D15469

Modified:
cfe/trunk/bindings/python/clang/cindex.py
cfe/trunk/bindings/python/tests/cindex/test_cursor.py
cfe/trunk/include/clang-c/Index.h
cfe/trunk/test/Index/availability.cpp
cfe/trunk/test/Index/file-refs.cpp
cfe/trunk/test/Index/get-cursor.cpp
cfe/trunk/test/Index/index-file.cpp
cfe/trunk/test/Index/load-classes.cpp
cfe/trunk/test/Index/print-type.cpp
cfe/trunk/test/Index/recursive-cxx-member-calls.cpp
cfe/trunk/test/Parser/skip-function-bodies.mm
cfe/trunk/tools/c-index-test/c-index-test.c
cfe/trunk/tools/libclang/CIndex.cpp
cfe/trunk/tools/libclang/libclang.exports

Modified: cfe/trunk/bindings/python/clang/cindex.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/cindex.py?rev=267706&r1=267705&r2=267706&view=diff
==
--- cfe/trunk/bindings/python/clang/cindex.py (original)
+++ cfe/trunk/bindings/python/clang/cindex.py Wed Apr 27 07:48:25 2016
@@ -1174,6 +1174,32 @@ class Cursor(Structure):
 """
 return conf.lib.clang_CXXMethod_isConst(self)
 
+def is_converting_constructor(self):
+"""Returns True if the cursor refers to a C++ converting constructor.
+"""
+return conf.lib.clang_CXXConstructor_isConvertingConstructor(self)
+
+def is_copy_constructor(self):
+"""Returns True if the cursor refers to a C++ copy constructor.
+"""
+return conf.lib.clang_CXXConstructor_isCopyConstructor(self)
+
+def is_default_constructor(self):
+"""Returns True if the cursor refers to a C++ default constructor.
+"""
+return conf.lib.clang_CXXConstructor_isDefaultConstructor(self)
+
+def is_move_constructor(self):
+"""Returns True if the cursor refers to a C++ move constructor.
+"""
+return conf.lib.clang_CXXConstructor_isMoveConstructor(self)
+
+def is_default_method(self):
+"""Returns True if the cursor refers to a C++ member function or member
+function template that is declared '= default'.
+"""
+return conf.lib.clang_CXXMethod_isDefaulted(self)
+
 def is_mutable_field(self):
 """Returns True if the cursor refers to a C++ field that is declared
 'mutable'.
@@ -2918,6 +2944,22 @@ functionList = [
[Index, c_char_p],
c_object_p),
 
+  ("clang_CXXConstructor_isConvertingConstructor",
+   [Cursor],
+   bool),
+
+  ("clang_CXXConstructor_isCopyConstructor",
+   [Cursor],
+   bool),
+
+  ("clang_CXXConstructor_isDefaultConstructor",
+   [Cursor],
+   bool),
+
+  ("clang_CXXConstructor_isMoveConstructor",
+   [Cursor],
+   bool),
+
   ("clang_CXXField_isMutable",
[Cursor],
bool),
@@ -2926,6 +2968,10 @@ functionList = [
[Cursor],
bool),
 
+  ("clang_CXXMethod_isDefaulted",
+   [Cursor],
+   bool),
+
   ("clang_CXXMethod_isPureVirtual",
[Cursor],
bool),

Modified: cfe/trunk/bindings/python/tests/cindex/test_cursor.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/tests/cindex/test_cursor.py?rev=267706&r1=267705&r2=267706&view=diff
==
--- cfe/trunk/bindings/python/tests/cindex/test_cursor.py (original)
+++ cfe/trunk/bindings/python/tests/cindex/test_cursor.py Wed Apr 27 07:48:25 
2016
@@ -112,6 +112,88 @@ def test_is_const_method():
 assert foo.is_const_method()
 assert not bar.is_const_method()
 
+def test_is_converting_constructor():
+"""Ensure Cursor.is_converting_constructor works."""
+source = 'class X { explicit X(int); X(double); X(); };'
+tu = get_tu(source, lang='cpp')
+
+xs = get_cursors(tu, 'X')
+
+assert len(xs) == 4
+assert xs[0].kind == CursorKind.CLASS_DECL
+cs = xs[1:]
+assert cs[0].kind == CursorKind.CONSTRUCTOR
+assert cs[1].kind == CursorKind.CONSTRUCTOR
+assert cs[2].kind == CursorKind.CONSTRUCTOR
+
+assert not cs[0].is_converting_constructor()
+assert cs[1].is_converting_constructor()
+assert not cs[2].is_converting_constructor()
+
+
+def test_is_copy_constructor():
+"""Ensure Cursor.is_copy_constructor works."""
+source = 'class X { X(); X(const X&); X(X&&

Re: [PATCH] D16962: clang-tidy: avoid std::bind

2016-05-05 Thread Jonathan Coe via cfe-commits
Modernize it is then.

The check currently only catches std::bind but further work can address that.

Jon

> On 4 May 2016, at 22:40, Arthur O'Dwyer  wrote:
> 
>> On Wed, May 4, 2016 at 1:43 PM, Aaron Ballman via cfe-commits 
>>  wrote:
>> jbcoe wrote:
>> > aaron.ballman wrote:
>> > > I believe we use "modernize" to really mean "migrate from the old way to 
>> > > the new way", which this definitely fits into since I think the point to 
>> > > this check is to replace bind with better alternatives.
>> > Would you prefer it to be in `modernize`? I can be easily convinced either 
>> > way and am happy to move it. If I do move it I might add a script to 
>> > facilitate doing so.
>> My preference is for modernize, your preference is for readability, so I 
>> say: make @alexfh the tie-breaker! ;-) Alex, what are your thoughts? This 
>> seems like a heuristic we may want to state in our documentation to help 
>> others decide where to put new checks in the future as well.
> 
> FWIW, I'd prefer "modernize", and I'll point out that these waters are 
> muddied by the fact that three of the old ways (boost::bind, std::bind1st, 
> std::bind2nd) all existed prior to C++11, so the fact that one of the old 
> ways (std::bind) was introduced in C++11 doesn't matter so much.
> (I haven't looked, but I'd assume that this clang-tidy check catches all four 
> cases, right?)
> 
> –Arthur
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r269341 - [clang-tidy] Adds modernize-avoid-bind check

2016-05-12 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Thu May 12 15:06:04 2016
New Revision: 269341

URL: http://llvm.org/viewvc/llvm-project?rev=269341&view=rev
Log:
[clang-tidy] Adds modernize-avoid-bind check

Summary:
This patch adds a check that replaces std::bind with a lambda.

Not yet working for member functions.

Reviewers: aaron.ballman, alexfh

Subscribers: cfe-commits

Differential Revision: http://reviews.llvm.org/D16962

Added:
clang-tools-extra/trunk/clang-tidy/modernize/AvoidBindCheck.cpp
clang-tools-extra/trunk/clang-tidy/modernize/AvoidBindCheck.h
clang-tools-extra/trunk/docs/clang-tidy/checks/modernize-avoid-bind.rst
clang-tools-extra/trunk/test/clang-tidy/modernize-avoid-bind.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt
clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Added: clang-tools-extra/trunk/clang-tidy/modernize/AvoidBindCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/AvoidBindCheck.cpp?rev=269341&view=auto
==
--- clang-tools-extra/trunk/clang-tidy/modernize/AvoidBindCheck.cpp (added)
+++ clang-tools-extra/trunk/clang-tidy/modernize/AvoidBindCheck.cpp Thu May 12 
15:06:04 2016
@@ -0,0 +1,163 @@
+//===--- AvoidBindCheck.cpp - clang-tidy===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+#include "AvoidBindCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+#include 
+#include 
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace modernize {
+
+namespace {
+enum BindArgumentKind { BK_Temporary, BK_Placeholder, BK_CallExpr, BK_Other };
+
+struct BindArgument {
+  StringRef Tokens;
+  BindArgumentKind Kind = BK_Other;
+  size_t PlaceHolderIndex = 0;
+};
+
+} // end namespace
+
+static SmallVector
+buildBindArguments(const MatchFinder::MatchResult &Result, const CallExpr *C) {
+  SmallVector BindArguments;
+  llvm::Regex MatchPlaceholder("^_([0-9]+)$");
+
+  // Start at index 1 as first argument to bind is the function name.
+  for (size_t I = 1, ArgCount = C->getNumArgs(); I < ArgCount; ++I) {
+const Expr *E = C->getArg(I);
+BindArgument B;
+if (const auto *M = dyn_cast(E)) {
+  const auto *TE = M->GetTemporaryExpr();
+  B.Kind = isa(TE) ? BK_CallExpr : BK_Temporary;
+}
+
+B.Tokens = Lexer::getSourceText(
+CharSourceRange::getTokenRange(E->getLocStart(), E->getLocEnd()),
+*Result.SourceManager, Result.Context->getLangOpts());
+
+SmallVector Matches;
+if (B.Kind == BK_Other && MatchPlaceholder.match(B.Tokens, &Matches)) {
+  B.Kind = BK_Placeholder;
+  B.PlaceHolderIndex = std::stoi(Matches[1]);
+}
+BindArguments.push_back(B);
+  }
+  return BindArguments;
+}
+
+static void addPlaceholderArgs(const ArrayRef Args,
+   llvm::raw_ostream &Stream) {
+  auto MaxPlaceholderIt =
+  std::max_element(Args.begin(), Args.end(),
+   [](const BindArgument &B1, const BindArgument &B2) {
+ return B1.PlaceHolderIndex < B2.PlaceHolderIndex;
+   });
+
+  // Placeholders (if present) have index 1 or greater.
+  if (MaxPlaceholderIt == Args.end() || MaxPlaceholderIt->PlaceHolderIndex == 
0)
+return;
+
+  size_t PlaceholderCount = MaxPlaceholderIt->PlaceHolderIndex;
+  Stream << "(";
+  StringRef Delimiter = "";
+  for (size_t I = 1; I <= PlaceholderCount; ++I) {
+Stream << Delimiter << "auto && arg" << I;
+Delimiter = ", ";
+  }
+  Stream << ")";
+}
+
+static void addFunctionCallArgs(const ArrayRef Args,
+llvm::raw_ostream &Stream) {
+  StringRef Delimiter = "";
+  for (const auto &B : Args) {
+if (B.PlaceHolderIndex)
+  Stream << Delimiter << "arg" << B.PlaceHolderIndex;
+else
+  Stream << Delimiter << B.Tokens;
+Delimiter = ", ";
+  }
+}
+
+static bool isPlaceHolderIndexRepeated(const ArrayRef Args) {
+  llvm::SmallSet PlaceHolderIndices;
+  for (const BindArgument &B : Args) {
+if (B.PlaceHolderIndex) {
+  if (!PlaceHolderIndices.insert(B.PlaceHolderIndex).second)
+return true;
+}
+  }
+  return false;
+}
+
+void AvoidBindCheck::registerMatchers(MatchFinder *Finder) {
+  if (!getLangOpts().CPlusPlus14) // Need C++14 for generic lambdas.
+return;
+
+  Finder->addMatcher(
+  callExpr(callee(namedDecl(hasName("::std::bind"))),
+   hasArgument(0, declRefExpr(to(functionDecl().bind("f")
+  .bind("bind"),
+  this);
+}
+
+void AvoidBindCheck::check(const

[libcxx] r273122 - Implement std::experimental::propagate_const from LFTS v2

2016-06-19 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Sun Jun 19 14:34:13 2016
New Revision: 273122

URL: http://llvm.org/viewvc/llvm-project?rev=273122&view=rev
Log:
Implement std::experimental::propagate_const from LFTS v2

Summary:
An implementation of std::experimental::propagate_const from Library 
Fundamentals Technical Specification v2.

No tests are provided for disallowed types like fancy pointers or function 
pointers as no code was written to handle these.

Reviewers: EricWF, mclow.lists

Differential Revision: http://reviews.llvm.org/D12486

Added:
libcxx/trunk/include/experimental/propagate_const
libcxx/trunk/test/std/experimental/utilities/propagate_const/

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.assignment/

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.assignment/assign.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.assignment/assign_convertible_element_type.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.assignment/assign_convertible_propagate_const.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.assignment/assign_element_type.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.assignment/move_assign.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.assignment/move_assign_convertible.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.assignment/move_assign_convertible_propagate_const.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.ctors/

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.ctors/convertible_element_type.explicit.ctor.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.ctors/convertible_element_type.non-explicit.ctor.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.ctors/convertible_propagate_const.copy_ctor.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.ctors/convertible_propagate_const.explicit.move_ctor.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.ctors/convertible_propagate_const.move_ctor.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.ctors/copy_ctor.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.ctors/element_type.explicit.ctor.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.ctors/element_type.non-explicit.ctor.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.ctors/move_ctor.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.non-const_observers/

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.non-const_observers/dereference.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.non-const_observers/explicit_operator_element_type_ptr.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.non-const_observers/get.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.non-const_observers/op_arrow.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.non-const_observers/operator_element_type_ptr.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.observers/

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.observers/dereference.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.observers/explicit_operator_element_type_ptr.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.observers/get.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propagate_const.observers/op_arrow.pass.cpp

libcxx/trunk/test/std/experimental/utilities/propagate_const/propagate_const.class/propaga

[libcxx] r273123 - Add entry to CREDITS.TXT for propagate_const

2016-06-19 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Sun Jun 19 14:36:28 2016
New Revision: 273123

URL: http://llvm.org/viewvc/llvm-project?rev=273123&view=rev
Log:
Add entry to CREDITS.TXT for propagate_const

Modified:
libcxx/trunk/CREDITS.TXT

Modified: libcxx/trunk/CREDITS.TXT
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/CREDITS.TXT?rev=273123&r1=273122&r2=273123&view=diff
==
--- libcxx/trunk/CREDITS.TXT (original)
+++ libcxx/trunk/CREDITS.TXT Sun Jun 19 14:36:28 2016
@@ -37,6 +37,10 @@ E: mclow.li...@gmail.com
 E: marsh...@idio.com
 D: C++14 support, patches and bug fixes.
 
+N: Jonathan B Coe
+E: jb...@me.com
+D: Implementation of propagate_const.
+
 N: Eric Fiselier
 E: e...@efcs.ca
 D: LFTS support, patches and bug fixes.


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D17772: [clang-tidy]: string_view of temporary string

2016-03-01 Thread Jonathan Coe via cfe-commits
Maybe config options could allow addition of owning and non-owning pairs?

I'd like to do that as an extension if this path is approved.

Jon

On 1 March 2016 at 12:29, David Blaikie  wrote:

> Any way to/would it be worth broadening this with an annotation or some
> such (or just a lost for now) of types that maintain references to their
> ctor params? (Eg: llvm arrayref, etc)
> On Mar 1, 2016 9:19 AM, "Jonathan B Coe via cfe-commits" <
> cfe-commits@lists.llvm.org> wrote:
>
>> jbcoe created this revision.
>> jbcoe added reviewers: aaron.ballman, alexfh.
>> jbcoe added a subscriber: cfe-commits.
>> jbcoe set the repository for this revision to rL LLVM.
>>
>> Find instances where a string_view is constructed from a temporary string
>> and replace the string_view with a string.
>>
>> Repository:
>>   rL LLVM
>>
>> http://reviews.llvm.org/D17772
>>
>> Files:
>>   clang-tidy/misc/CMakeLists.txt
>>   clang-tidy/misc/MiscTidyModule.cpp
>>   clang-tidy/misc/StringViewOfTemporaryCheck.cpp
>>   clang-tidy/misc/StringViewOfTemporaryCheck.h
>>   docs/clang-tidy/checks/list.rst
>>   docs/clang-tidy/checks/misc-string_view-of-temporary.rst
>>   test/clang-tidy/misc-string_view-of-temporary.cpp
>>
>>
>> ___
>> cfe-commits mailing list
>> cfe-commits@lists.llvm.org
>> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>>
>>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r263170 - libclang python bindings: Fix for bug 26394

2016-03-10 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Thu Mar 10 17:29:45 2016
New Revision: 263170

URL: http://llvm.org/viewvc/llvm-project?rev=263170&view=rev
Log:
libclang python bindings: Fix for bug 26394

Summary:
https://llvm.org/bugs/show_bug.cgi?id=26394 reports that clang's python 
bindings tests are failing.

I can confirm that the bug exists and that the proposed fix is good.

Differential Revision: http://reviews.llvm.org/D17226

Modified:
cfe/trunk/bindings/python/clang/cindex.py

Modified: cfe/trunk/bindings/python/clang/cindex.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/cindex.py?rev=263170&r1=263169&r2=263170&view=diff
==
--- cfe/trunk/bindings/python/clang/cindex.py (original)
+++ cfe/trunk/bindings/python/clang/cindex.py Thu Mar 10 17:29:45 2016
@@ -2383,7 +2383,7 @@ class TranslationUnit(ClangObject):
 functions above. __init__ is only called internally.
 """
 assert isinstance(index, Index)
-
+self.index = index
 ClangObject.__init__(self, ptr)
 
 def __del__(self):


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r258835 - Test commit. Fix typo in comment.

2016-01-26 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Tue Jan 26 12:55:55 2016
New Revision: 258835

URL: http://llvm.org/viewvc/llvm-project?rev=258835&view=rev
Log:
Test commit. Fix typo in comment.

Modified:
clang-tools-extra/trunk/clang-tidy/readability/IdentifierNamingCheck.cpp

Modified: 
clang-tools-extra/trunk/clang-tidy/readability/IdentifierNamingCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/IdentifierNamingCheck.cpp?rev=258835&r1=258834&r2=258835&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/readability/IdentifierNamingCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/readability/IdentifierNamingCheck.cpp 
Tue Jan 26 12:55:55 2016
@@ -504,7 +504,7 @@ static StyleKind findStyleKind(
 static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures,
  const NamedDecl *Decl, SourceRange Range,
  const SourceManager *SM) {
-  // Do nothin if the provided range is invalid
+  // Do nothing if the provided range is invalid.
   if (Range.getBegin().isInvalid() || Range.getEnd().isInvalid())
 return;
 


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits