Skip to content

Commit

Permalink
Merge pull request #36 from kntkymt/feature/prefix-operator-node-sizeof
Browse files Browse the repository at this point in the history
CSTにsizeofのNodeを作る
  • Loading branch information
kntkymt authored Jan 22, 2024
2 parents 40aa815 + dea1ef1 commit a471da8
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 14 deletions.
6 changes: 6 additions & 0 deletions Sources/Generator/Generator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -591,6 +591,12 @@ public final class Generator {
} else {
throw GenerateError.invalidSyntax(location: node.sourceTokens[0].sourceRange.start)
}

case .sizeof:
// FIXME: どうやって式の型を推測する?
// 今はとりあえず固定で8
result += " mov x0, #8\n"
result += " str x0, [sp, #-16]!\n"
}

return result
Expand Down
6 changes: 6 additions & 0 deletions Sources/Parser/Node/ExpressionNode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ public class PrefixOperatorExpressionNode: NodeProtocol {

/// `&`
case address

/// `sizeof`
case sizeof
}

// MARK: - Property
Expand All @@ -62,6 +65,9 @@ public class PrefixOperatorExpressionNode: NodeProtocol {
case .reserved(.and):
return .address

case .keyword(.sizeof):
return .sizeof

default:
fatalError()
}
Expand Down
10 changes: 4 additions & 6 deletions Sources/Parser/Parser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -614,12 +614,10 @@ public final class Parser {

switch tokens[index].kind {
case .keyword(.sizeof):
try consumeKeywordToken(.sizeof)

_ = try unary()

// FIXME: どうやって式の型を判断する?
return IntegerLiteralNode(literal: TokenNode(token: Token(kind: .number("8"), sourceRange: SourceRange(start: .startOfFile, end: .startOfFile))))
return PrefixOperatorExpressionNode(
operator: try consumeKeywordToken(.sizeof),
expression: try unary()
)

case .reserved(.add):
return PrefixOperatorExpressionNode(
Expand Down
17 changes: 9 additions & 8 deletions Tests/ParserTest/OperatorsTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -373,17 +373,18 @@ final class OperatorsTest: XCTestCase {
)
let node = try Parser(tokens: tokens).stmt()

XCTAssertEqual(node.sourceTokens, tokens)

XCTAssertEqual(
node,
BlockItemNode(
item: IntegerLiteralNode(
literal: TokenNode(token: Token(
kind: .number("8"),
sourceRange: SourceRange(
start: SourceLocation(line: 1, column: 1),
end: SourceLocation(line: 1, column: 1)
)
))
item: PrefixOperatorExpressionNode(
operator: TokenNode(token: tokens[0]),
expression: TupleExpressionNode(
parenthesisLeft: TokenNode(token: tokens[1]),
expression: IntegerLiteralNode(literal: TokenNode(token: tokens[2])),
parenthesisRight: TokenNode(token: tokens[3])
)
),
semicolon: TokenNode(token: tokens[4])
)
Expand Down

0 comments on commit a471da8

Please sign in to comment.