Skip to content

Commit

Permalink
🎨 format
Browse files Browse the repository at this point in the history
  • Loading branch information
johnmai-dev committed Apr 27, 2024
1 parent 5f1679e commit c64b900
Show file tree
Hide file tree
Showing 12 changed files with 232 additions and 125 deletions.
13 changes: 13 additions & 0 deletions .swift-format
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"version": 1,
"indentation": {
"spaces": 4
},
"lineLength" : 120,
"maximumBlankLines": 1,
"respectsExistingLineBreaks": true,
"lineBreakBeforeControlFlowKeywords": true,
"lineBreakBeforeEachArgument": true,
"multiElementCollectionTrailingCommas": true,
"spacesAroundRangeFormationOperators": true
}
3 changes: 2 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ let package = Package(
// Products define the executables and libraries a package produces, making them visible to other packages.
.library(
name: "Jinja",
targets: ["Jinja"]),
targets: ["Jinja"]
)
],
targets: [
// Targets are the basic building blocks of a package, defining a module or a test suite.
Expand Down
14 changes: 9 additions & 5 deletions Sources/Environment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class Environment {
}

return args[0]
}),
})
]

var tests: [String: (any RuntimeValue...) throws -> Bool] = [
Expand All @@ -39,14 +39,16 @@ class Environment {
args in
if let arg = args.first as? NumericValue {
return arg.value as! Int % 2 != 0
} else {
}
else {
throw JinjaError.runtimeError("Cannot apply test 'odd' to type: \(args.first!.type)")
}
},
"even": { args in
if let arg = args.first as? NumericValue {
return arg.value as! Int % 2 == 0
} else {
}
else {
throw JinjaError.runtimeError("Cannot apply test 'even' to type: \(args.first!.type)")
}
},
Expand Down Expand Up @@ -205,10 +207,12 @@ class Environment {
do {
if let value = try self.resolve(name: name).variables[name] {
return value
} else {
}
else {
return UndefinedValue()
}
} catch {
}
catch {
return UndefinedValue()
}
}
Expand Down
1 change: 1 addition & 0 deletions Sources/Error.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ enum JinjaError: Error {
case syntaxError(String)
case parserError(String)
case runtimeError(String)
case todo(String)
case notSupportError
}
26 changes: 15 additions & 11 deletions Sources/Lexer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ let keywords: [String: TokenType] = [
"or": .or,
"not": .not,
"true": .booleanLiteral,
"false": .booleanLiteral
"false": .booleanLiteral,
]

func isWord(char: String) -> Bool {
Expand Down Expand Up @@ -111,7 +111,7 @@ let orderedMappingTable: [(String, TokenType)] = [
("*", .multiplicativeBinaryOperator),
("/", .multiplicativeBinaryOperator),
("%", .multiplicativeBinaryOperator),
("=", .equals)
("=", .equals),
]

let escapeCharacters: [String: String] = [
Expand All @@ -123,7 +123,7 @@ let escapeCharacters: [String: String] = [
"v": "\u{000B}",
"'": "'",
"\"": "\"",
"\\": "\\"
"\\": "\\",
]

struct PreprocessOptions {
Expand All @@ -148,7 +148,8 @@ func preprocess(template: String, options: PreprocessOptions = PreprocessOptions
template = template.replacing(/([#%]})\n/, with: { $0.output.1 })
}

return template
return
template
.replacing(/{##}/, with: "")
.replacing(/-%}\s*/, with: "%}")
.replacing(/\s*{%-/, with: "{%")
Expand Down Expand Up @@ -197,7 +198,9 @@ func tokenize(_ source: String, options: PreprocessOptions = PreprocessOptions()
if lastTokenType == nil || lastTokenType == .closeStatement || lastTokenType == .closeExpression {
var text = ""

while cursorPosition < src.count, !(src[cursorPosition] == "{" && (src[cursorPosition + 1] == "%" || src[cursorPosition + 1] == "{")) {
while cursorPosition < src.count,
!(src[cursorPosition] == "{" && (src[cursorPosition + 1] == "%" || src[cursorPosition + 1] == "{"))
{
text.append(src[cursorPosition])
cursorPosition += 1
}
Expand All @@ -221,11 +224,11 @@ func tokenize(_ source: String, options: PreprocessOptions = PreprocessOptions()

switch lastTokenType {
case .identifier,
.numericLiteral,
.booleanLiteral,
.stringLiteral,
.closeParen,
.closeSquareBracket:
.numericLiteral,
.booleanLiteral,
.stringLiteral,
.closeParen,
.closeSquareBracket:
break

default:
Expand Down Expand Up @@ -272,7 +275,8 @@ func tokenize(_ source: String, options: PreprocessOptions = PreprocessOptions()
if type == .in, tokens.last?.type == .not {
_ = tokens.popLast()
tokens.append(Token(value: "not in", type: .notIn))
} else {
}
else {
tokens.append(Token(value: word, type: type))
}

Expand Down
49 changes: 32 additions & 17 deletions Sources/Parser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ func parse(tokens: [Token]) throws -> Program {
if let identifier = argument as? Identifier {
let value = try parseExpression()
argument = KeywordArgumentExpression(key: identifier, value: value as! Expression)
} else {
}
else {
throw JinjaError.syntaxError("Expected identifier for keyword argument")
}
}
Expand Down Expand Up @@ -88,7 +89,8 @@ func parse(tokens: [Token]) throws -> Program {
slices.append(nil)
current += 1
isSlice = true
} else {
}
else {
try slices.append(parseExpression())
if typeof(.colon) {
current += 1
Expand Down Expand Up @@ -129,14 +131,19 @@ func parse(tokens: [Token]) throws -> Program {
if computed {
property = try parseMemberExpressionArgumentsList()
try expect(type: .closeSquareBracket, error: "Expected closing square bracket")
} else {
}
else {
property = try parsePrimaryExpression()
if property.type != "Identifier" {
throw JinjaError.syntaxError("Expected identifier following dot operator")
}
}

object = MemberExpression(object: object as! Expression, property: property as! Expression, computed: computed)
object = MemberExpression(
object: object as! Expression,
property: property as! Expression,
computed: computed
)
}

return object
Expand Down Expand Up @@ -193,7 +200,8 @@ func parse(tokens: [Token]) throws -> Program {

if let test = filter as? Identifier {
operand = TestExpression(operand: operand as! Expression, negate: negate, test: test)
} else {
}
else {
throw JinjaError.syntaxError("Expected identifier for the test")
}
}
Expand Down Expand Up @@ -247,7 +255,8 @@ func parse(tokens: [Token]) throws -> Program {

if let right {
return right
} else {
}
else {
return try parseComparisonExpression()
}
}
Expand Down Expand Up @@ -294,12 +303,12 @@ func parse(tokens: [Token]) throws -> Program {
}

func typeof(_ types: TokenType...) -> Bool {
guard current+types.count <= tokens.count else {
guard current + types.count <= tokens.count else {
return false
}

for (index, type) in types.enumerated() {
if type != tokens[current+index].type {
if type != tokens[current + index].type {
return false
}
}
Expand Down Expand Up @@ -328,21 +337,23 @@ func parse(tokens: [Token]) throws -> Program {
var body: [Statement] = []
var alternate: [Statement] = []

while !(tokens[current].type == .openStatement && (
tokens[current+1].type == .elseIf || tokens[current+1].type == .else || tokens[current+1].type == .endIf))
while !(tokens[current].type == .openStatement
&& (tokens[current + 1].type == .elseIf || tokens[current + 1].type == .else
|| tokens[current + 1].type == .endIf))
{
try body.append(parseAny())
}
if tokens[current].type == .openStatement, tokens[current+1].type != .endIf {
if tokens[current].type == .openStatement, tokens[current + 1].type != .endIf {
current += 1
if typeof(.elseIf) {
try expect(type: .elseIf, error: "Expected elseif token")
try alternate.append(parseIfStatement())
} else {
}
else {
try expect(type: .else, error: "Expected else token")
try expect(type: .closeStatement, error: "Expected closing statement token")

while !(tokens[current].type == .openStatement && tokens[current+1].type == .endIf) {
while !(tokens[current].type == .openStatement && tokens[current + 1].type == .endIf) {
try alternate.append(parseAny())
}
}
Expand Down Expand Up @@ -425,20 +436,22 @@ func parse(tokens: [Token]) throws -> Program {
}

func not(_ types: TokenType...) -> Bool {
guard current+types.count <= tokens.count else {
guard current + types.count <= tokens.count else {
return false
}

return types.enumerated().contains { i, type -> Bool in
type != tokens[current+i].type
type != tokens[current + i].type
}
}

func parseForStatement() throws -> Statement {
let loopVariable = try parseExpressionSequence(primary: true)

if !(loopVariable is Identifier || loopVariable is TupleLiteral) {
throw JinjaError.syntaxError("Expected identifier/tuple for the loop variable, got \(loopVariable.type) instead")
throw JinjaError.syntaxError(
"Expected identifier/tuple for the loop variable, got \(loopVariable.type) instead"
)
}

try expect(type: .in, error: "Expected `in` keyword following loop variable")
Expand All @@ -456,7 +469,9 @@ func parse(tokens: [Token]) throws -> Program {
return For(loopvar: loopVariable, iterable: iterable as! Expression, body: body)
}

throw JinjaError.syntaxError("Expected identifier/tuple for the loop variable, got \(loopVariable.type) instead")
throw JinjaError.syntaxError(
"Expected identifier/tuple for the loop variable, got \(loopVariable.type) instead"
)
}

func parseJinjaStatement() throws -> Statement {
Expand Down
9 changes: 6 additions & 3 deletions Sources/Template.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@ public struct Template {

try env.set(name: "false", value: false)
try env.set(name: "true", value: true)
try env.set(name: "raise_exception", value: { (args: String) throws in
throw JinjaError.runtimeError("\(args)")
})
try env.set(
name: "raise_exception",
value: { (args: String) throws in
throw JinjaError.runtimeError("\(args)")
}
)
try env.set(name: "range", value: range)

for (key, value) in items {
Expand Down
3 changes: 2 additions & 1 deletion Sources/Utilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ func slice<T>(_ array: [T], start: Int? = nil, stop: Int? = nil, step: Int? = 1)
for i in stride(from: startIndex, to: stopIndex, by: step) {
slicedArray.append(array[i])
}
} else {
}
else {
let startIndex = startValue < 0 ? max(arrayCount + startValue, -1) : min(startValue, arrayCount - 1)
let stopIndex = stopValue < -1 ? max(arrayCount + stopValue, -1) : min(stopValue, arrayCount - 1)
for i in stride(from: startIndex, through: stopIndex, by: step) {
Expand Down
Loading

0 comments on commit c64b900

Please sign in to comment.