Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions functional_tests/ConstantDeclarationTests.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
2:4: error: Global constant should be either lowerCamelCase or UpperCamelCase
5:15: error: Constant should be in lowerCamelCase
5:44: error: Constant should be in lowerCamelCase
11:12: error: Global constant should be either lowerCamelCase or UpperCamelCase
12:14: error: Global constant should be either lowerCamelCase or UpperCamelCase
15:8: error: Constant should be in lowerCamelCase
20:4: error: Global constant should be either lowerCamelCase or UpperCamelCase
24:4: error: Global constant should be either lowerCamelCase or UpperCamelCase
29:32: error: Constant should be in lowerCamelCase
29:18: error: Constant should be in lowerCamelCase
30:6: error: Constant should be in lowerCamelCase
31:6: error: Constant should be in lowerCamelCase
33:6: error: Constant should be in lowerCamelCase
40:13: error: Constant should be in lowerCamelCase
50:10: error: Constant should be in lowerCamelCase
56:4: error: Global constant should be either lowerCamelCase or UpperCamelCase
67:8: error: Global constant should be either lowerCamelCase or UpperCamelCase
78:8: error: Global constant should be either lowerCamelCase or UpperCamelCase
87:16: error: Constant should be in lowerCamelCase
94:7: error: Constant should be in lowerCamelCase
104:13: error: Constant should be in lowerCamelCase
109 changes: 109 additions & 0 deletions functional_tests/ConstantDeclarationTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
let hello = false
let hello_World = { (kVar1: String, kVar2: String) -> Bool in return hello }

switch productBarcode {
case let .UPCA(KNumberSystem, manufacturer, Product, check):
println("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).")
case let .QRCode(productCode):
println("QR code: \(productCode).")
}

let (valid, in_valid) = (5 , "hello")
let numX = 2, func_y = { x in println(x) }

func toMicroseconds(seconds: Int) -> Int {
let SecondsToMicroseconds = 100000
let secondsToMicroseconds = 100000
return seconds * secondsToMicroseconds
}

let exclamation_Mark: Character = "!"
let index = advance(greeting.startIndex, 7)
let range = advance(welcome.endIndex, -6)..<welcome.endIndex

let romeo_And_Juliet = [
"Act 1 Scene 1: Verona, A public place",
"Act 1 Scene 2: Capulet's mansion",
]

func declarations(ExternalParam LocalParam: String) {
let OddDigits: Set = [1, 3, 5, 7, 9]
let airport_Codes = [String](airports.keys)
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
let Movie = object as! Movie
}

let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
println("on the x-axis with an x value of \(x)")
case (0, let DrDrae):
println("on the y-axis with a y value of \(y)")
case let (x, y):
println("somewhere else at (\(x), \(y))")
}

let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == ThisShouldNotMatter:
println("(\(x), \(y)) is on the line x == y")
case let (DrDrae, y) where DrDrae == -y:
println("(\(x), \(y)) is on the line x == -y")
case let (x, y):
println("(\(x), \(y)) is just some arbitrary point")
}

let many_strings = numbers.map {
(var number) -> String in
var output = ""
while number > 0 {
output = digitNames[number % 10]! + output
number /= 10
}
return output
}

class Queue {
let max_QueueSize = 1000
let maxQueueSize = 1000
let MaxQueueSize = 1000

func hello() {
println("hello")
}
}

struct FixedLengthRange {
var firstValue: Int
let K_Length: Int
static let KThresholdLevel = 10
}

struct AlternativeRect {
var origin = Point()
var size = Size()
var center: Point {
get {
let CenterX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
}
}

if let RoomCount = john.residence?.numberOfRooms {
println("John's residence has \(roomCount) room(s).")
}

for thing in things {
switch thing {
case 0 as Int:
println("zero as an Int")
case 0 as Double:
println("zero as a Double")
case let SomeInt as Int:
println("an integer value of \(someInt)")
case let someDouble as Double where someDouble > 0:
println("a positive double value of \(someDouble)")
}
}
49 changes: 30 additions & 19 deletions grammar/Swift.g4
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ switchStatement : 'switch' expression '{' switchCases? '}' ;
switchCases : switchCase switchCases? ;
switchCase : caseLabel statements | defaultLabel statements | caseLabel ';' | defaultLabel ';' ;
caseLabel : 'case' caseItemList ':' ;
caseItemList : pattern guardClause? pattern guardClause?',' caseItemList ;
caseItemList : pattern guardClause? | pattern guardClause? ',' caseItemList ;
defaultLabel : 'default' ':' ;
guardClause : 'where' guardExpression ;
guardExpression : expression ;
Expand Down Expand Up @@ -133,18 +133,18 @@ returnStatement : 'return' expression? ;

// GRAMMAR OF A GENERIC PARAMETER CLAUSE

genericParameterClause : '<' genericParameterList requirementClause? '>' ;
genericParameterClause : LessThanOperator genericParameterList requirementClause? GreaterThanOperator ;
genericParameterList : genericParameter | genericParameter ',' genericParameterList ;
genericParameter : typeName | typeName ':' typeIdentifier | typeName ':' protocolCompositionType ;
requirementClause : 'where' requirementList ;
requirementList : requirement | requirement ',' requirementList ;
requirement : conformanceRequirement | sameTypeRequirement ;
conformanceRequirement : typeIdentifier ':' typeIdentifier | typeIdentifier ':' protocolCompositionType ;
sameTypeRequirement : typeIdentifier '==' typeIdentifier ;
sameTypeRequirement : typeIdentifier EqualityOperator typeIdentifier ;

// GRAMMAR OF A GENERIC ARGUMENT CLAUSE

genericArgumentClause : '<' genericArgumentList '>' ;
genericArgumentClause : LessThanOperator genericArgumentList GreaterThanOperator ;
genericArgumentList : genericArgument (',' genericArgument)* ;
genericArgument : sType ;

Expand Down Expand Up @@ -189,7 +189,7 @@ importPathIdentifier : identifier | operator ;
constantDeclaration : attributes? declarationSpecifiers? 'let' patternInitializerList ;
patternInitializerList : patternInitializer (',' patternInitializer)* ;
patternInitializer : pattern initializer? ;
initializer : '=' expression ;
initializer : AssignmentOperator expression ;

// GRAMMAR OF A VARIABLE DECLARATION

Expand Down Expand Up @@ -219,7 +219,7 @@ didSetClause : attributes? 'didSet' setterName? codeBlock ;
typealiasDeclaration : typealiasHead typealiasAssignment ;
typealiasHead : 'typealias' typealiasName ;
typealiasName : identifier ;
typealiasAssignment : '=' sType ;
typealiasAssignment : AssignmentOperator sType ;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What made you refactor the comparator and assignment operators? To improve readability?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Nope, it was to fix a bug in the grammar. I can discuss this in person if you want, too long of an explanation.


// GRAMMAR OF A FUNCTION DECLARATION

Expand All @@ -232,13 +232,13 @@ functionBody : codeBlock ;
parameterClauses : parameterClause parameterClauses? ;
parameterClause : '(' ')' | '(' parameterList '...'? ')' ;
parameterList : parameter | parameter ',' parameterList ;
parameter : 'inout'? 'let'? '#'? parameterName localParameterName? typeAnnotation defaultArgumentClause?
| 'inout'? 'var' '#'? parameterName localParameterName? typeAnnotation defaultArgumentClause?
parameter : 'inout'? 'let'? '#'? externalParameterName? localParameterName typeAnnotation? defaultArgumentClause?
| 'inout'? 'var' '#'? externalParameterName? localParameterName typeAnnotation? defaultArgumentClause?
| attributes? sType
;
parameterName : identifier | '_' ;
externalParameterName : identifier | '_' ;
localParameterName : identifier | '_' ;
defaultArgumentClause : '=' expression ;
defaultArgumentClause : AssignmentOperator expression ;

// GRAMMAR OF AN ENUMERATION DECLARATION

Expand All @@ -258,7 +258,7 @@ rawValueStyleEnumMember : declaration | rawValueStyleEnumCaseClause ;
rawValueStyleEnumCaseClause : attributes? 'case' rawValueStyleEnumCaseList ;
rawValueStyleEnumCaseList : rawValueStyleEnumCase | rawValueStyleEnumCase ',' rawValueStyleEnumCaseList ;
rawValueStyleEnumCase : enumCaseName rawValueAssignment? ;
rawValueAssignment : '=' literal ;
rawValueAssignment : AssignmentOperator literal ;

// GRAMMAR OF A STRUCTURE DECLARATION

Expand Down Expand Up @@ -456,7 +456,7 @@ binaryExpression

// GRAMMAR OF AN ASSIGNMENT OPERATOR

assignmentOperator : '=' ;
assignmentOperator : AssignmentOperator ;

// GRAMMAR OF A CONDITIONAL OPERATOR

Expand All @@ -468,6 +468,7 @@ typeCastingOperator
: 'is' sType
| 'as' '?' sType
| 'as' sType
| 'as' NotOperator sType
;

// GRAMMAR OF A PRIMARY EXPRESSION
Expand Down Expand Up @@ -563,7 +564,7 @@ postfixExpression
| postfixExpression '.' 'self' # postfixSelfExpression
| postfixExpression '.' 'dynamicType' # dynamicTypeExpression
| postfixExpression '[' expressionList ']' # subscriptExpression
| postfixExpression '!' # forcedValueExpression
| postfixExpression NotOperator # forcedValueExpression
| postfixExpression '?' # optionalChainingExpression
;

Expand Down Expand Up @@ -609,7 +610,7 @@ functionCallExpression
// split the operators out into the individual tokens as some of those tokens
// are also referenced individually. For example, type signatures use
// <...>.
operator: Operator ;
operator: EqualityOperator | LessThanOperator | GreaterThanOperator | NotOperator | Operator;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What about logical operators (&&, ||), and other unary operators?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

They will be handled by Operator.



// WHITESPACE scariness:
Expand Down Expand Up @@ -662,7 +663,7 @@ sType
| typeIdentifier
| tupleType
| sType '?'
| sType '!'
| sType NotOperator
| protocolCompositionType
| sType '.' 'Type'
| sType '.' 'Protocol'
Expand Down Expand Up @@ -691,7 +692,7 @@ elementName : identifier ;

// GRAMMAR OF A PROTOCOL COMPOSITION TYPE

protocolCompositionType : 'protocol' '<' protocolIdentifierList?'>' ;
protocolCompositionType : 'protocol' LessThanOperator protocolIdentifierList? GreaterThanOperator ;
protocolIdentifierList : protocolIdentifier | protocolIdentifier ',' protocolIdentifierList ;
protocolIdentifier : typeIdentifier ;

Expand All @@ -718,13 +719,23 @@ contextSensitiveKeyword :
'set' | 'unowned' | 'unowned(safe)' | 'unowned(unsafe)' | 'weak' | 'willSet'
;

AssignmentOperator: '=' ;

EqualityOperator: '==' ;

LessThanOperator: '<' ;

GreaterThanOperator: '>' ;

NotOperator: '!';

Operator
: OperatorHead OperatorCharacter*
| '..' ('.'|OperatorCharacter)*
;

OperatorHead
: '/' | '=' | '\\' | '-' | '+' | '!' | '*' | '%' | '<' | '>' | '&' | '|' | '^' | '!' | '.'
: '/' | '=' | '-' | '+' | '!' | '*' | '%' | '<' | '>' | '&' | '|' | '^' | '~' | '?'
| [\u00A1-\u00A7]
| [\u00A9\u00AB\u00AC\u00AE]
| [\u00B0-\u00B1\u00B6\u00BB\u00BF\u00D7\u00F7]
Expand Down Expand Up @@ -838,13 +849,13 @@ fragment Sign : [+\-] ;

// GRAMMAR OF A STRING LITERAL

StringLiteral : '"' QuotedText '"' ;
StringLiteral : '"' QuotedText? '"' ;
fragment QuotedText : QuotedTextItem QuotedText? ;
fragment QuotedTextItem : EscapedCharacter
// | '\\(' expression ')'
| ~["\\\u000A\u000D]
;
EscapedCharacter : '\\' [0\\tnr"']
EscapedCharacter : '\\' [0\\(tnr"']
| '\\x' HexadecimalDigit HexadecimalDigit
| '\\u' HexadecimalDigit HexadecimalDigit HexadecimalDigit HexadecimalDigit
| '\\U' HexadecimalDigit HexadecimalDigit HexadecimalDigit HexadecimalDigit HexadecimalDigit HexadecimalDigit HexadecimalDigit HexadecimalDigit
Expand Down
72 changes: 72 additions & 0 deletions tailor/listeners/constantdeclistener.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
from tailor.swift.swiftlistener import SwiftListener
from tailor.swift.swiftparser import SwiftParser
from tailor.utils import charformat


class ConstantDecListener(SwiftListener):

def __init__(self, printer):
self.__printer = printer

def enterIdentifier(self, ctx):
constant_name = ctx.getText()
constant_decl_ctx = self.__get_constant_declaration(ctx)
if (self.__is_global(constant_decl_ctx)
or self.__inside_class(constant_decl_ctx)
or self.__inside_struct(constant_decl_ctx)):
if not (charformat.is_upper_camel_case(constant_name)
or charformat.is_lower_camel_case(constant_name)):
self.__printer.error('Global constant should be either' +
' lowerCamelCase or UpperCamelCase',
ctx=ctx)
else:
if not charformat.is_lower_camel_case(constant_name):
self.__printer.error('Constant should be in lowerCamelCase',
ctx=ctx)

def __get_constant_declaration(self, ctx):
if ctx.parentCtx:
if isinstance(ctx.parentCtx,
SwiftParser.ConstantDeclarationContext):
return ctx.parentCtx
else:
return self.__get_constant_declaration(ctx.parentCtx)
else:
return None

def __is_global(self, ctx):
parent = self.__get_nth_parent(ctx, 3)
return parent and isinstance(parent, SwiftParser.TopLevelContext)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What happens if parent is None?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

returns False


def __inside_class(self, ctx):
root_ctx = self.__get_nth_parent(self.__get_declaration_root(ctx), 1)
return root_ctx and isinstance(root_ctx,
SwiftParser.ClassDeclarationContext)

def __inside_struct(self, ctx):
root_ctx = self.__get_nth_parent(self.__get_declaration_root(ctx), 1)
return root_ctx and isinstance(root_ctx,
SwiftParser.StructDeclarationContext)

@staticmethod
# pylint: disable=invalid-name
def __get_nth_parent(ctx, n):
if ctx is None:
return None
while n != 0:
n -= 1
ctx = ctx.parentCtx
if ctx is None:
return None
return ctx

@staticmethod
def __get_declaration_root(ctx):
if ctx is None:
return None
while True:
ctx = ctx.parentCtx
if not (isinstance(ctx, SwiftParser.DeclarationsContext)
or isinstance(ctx, SwiftParser.DeclarationContext)):
break
return ctx
Loading